code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/**
******************************************************************************
* @file stm32u5xx_hal_rcc.c
* @author MCD Application Team
* @brief RCC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Reset and Clock Control (RCC) peripheral:
* + Initialization and de-initialization functions
* + Peripheral Control functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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
==============================================================================
##### RCC specific features #####
==============================================================================
[..]
After reset the device is running from Multiple Speed Internal oscillator
(4 MHz) with Flash 0 wait state. Flash prefetch buffer, D-Cache
and I-Cache are disabled, and all peripherals are off except internal
SRAM, Flash and JTAG.
(+) There is no prescaler on High speed (AHBs) and Low speed (APBs) busses:
all peripherals mapped on these busses are running at MSI speed.
(+) The clock for all peripherals is switched off, except the SRAM and FLASH.
(+) All GPIOs are in analog mode, except the JTAG pins which
are assigned to be used for debug purpose.
[..]
Once the device started from reset, the user application has to:
(+) Configure the clock source to be used to drive the System clock
(if the application needs higher frequency/performance)
(+) Configure the System clock frequency and Flash settings
(+) Configure the AHB and APB busses prescalers
(+) Enable the clock for the peripheral(s) to be used
(+) Configure the clock source(s) for peripherals which clocks are not
derived from the System clock (SAIx, SYSTICK, RTC, ADC, USB OTG FS/SDMMC1/RNG)
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup RCC RCC
* @brief RCC HAL module driver
* @{
*/
#ifdef HAL_RCC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup RCC_Private_Constants RCC Private Constants
* @{
*/
#define PLLDIVR_RESET_VALUE (0x01010280U)
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RCC_Private_Macros
* @{
*/
#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \
(((__OSCILLATOR__) & ~RCC_OSCILLATORTYPE_ALL) == 0x00U))
#define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \
((__HSE__) == RCC_HSE_BYPASS) || ((__HSE__) == RCC_HSE_BYPASS_DIGITAL))
#define IS_RCC_LSE(__LSE__) (((__LSE__) == RCC_LSE_OFF) || ((__LSE__) == RCC_LSE_ON) || \
((__LSE__) == RCC_LSE_ON_RTC_ONLY) || ((__LSE__) == RCC_LSE_BYPASS_RTC_ONLY) || \
((__LSE__) == RCC_LSE_BYPASS))
#define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON))
#define IS_RCC_HSI_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= (uint32_t)( RCC_ICSCR3_HSITRIM >>\
RCC_ICSCR3_HSITRIM_Pos))
#define IS_RCC_LSI(__LSI__) (((__LSI__) == RCC_LSI_OFF) || ((__LSI__) == RCC_LSI_ON))
#define IS_RCC_LSIDIV(__LSIDIV__) (((__LSIDIV__) == RCC_LSI_DIV1) || ((__LSIDIV__) == RCC_LSI_DIV128))
#define IS_RCC_MSI(__MSI__) (((__MSI__) == RCC_MSI_OFF) || ((__MSI__) == RCC_MSI_ON))
#define IS_RCC_MSICALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= 255U)
#define IS_RCC_HSI48(__HSI48__) (((__HSI48__) == RCC_HSI48_OFF) || ((__HSI48__) == RCC_HSI48_ON))
#define IS_RCC_SHSI(__SHSI__) (((__SHSI__) == RCC_SHSI_OFF) || ((__SHSI__) == RCC_SHSI_ON))
#define IS_RCC_MSIK(__MSIK__) (((__MSIK__) == RCC_MSIK_OFF) || ((__MSIK__) == RCC_MSIK_ON))
#define IS_RCC_PLL(PLL) (((PLL) == RCC_PLL_NONE) ||((PLL) == RCC_PLL_OFF) || \
((PLL) == RCC_PLL_ON))
#define IS_RCC_PLLMBOOST_VALUE(VALUE) (((VALUE) == RCC_PLLMBOOST_DIV1) || \
((VALUE) == RCC_PLLMBOOST_DIV2) || \
((VALUE) == RCC_PLLMBOOST_DIV4) || \
((VALUE) == RCC_PLLMBOOST_DIV6) || \
((VALUE) == RCC_PLLMBOOST_DIV8) || \
((VALUE) == RCC_PLLMBOOST_DIV10) || \
((VALUE) == RCC_PLLMBOOST_DIV12) || \
((VALUE) == RCC_PLLMBOOST_DIV14) || \
((VALUE) == RCC_PLLMBOOST_DIV16))
#define IS_RCC_PLLCLOCKOUT_VALUE(VALUE) (((VALUE) == RCC_PLL1_DIVP) || \
((VALUE) == RCC_PLL1_DIVQ) || \
((VALUE) == RCC_PLL1_DIVR))
#define IS_RCC_PLLRGE_VALUE(VALUE) (((VALUE) == RCC_PLLVCIRANGE_0) || \
((VALUE) == RCC_PLLVCIRANGE_1))
#define IS_RCC_PLLFRACN_VALUE(VALUE) ((VALUE) <= 8191U)
#define IS_RCC_CLOCKTYPE(CLK) ((1U <= (CLK)) && ((CLK) <= 0x1FU))
#define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_MSI) || \
((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \
((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \
((__SOURCE__) == RCC_SYSCLKSOURCE_PLLCLK))
#define IS_RCC_HCLK(__HCLK__) (((__HCLK__) == RCC_SYSCLK_DIV1) || ((__HCLK__) == RCC_SYSCLK_DIV2) || \
((__HCLK__) == RCC_SYSCLK_DIV4) || ((__HCLK__) == RCC_SYSCLK_DIV8) || \
((__HCLK__) == RCC_SYSCLK_DIV16) || ((__HCLK__) == RCC_SYSCLK_DIV64) || \
((__HCLK__) == RCC_SYSCLK_DIV128) || ((__HCLK__) == RCC_SYSCLK_DIV256) || \
((__HCLK__) == RCC_SYSCLK_DIV512))
#define IS_RCC_PCLK(__PCLK__) (((__PCLK__) == RCC_HCLK_DIV1) || ((__PCLK__) == RCC_HCLK_DIV2) || \
((__PCLK__) == RCC_HCLK_DIV4) || ((__PCLK__) == RCC_HCLK_DIV8) || \
((__PCLK__) == RCC_HCLK_DIV16))
#define IS_RCC_MCO(__MCOX__) ((__MCOX__) == RCC_MCO1)
#define IS_RCC_MCO1SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO1SOURCE_NOCLOCK) || \
((__SOURCE__) == RCC_MCO1SOURCE_SYSCLK) || \
((__SOURCE__) == RCC_MCO1SOURCE_MSI) || \
((__SOURCE__) == RCC_MCO1SOURCE_HSI) || \
((__SOURCE__) == RCC_MCO1SOURCE_HSE) || \
((__SOURCE__) == RCC_MCO1SOURCE_PLL1CLK) || \
((__SOURCE__) == RCC_MCO1SOURCE_LSI) || \
((__SOURCE__) == RCC_MCO1SOURCE_LSE) || \
((__SOURCE__) == RCC_MCO1SOURCE_HSI48)|| \
((__SOURCE__) == RCC_MCO1SOURCE_MSIK))
#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))
#define IS_RCC_LSE_DRIVE(__DRIVE__) (((__DRIVE__) == RCC_LSEDRIVE_LOW) || \
((__DRIVE__) == RCC_LSEDRIVE_MEDIUMLOW) || \
((__DRIVE__) == RCC_LSEDRIVE_MEDIUMHIGH) || \
((__DRIVE__) == RCC_LSEDRIVE_HIGH))
#define IS_RCC_ITEM_ATTRIBUTES(ITEM) ((0U < (ITEM)) && ((ITEM) <= 0x1FFFU))
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
#define IS_RCC_ATTRIBUTES(ATTRIBUTES) (((ATTRIBUTES) == RCC_SEC_PRIV) || \
((ATTRIBUTES) == RCC_SEC_NPRIV) || \
((ATTRIBUTES) == RCC_NSEC_PRIV) || \
((ATTRIBUTES) == RCC_NSEC_NPRIV))
#else
#define IS_RCC_ATTRIBUTES(ATTRIBUTES) (((ATTRIBUTES) == RCC_NSEC_NPRIV) || ((ATTRIBUTES) == RCC_NSEC_PRIV))
#endif /* __ARM_FEATURE_CMSE */
/**
* @}
*/
/* Private define ------------------------------------------------------------*/
/** @defgroup RCC_Private_Constants RCC Private Constants
* @{
*/
#define LSI_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define HSI48_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define SHSI_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define MSIK_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define PLL_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define CLOCKSWITCH_TIMEOUT_VALUE 5000UL /* 5 s */
#define EPOD_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/** @defgroup RCC_Private_Macros RCC Private Macros
* @{
*/
#define MCO1_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
#define MCO1_GPIO_PORT GPIOA
#define MCO1_PIN GPIO_PIN_8
#define RCC_PLL_OSCSOURCE_CONFIG(__HAL_RCC_PLLSOURCE__) \
(MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, (uint32_t)(__HAL_RCC_PLLSOURCE__)))
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup RCC_Private_Functions RCC Private Functions
* @{
*/
static HAL_StatusTypeDef RCC_SetFlashLatencyFromMSIRange(uint32_t msirange);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup RCC_Exported_Functions RCC Exported Functions
* @{
*/
/** @defgroup RCC_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 configure the internal and external oscillators
(HSE, HSI, LSE, MSI, LSI, PLL, CSS and MCO) and the System busses clocks (SYSCLK, AHB, APB1
and APB2).
[..] Internal/external clock and PLL configuration
(+) HSI (high-speed internal): 16 MHz factory-trimmed RC used directly or through
the PLL as System clock source.
(+) MSI (Multiple Speed Internal): Its frequency is software trimmable from 100KHZ to 48MHZ.
It can be used to generate the clock for the USB OTG FS (48 MHz).
The number of flash wait states is automatically adjusted when MSI range is updated with
HAL_RCC_OscConfig() and the MSI is used as System clock source.
(+) LSI (low-speed internal): 32 KHz low consumption RC used as IWDG and/or RTC
clock source.
(+) HSE (high-speed external): 4 to 48 MHz crystal oscillator used directly or
through the PLL as System clock source. Can be used also optionally as RTC clock source.
(+) LSE (low-speed external): 32.768 KHz oscillator used optionally as RTC clock source.
(+) PLL (clocked by HSI, HSE or MSI) providing up to three independent output clocks:
(++) The first output is used to generate the high speed system clock (up to 80MHz).
(++) The second output is used to generate the clock for the USB OTG FS (48 MHz),
the random analog generator (<=48 MHz) and the SDMMC1 (<= 48 MHz).
(++) The third output is used to generate an accurate clock to achieve
high-quality audio performance on SAI interface.
(+) PLL2 (clocked by HSI, HSE or MSI) providing up to three independent output clocks:
(++) The first output is used to generate SAR ADC1 clock.
(++) The second output is used to generate the clock for the USB OTG FS (48 MHz),
the random analog generator (<=48 MHz) and the SDMMC1 (<= 48 MHz).
(++) The Third output is used to generate an accurate clock to achieve
high-quality audio performance on SAI interface.
(+) PLL3 (clocked by HSI , HSE or MSI) providing up to two independent output clocks:
(++) The first output is used to generate SAR ADC4 clock.
(++) The second output is used to generate an accurate clock to achieve
high-quality audio performance on SAI interface.
(+) CSS (Clock security system): once enabled, if a HSE clock failure occurs
(HSE used directly or through PLL as System clock source), the System clock
is automatically switched to HSI and an interrupt is generated if enabled.
The interrupt is linked to the Cortex-M4 NMI (Non-Maskable Interrupt)
exception vector.
(+) MCO (microcontroller clock output): used to output MSI, LSI, HSI, LSE, HSE or
main PLL clock (through a configurable prescaler) on PA8 pin.
[..] System, AHB and APB busses clocks configuration
(+) Several clock sources can be used to drive the System clock (SYSCLK): MSI, HSI,
HSE and main PLL.
The AHB clock (HCLK) is derived from System clock through configurable
prescaler and used to clock the CPU, memory and peripherals mapped
on AHB bus (DMA, GPIO...). APB1 (PCLK1) and APB2 (PCLK2) clocks are derived
from AHB clock through configurable prescalers and used to clock
the peripherals mapped on these busses. You can use
"HAL_RCC_GetSysClockFreq()" function to retrieve the frequencies of these clocks.
-@- All the peripheral clocks are derived from the System clock (SYSCLK) except:
(+@) SAI: the SAI clock can be derived either from a specific PLL (PLL2) or (PLL3) or
from an external clock mapped on the SAI_CKIN pin.
You have to use HAL_RCCEx_PeriphCLKConfig() function to configure this clock.
(+@) RTC: the RTC clock can be derived either from the LSI, LSE or HSE clock
divided by 2 to 31.
You have to use __HAL_RCC_RTC_ENABLE() and HAL_RCCEx_PeriphCLKConfig() function
to configure this clock.
(+@) USB OTG FS, SDMMC1 and RNG: USB OTG FS requires a frequency equal to 48 MHz
to work correctly, while the SDMMC1 and RNG peripherals require a frequency
equal or lower than to 48 MHz. This clock is derived of the main PLL or PLL2
through PLLQ divider. You have to enable the peripheral clock and use
HAL_RCCEx_PeriphCLKConfig() function to configure this clock.
(+@) IWDG clock which is always the LSI clock.
(+) The maximum frequency of the SYSCLK, HCLK, PCLK1 and PCLK2 is 80 MHz.
The clock source frequency should be adapted depending on the device voltage range
as listed in the Reference Manual "Clock source frequency versus voltage scaling" chapter.
@endverbatim
Table 1. HCLK clock frequency for STM32U5xx devices
+-------------------------------------------------------+----------------------------------------+
| Latency | HCLK clock frequency (MHz) 0.9V-1.2V |
| |-------------------------------------|---------------------+------------------|
| | voltage range 1 | voltage range 2 | voltage range 3 | voltage range 4 |
| | 1.1 V - 1.2V | 1.0 V - 1.1V | 0.9 V - 1.0V | 0.9V |
|-----------------|------------------|------------------|---------------------|------------------|
|0WS(1 CPU cycles)| 0 < HCLK <= 32 | 0 < HCLK <= 25 | 0 < HCLK <= 12.5 | 0 < HCLK <= 8 |
|-----------------|------------------|------------------|---------------------|------------------|
|1WS(2 CPU cycles)| 32 < HCLK <= 64 | 25 < HCLK <= 50 | 12.5 < HCLK <= 25 | 8 < HCLK <= 16 |
|-----------------|------------------|------------------|---------------------|------------------|
|2WS(3 CPU cycles)| 64 < HCLK <= 96 | 50 < HCLK <= 75 | 25 < HCLK <= 37.5 | 16 < HCLK <= 24 |
|-----------------|------------------|------------------|---------------------|------------------|
|3WS(4 CPU cycles)| 96 < HCLK <= 128 | 75 < HCLK <= 100 | 37.5 < HCLK <= 50 | - |
|-----------------|------------------|------------------|---------------------|------------------|
|4WS(5 CPU cycles)|128 < HCLK <= 160 | - | - | - |
+-----------------+------------------+------------------+---------------------+------------------+
* @{
*/
/**
* @brief Reset the RCC clock configuration to the default reset state.
* @note The default reset state of the clock configuration is given below:
* - MSI ON and used as system clock source
* - HSE, HSI, PLL, PLL2 and PLLISAI2 OFF
* - AHB, APB1 and APB2 prescaler set to 1
* - CSS, MCO1 OFF
* - All interrupts disabled
* - All interrupt and reset flags cleared
* @note This function doesn't modify the configuration of the
* - Peripheral clocks
* - LSI, LSE and RTC clocks
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCC_DeInit(void)
{
uint32_t tickstart;
/* Increasing the CPU frequency */
if (FLASH_LATENCY_DEFAULT > __HAL_FLASH_GET_LATENCY())
{
/* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
__HAL_FLASH_SET_LATENCY(FLASH_LATENCY_DEFAULT);
/* 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() != FLASH_LATENCY_DEFAULT)
{
return HAL_ERROR;
}
}
tickstart = HAL_GetTick();
/* Set MSION bit */
SET_BIT(RCC->CR, RCC_CR_MSISON);
/* Insure MSIRDY bit is set before writing default MSIRANGE value */
while (READ_BIT(RCC->CR, RCC_CR_MSISRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > MSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Set MSIRANGE default value */
MODIFY_REG(RCC->ICSCR1, RCC_ICSCR1_MSISRANGE, RCC_MSIRANGE_4);
/* Set MSITRIM default value */
WRITE_REG(RCC->ICSCR2, 0x00084210U);
/* Set MSIKRANGE default value */
MODIFY_REG(RCC->ICSCR1, RCC_ICSCR1_MSIKRANGE, RCC_MSIKRANGE_4);
/* Set MSIRGSEL default value */
MODIFY_REG(RCC->ICSCR1, RCC_ICSCR1_MSIRGSEL, 0x0U);
tickstart = HAL_GetTick();
/* Reset CFGR register (MSI is selected as system clock source) */
CLEAR_REG(RCC->CFGR1);
CLEAR_REG(RCC->CFGR2);
/* Wait till clock switch is ready */
while (READ_BIT(RCC->CFGR1, RCC_CFGR1_SWS) != 0U)
{
if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Reset MSIKON, HSECSSON , HSEON, HSEBYP, HSION, HSIKERON, PLL1ON, PLL2ON, PLL3ON bits */
CLEAR_BIT(RCC->CR, RCC_CR_MSIKON | RCC_CR_MSIPLLSEL | RCC_CR_MSIPLLFAST | RCC_CR_MSIKERON | RCC_CR_CSSON | \
RCC_CR_HSION | RCC_CR_HSIKERON | RCC_CR_PLL1ON | RCC_CR_PLL2ON | RCC_CR_PLL3ON | RCC_CR_HSI48ON | \
RCC_CR_HSEON | RCC_CR_SHSION);
/* Reset HSEBYP & HSEEXT bits */
CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP | RCC_CR_HSEEXT);
tickstart = HAL_GetTick();
/* Clear PLL1ON bit */
CLEAR_BIT(RCC->CR, RCC_CR_PLL1ON);
/* Wait till PLL1 is disabled */
while (READ_BIT(RCC->CR, RCC_CR_PLL1RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
tickstart = HAL_GetTick();
/* Reset PLL2N bit */
CLEAR_BIT(RCC->CR, RCC_CR_PLL2ON);
/* Wait till PLL2 is disabled */
while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
tickstart = HAL_GetTick();
/* Reset PLL3 bit */
CLEAR_BIT(RCC->CR, RCC_CR_PLL3ON);
/* Wait till PLL3 is disabled */
while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Reset PLL1CFGR register */
CLEAR_REG(RCC->PLL1CFGR);
/* Reset PLL1DIVR register */
WRITE_REG(RCC->PLL1DIVR, PLLDIVR_RESET_VALUE);
/* Reset PLL1FRACR register */
CLEAR_REG(RCC->PLL1FRACR);
/* Reset PLL2CFGR register */
CLEAR_REG(RCC->PLL2CFGR);
/* Reset PLL2DIVR register */
WRITE_REG(RCC->PLL2DIVR, PLLDIVR_RESET_VALUE);
/* Reset PLL2FRACR register */
CLEAR_REG(RCC->PLL2FRACR);
/* Reset PLL3CFGR register */
CLEAR_REG(RCC->PLL3CFGR);
/* Reset PLL3DIVR register */
WRITE_REG(RCC->PLL3DIVR, PLLDIVR_RESET_VALUE);
/* Reset PLL3FRACR register */
CLEAR_REG(RCC->PLL3FRACR);
/* Disable all interrupts */
CLEAR_REG(RCC->CIER);
/* Clear all interrupts flags */
WRITE_REG(RCC->CICR, 0xFFFFFFFFU);
/* Reset all CSR flags */
SET_BIT(RCC->CSR, RCC_CSR_RMVF);
/* Update the SystemCoreClock global variable */
SystemCoreClock = MSI_VALUE;
/* Decreasing the number of wait states because of lower CPU frequency */
if (FLASH_LATENCY_DEFAULT < __HAL_FLASH_GET_LATENCY())
{
/* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
__HAL_FLASH_SET_LATENCY(FLASH_LATENCY_DEFAULT);
/* 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() != FLASH_LATENCY_DEFAULT)
{
return HAL_ERROR;
}
}
/* Adapt Systick interrupt period */
return (HAL_InitTick(TICK_INT_PRIORITY));
}
/**
* @brief Initialize the RCC Oscillators according to the specified parameters in the
* RCC_OscInitTypeDef.
* @param pRCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
* contains the configuration information for the RCC Oscillators.
* @note The PLL is not disabled when used as system clock.
* @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not
* supported by this function. User should request a transition to LSE Off
* first and then LSE On or LSE Bypass.
* @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not
* supported by this function. User should request a transition to HSE Off
* first and then HSE On or HSE Bypass.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *pRCC_OscInitStruct)
{
uint32_t tickstart;
HAL_StatusTypeDef status;
uint32_t sysclk_source;
uint32_t pll_config;
FlagStatus pwrboosten = RESET;
uint32_t temp1_pllckcfg;
uint32_t temp2_pllckcfg;
/* Check Null pointer */
if (pRCC_OscInitStruct == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RCC_OSCILLATORTYPE(pRCC_OscInitStruct->OscillatorType));
sysclk_source = __HAL_RCC_GET_SYSCLK_SOURCE();
pll_config = __HAL_RCC_GET_PLL_OSCSOURCE();
/*----------------------------- MSI Configuration --------------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_MSI) == RCC_OSCILLATORTYPE_MSI)
{
/* Check the parameters */
assert_param(IS_RCC_MSI(pRCC_OscInitStruct->MSIState));
assert_param(IS_RCC_MSICALIBRATION_VALUE(pRCC_OscInitStruct->MSICalibrationValue));
assert_param(IS_RCC_MSI_CLOCK_RANGE(pRCC_OscInitStruct->MSIClockRange));
/*Check if MSI is used as system clock or as PLL source when PLL is selected as system clock*/
if ((sysclk_source == RCC_SYSCLKSOURCE_STATUS_MSI) ||
((sysclk_source == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (pll_config == RCC_PLLSOURCE_MSI)))
{
if ((READ_BIT(RCC->CR, RCC_CR_MSISRDY) != 0U) && (pRCC_OscInitStruct->MSIState == RCC_MSI_OFF))
{
return HAL_ERROR;
}
/* Otherwise, just the calibration and MSI range change are allowed */
else
{
/* To correctly read data from FLASH memory, the number of wait states (LATENCY)
must be correctly programmed according to the frequency of the CPU clock
(HCLK) and the supply voltage of the device */
if (pRCC_OscInitStruct->MSIClockRange > __HAL_RCC_GET_MSI_RANGE())
{
/* Decrease number of wait states update if necessary */
/* Only possible when MSI is the System clock source */
if (sysclk_source == RCC_SYSCLKSOURCE_STATUS_MSI)
{
if (RCC_SetFlashLatencyFromMSIRange(pRCC_OscInitStruct->MSIClockRange) != HAL_OK)
{
return HAL_ERROR;
}
}
/* Selects the Multiple Speed oscillator (MSI) clock range */
__HAL_RCC_MSI_RANGE_CONFIG(pRCC_OscInitStruct->MSIClockRange);
/* Adjusts the Multiple Speed oscillator (MSI) calibration value */
__HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST((pRCC_OscInitStruct->MSICalibrationValue), \
(pRCC_OscInitStruct->MSIClockRange));
}
else
{
/* Else, keep current flash latency while decreasing applies */
/* Selects the Multiple Speed oscillator (MSI) clock range */
__HAL_RCC_MSI_RANGE_CONFIG(pRCC_OscInitStruct->MSIClockRange);
/* Adjusts the Multiple Speed oscillator (MSI) calibration value */
__HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST((pRCC_OscInitStruct->MSICalibrationValue), \
(pRCC_OscInitStruct->MSIClockRange));
if (sysclk_source == RCC_SYSCLKSOURCE_STATUS_MSI)
{
if (RCC_SetFlashLatencyFromMSIRange(pRCC_OscInitStruct->MSIClockRange) != HAL_OK)
{
return HAL_ERROR;
}
}
}
/* Update the SystemCoreClock global variable */
(void) HAL_RCC_GetHCLKFreq();
/* Configure the source of time base considering new system clocks settings*/
status = HAL_InitTick(uwTickPrio);
if (status != HAL_OK)
{
return status;
}
}
}
else
{
/* Check the MSI State */
if (pRCC_OscInitStruct->MSIState != RCC_MSI_OFF)
{
/* Enable the Internal High Speed oscillator (MSI) */
__HAL_RCC_MSI_ENABLE();
tickstart = HAL_GetTick();
/* Wait till MSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_MSISRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > MSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Selects the Multiple Speed oscillator (MSI) clock range */
__HAL_RCC_MSI_RANGE_CONFIG(pRCC_OscInitStruct->MSIClockRange);
/* Adjusts the Multiple Speed oscillator (MSI) calibration value */
__HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST((pRCC_OscInitStruct->MSICalibrationValue), \
(pRCC_OscInitStruct->MSIClockRange));
}
else
{
/* Disable the Internal High Speed oscillator (MSI) */
__HAL_RCC_MSI_DISABLE();
tickstart = HAL_GetTick();
/* Wait till MSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_MSISRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > MSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
}
/*------------------------------- HSE Configuration ------------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE)
{
/* Check the parameters */
assert_param(IS_RCC_HSE(pRCC_OscInitStruct->HSEState));
/* When the HSE is used as system clock or clock source for PLL in these cases it is not allowed to be disabled */
if ((sysclk_source == RCC_SYSCLKSOURCE_STATUS_HSE) ||
((sysclk_source == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (pll_config == RCC_PLLSOURCE_HSE)))
{
if ((READ_BIT(RCC->CR, RCC_CR_HSERDY) != 0U) && (pRCC_OscInitStruct->HSEState == RCC_HSE_OFF))
{
return HAL_ERROR;
}
}
else
{
/* Set the new HSE configuration ---------------------------------------*/
__HAL_RCC_HSE_CONFIG(pRCC_OscInitStruct->HSEState);
/* Check the HSE State */
if (pRCC_OscInitStruct->HSEState != RCC_HSE_OFF)
{
tickstart = HAL_GetTick();
/* Wait till HSE is ready */
while (READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
tickstart = HAL_GetTick();
/* Wait till HSE is disabled */
while (READ_BIT(RCC->CR, RCC_CR_HSERDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
}
/*----------------------------- HSI Configuration --------------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
{
/* Check the parameters */
assert_param(IS_RCC_HSI(pRCC_OscInitStruct->HSIState));
assert_param(IS_RCC_HSI_CALIBRATION_VALUE(pRCC_OscInitStruct->HSICalibrationValue));
/* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */
if ((sysclk_source == RCC_SYSCLKSOURCE_STATUS_HSI) ||
((sysclk_source == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (pll_config == RCC_PLLSOURCE_HSI)))
{
/* When HSI is used as system clock it will not be disabled */
if ((READ_BIT(RCC->CR, RCC_CR_HSIRDY) != 0U) && (pRCC_OscInitStruct->HSIState == RCC_HSI_OFF))
{
return HAL_ERROR;
}
/* Otherwise, just the calibration is allowed */
else
{
/* Adjusts the Internal High Speed oscillator (HSI) calibration value */
__HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(pRCC_OscInitStruct->HSICalibrationValue);
}
}
else
{
/* Check the HSI State */
if (pRCC_OscInitStruct->HSIState != RCC_HSI_OFF)
{
/* Enable the Internal High Speed oscillator (HSI) */
__HAL_RCC_HSI_ENABLE();
tickstart = HAL_GetTick();
/* Wait till HSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Adjusts the Internal High Speed oscillator (HSI) calibration value */
__HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(pRCC_OscInitStruct->HSICalibrationValue);
}
else
{
/* Disable the Internal High Speed oscillator (HSI) */
__HAL_RCC_HSI_DISABLE();
tickstart = HAL_GetTick();
/* Wait till HSI is disabled */
while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
}
/*------------------------------ LSI Configuration -------------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI)
{
/* Check the parameters */
assert_param(IS_RCC_LSI(pRCC_OscInitStruct->LSIState));
FlagStatus pwrclkchanged = RESET;
/* Update LSI configuration in Backup Domain control register */
/* Requires to enable write access to Backup Domain of necessary */
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
if (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
/* Enable write access to Backup domain */
SET_BIT(PWR->DBPR, PWR_DBPR_DBP);
/* Wait for Backup domain Write protection disable */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
/* Check the LSI State */
if (pRCC_OscInitStruct->LSIState != RCC_LSI_OFF)
{
uint32_t bdcr_temp = RCC->BDCR;
/* Check LSI division factor */
assert_param(IS_RCC_LSIDIV(pRCC_OscInitStruct->LSIDiv));
if (pRCC_OscInitStruct->LSIDiv != (bdcr_temp & RCC_BDCR_LSIPREDIV))
{
if (((bdcr_temp & RCC_BDCR_LSIRDY) == RCC_BDCR_LSIRDY) && \
((bdcr_temp & RCC_BDCR_LSION) != RCC_BDCR_LSION))
{
/* If LSIRDY is set while LSION is not enabled, LSIPREDIV can't be updated */
/* The LSIPREDIV cannot be changed if the LSI is used by the IWDG or by the RTC */
return HAL_ERROR;
}
/* Turn off LSI before changing RCC_BDCR_LSIPREDIV */
if ((bdcr_temp & RCC_BDCR_LSION) == RCC_BDCR_LSION)
{
__HAL_RCC_LSI_DISABLE();
tickstart = HAL_GetTick();
/* Wait till LSI is disabled */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSIRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
/* Set LSI division factor */
MODIFY_REG(RCC->BDCR, RCC_BDCR_LSIPREDIV, pRCC_OscInitStruct->LSIDiv);
}
/* Enable the Internal Low Speed oscillator (LSI) */
__HAL_RCC_LSI_ENABLE();
tickstart = HAL_GetTick();
/* Wait till LSI is ready */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSIRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Disable the Internal Low Speed oscillator (LSI) */
__HAL_RCC_LSI_DISABLE();
tickstart = HAL_GetTick();
/* Wait till LSI is disabled */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSIRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
/* Restore clock configuration if changed */
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
}
/*------------------------------ LSE Configuration -------------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)
{
FlagStatus pwrclkchanged = RESET;
/* Check the parameters */
assert_param(IS_RCC_LSE(pRCC_OscInitStruct->LSEState));
/* 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())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
if (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
/* Enable write access to Backup domain */
SET_BIT(PWR->DBPR, PWR_DBPR_DBP);
/* Wait for Backup domain Write protection disable */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
/* Set the new LSE configuration -----------------------------------------*/
if ((pRCC_OscInitStruct->LSEState & RCC_BDCR_LSEON) != 0U)
{
if ((pRCC_OscInitStruct->LSEState & RCC_BDCR_LSEBYP) != 0U)
{
/* LSE oscillator bypass enable */
SET_BIT(RCC->BDCR, RCC_BDCR_LSEBYP);
SET_BIT(RCC->BDCR, RCC_BDCR_LSEON);
}
else
{
/* LSE oscillator enable */
SET_BIT(RCC->BDCR, RCC_BDCR_LSEON);
}
}
else
{
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON);
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP);
}
/* Check the LSE State */
if (pRCC_OscInitStruct->LSEState != RCC_LSE_OFF)
{
tickstart = HAL_GetTick();
/* Wait till LSE is ready */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Enable LSESYS additionally if requested */
if ((pRCC_OscInitStruct->LSEState & RCC_BDCR_LSESYSEN) != 0U)
{
SET_BIT(RCC->BDCR, RCC_BDCR_LSESYSEN);
/* Wait till LSESYS is ready */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSESYSRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Make sure LSESYSEN/LSESYSRDY are reset */
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSESYSEN);
/* Wait till LSESYSRDY is cleared */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSESYSRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
else
{
tickstart = HAL_GetTick();
/* Wait till LSE is disabled */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
if (READ_BIT(RCC->BDCR, RCC_BDCR_LSESYSEN) != 0U)
{
/* Reset LSESYSEN once LSE is disabled */
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSESYSEN);
/* Wait till LSESYSRDY is cleared */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSESYSRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
/* Restore clock configuration if changed */
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
}
/*------------------------------ HSI48 Configuration -----------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48)
{
/* Check the parameters */
assert_param(IS_RCC_HSI48(pRCC_OscInitStruct->HSI48State));
/* Check the HSI48 State */
if (pRCC_OscInitStruct->HSI48State != RCC_HSI48_OFF)
{
/* Enable the Internal High Speed oscillator (HSI48) */
__HAL_RCC_HSI48_ENABLE();
tickstart = HAL_GetTick();
/* Wait till HSI48 is ready */
while (READ_BIT(RCC->CR, RCC_CR_HSI48RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Disable the Internal High Speed oscillator (HSI48) */
__HAL_RCC_HSI48_DISABLE();
tickstart = HAL_GetTick();
/* Wait till HSI48 is disabled */
while (READ_BIT(RCC->CR, RCC_CR_HSI48RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
/*------------------------------ SHSI Configuration -----------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_SHSI) == RCC_OSCILLATORTYPE_SHSI)
{
/* Check the parameters */
assert_param(IS_RCC_SHSI(pRCC_OscInitStruct->SHSIState));
/* Check the SHSI State */
if (pRCC_OscInitStruct->SHSIState != RCC_SHSI_OFF)
{
/* Enable the Secure Internal High Speed oscillator (SHSI) */
__HAL_RCC_SHSI_ENABLE();
tickstart = HAL_GetTick();
/* Wait till SHSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_SHSIRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > SHSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Disable the Secure Internal High Speed oscillator (SHSI) */
__HAL_RCC_SHSI_DISABLE();
tickstart = HAL_GetTick();
/* Wait till SHSI is disabled */
while (READ_BIT(RCC->CR, RCC_CR_SHSIRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > SHSI_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
/*------------------------------ MSIK Configuration -----------------------*/
if (((pRCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_MSIK) == RCC_OSCILLATORTYPE_MSIK)
{
/* Check the parameters */
assert_param(IS_RCC_MSIK(pRCC_OscInitStruct->MSIKState));
assert_param(IS_RCC_MSIK_CLOCK_RANGE(pRCC_OscInitStruct->MSIKClockRange));
assert_param(IS_RCC_MSICALIBRATION_VALUE(pRCC_OscInitStruct->MSICalibrationValue));
/* Check the MSIK State */
if (pRCC_OscInitStruct->MSIKState != RCC_MSIK_OFF)
{
/* Selects the Multiple Speed of kernel high speed oscillator (MSIK) clock range .*/
__HAL_RCC_MSIK_RANGE_CONFIG(pRCC_OscInitStruct->MSIKClockRange);
/* Adjusts the Multiple Speed of kernel high speed oscillator (MSIK) calibration value.*/
__HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST((pRCC_OscInitStruct->MSICalibrationValue), \
(pRCC_OscInitStruct->MSIClockRange));
/* Enable the Internal kernel High Speed oscillator (MSIK) */
__HAL_RCC_MSIK_ENABLE();
tickstart = HAL_GetTick();
/* Wait till MSIK is ready */
while (READ_BIT(RCC->CR, RCC_CR_MSIKRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > MSIK_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Disable the Internal High Speed Kernel oscillator (MSIK) */
__HAL_RCC_MSIK_DISABLE();
tickstart = HAL_GetTick();
/* Wait till MSIK is disabled */
while (READ_BIT(RCC->CR, RCC_CR_MSIKRDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > MSIK_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
/*-------------------------------- PLL Configuration -----------------------*/
/* Check the parameters */
assert_param(IS_RCC_PLL(pRCC_OscInitStruct->PLL.PLLState));
if ((pRCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE)
{
FlagStatus pwrclkchanged = RESET;
/* Check if the PLL is used as system clock or not */
if (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK)
{
if ((pRCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON)
{
/* Check the parameters */
assert_param(IS_RCC_PLLMBOOST_VALUE(pRCC_OscInitStruct->PLL.PLLMBOOST));
assert_param(IS_RCC_PLLSOURCE(pRCC_OscInitStruct->PLL.PLLSource));
assert_param(IS_RCC_PLLM_VALUE(pRCC_OscInitStruct->PLL.PLLM));
assert_param(IS_RCC_PLLN_VALUE(pRCC_OscInitStruct->PLL.PLLN));
assert_param(IS_RCC_PLLP_VALUE(pRCC_OscInitStruct->PLL.PLLP));
assert_param(IS_RCC_PLLQ_VALUE(pRCC_OscInitStruct->PLL.PLLQ));
assert_param(IS_RCC_PLLR_VALUE(pRCC_OscInitStruct->PLL.PLLR));
/* Disable the main PLL */
__HAL_RCC_PLL_DISABLE();
tickstart = HAL_GetTick();
/* Wait till PLL is disabled */
while (READ_BIT(RCC->CR, RCC_CR_PLL1RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Requires to enable write access to Backup Domain of necessary */
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
/*Disable EPOD to configure PLL1MBOOST*/
if (READ_BIT(PWR->VOSR, PWR_VOSR_BOOSTEN) == PWR_VOSR_BOOSTEN)
{
pwrboosten = SET;
}
CLEAR_BIT(PWR->VOSR, PWR_VOSR_BOOSTEN);
/* Configure the main PLL clock source, multiplication and division factors */
__HAL_RCC_PLL_CONFIG(pRCC_OscInitStruct->PLL.PLLSource,
pRCC_OscInitStruct->PLL.PLLMBOOST,
pRCC_OscInitStruct->PLL.PLLM,
pRCC_OscInitStruct->PLL.PLLN,
pRCC_OscInitStruct->PLL.PLLP,
pRCC_OscInitStruct->PLL.PLLQ,
pRCC_OscInitStruct->PLL.PLLR);
assert_param(IS_RCC_PLLFRACN_VALUE(pRCC_OscInitStruct->PLL.PLLFRACN));
/* Disable PLL1FRACN */
__HAL_RCC_PLLFRACN_DISABLE();
/* Configure PLL PLL1FRACN */
__HAL_RCC_PLLFRACN_CONFIG(pRCC_OscInitStruct->PLL.PLLFRACN);
/* Enable PLL1FRACN */
__HAL_RCC_PLLFRACN_ENABLE();
assert_param(IS_RCC_PLLRGE_VALUE(pRCC_OscInitStruct->PLL.PLLRGE));
/* Select PLL1 input reference frequency range: VCI */
__HAL_RCC_PLL_VCIRANGE(pRCC_OscInitStruct->PLL.PLLRGE);
if (pwrboosten == SET)
{
/* Enable the EPOD to reach max frequency */
SET_BIT(PWR->VOSR, PWR_VOSR_BOOSTEN);
}
/* Restore clock configuration if changed */
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
/* Enable PLL System Clock output */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVR);
/* Enable the main PLL */
__HAL_RCC_PLL_ENABLE();
tickstart = HAL_GetTick();
/* Wait till PLL is ready */
while (READ_BIT(RCC->CR, RCC_CR_PLL1RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
/* Disable the main PLL */
__HAL_RCC_PLL_DISABLE();
tickstart = HAL_GetTick();
/* Wait till PLL is disabled */
while (READ_BIT(RCC->CR, RCC_CR_PLL1RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Unselect main PLL clock source and disable main PLL outputs to save power */
RCC->PLL1CFGR &= ~(RCC_PLL1CFGR_PLL1SRC | RCC_PLL1CFGR_PLL1PEN | RCC_PLL1CFGR_PLL1QEN | RCC_PLL1CFGR_PLL1REN);
}
}
else
{
/* Do not return HAL_ERROR if request repeats the current configuration */
temp1_pllckcfg = RCC->PLL1CFGR;
temp2_pllckcfg = RCC->PLL1DIVR;
if (((pRCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) ||
(READ_BIT(temp1_pllckcfg, RCC_PLL1CFGR_PLL1SRC) != pRCC_OscInitStruct->PLL.PLLSource) ||
((READ_BIT(temp1_pllckcfg, RCC_PLL1CFGR_PLL1M) >> \
RCC_PLL1CFGR_PLL1M_Pos) != (pRCC_OscInitStruct->PLL.PLLM - 1U)) ||
((READ_BIT(temp1_pllckcfg, RCC_PLL1CFGR_PLL1MBOOST) >> \
RCC_PLL1CFGR_PLL1MBOOST_Pos) != pRCC_OscInitStruct->PLL.PLLMBOOST) ||
(READ_BIT(temp2_pllckcfg, RCC_PLL1DIVR_PLL1N) != (pRCC_OscInitStruct->PLL.PLLN - 1U)) ||
((READ_BIT(temp2_pllckcfg, RCC_PLL1DIVR_PLL1P) >> \
RCC_PLL1DIVR_PLL1P_Pos) != (pRCC_OscInitStruct->PLL.PLLP - 1U)) ||
((READ_BIT(temp2_pllckcfg, RCC_PLL1DIVR_PLL1Q) >> \
RCC_PLL1DIVR_PLL1Q_Pos) != (pRCC_OscInitStruct->PLL.PLLQ - 1U)) ||
((READ_BIT(temp2_pllckcfg, RCC_PLL1DIVR_PLL1R) >> \
RCC_PLL1DIVR_PLL1R_Pos) != (pRCC_OscInitStruct->PLL.PLLR - 1U)))
{
return HAL_ERROR;
}
}
}
return HAL_OK;
}
/**
* @brief Initialize the CPU, AHB and APB busses clocks according to the specified
* parameters in the pRCC_ClkInitStruct.
* @param pRCC_ClkInitStruct pointer to an RCC_OscInitTypeDef structure that
* contains the configuration information for the RCC peripheral.
* @param FLatency FLASH Latency
* This parameter can be one of the following values:
* @arg FLASH_LATENCY_0 FLASH 0 Latency cycle
* @arg FLASH_LATENCY_1 FLASH 1 Latency cycle
* @arg FLASH_LATENCY_2 FLASH 2 Latency cycles
* @arg FLASH_LATENCY_3 FLASH 3 Latency cycles
* @arg FLASH_LATENCY_4 FLASH 4 Latency cycles
* @arg FLASH_LATENCY_5 FLASH 5 Latency cycles
*
* @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
* and updated by HAL_RCC_GetHCLKFreq() function called within this function
*
* @note The MSI is used by default as system clock source after
* startup from Reset, wake-up from STANDBY mode. After restart from Reset,
* the MSI frequency is set to its default value 4 MHz.
* @note The HSI can be selected as system clock source after wakeup
* from STOP modes or in case of failure of the HSE used directly or indirectly
* as system clock (if the Clock Security System CSS is enabled).
* @note A switch from one clock source to another occurs only if the target
* clock source is ready (clock stable after startup delay or PLL locked).
* If a clock source which is not yet ready is selected, the switch will
* occur when the clock source is ready.
* @note You can use HAL_RCC_GetClockConfig() function to know which clock is
* currently used as system clock source.
*
* @note Depending on the device voltage range, the software has to set correctly
* HPRE[3:0] bits to ensure that HCLK not exceed the maximum allowed frequency
* (for more details refer to section above "Initialization/de-initialization functions")
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *const pRCC_ClkInitStruct, uint32_t FLatency)
{
HAL_StatusTypeDef status;
uint32_t tickstart;
/* Check Null pointer */
if (pRCC_ClkInitStruct == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RCC_CLOCKTYPE(pRCC_ClkInitStruct->ClockType));
assert_param(IS_FLASH_LATENCY(FLatency));
/* To correctly read data from FLASH memory, the number of wait states (LATENCY)
must be correctly programmed according to the frequency of the CPU clock
(HCLK) and the supply voltage of the device */
/* Increasing the number of wait states because of higher CPU frequency */
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)
{
return HAL_ERROR;
}
}
/* Increasing the BUS frequency divider */
/*-------------------------- PCLK3 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK3) == RCC_CLOCKTYPE_PCLK3)
{
if ((pRCC_ClkInitStruct->APB3CLKDivider) > (RCC->CFGR3 & RCC_CFGR3_PPRE3))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB3CLKDivider));
MODIFY_REG(RCC->CFGR3, RCC_CFGR3_PPRE3, pRCC_ClkInitStruct->APB3CLKDivider);
}
}
/*-------------------------- PCLK2 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)
{
if ((pRCC_ClkInitStruct->APB2CLKDivider) > ((RCC->CFGR2 & RCC_CFGR2_PPRE2) >> 4))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB2CLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PPRE2, ((pRCC_ClkInitStruct->APB2CLKDivider) << 4));
}
}
/*-------------------------- PCLK1 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)
{
if ((pRCC_ClkInitStruct->APB1CLKDivider) > (RCC->CFGR2 & RCC_CFGR2_PPRE1))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB1CLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PPRE1, pRCC_ClkInitStruct->APB1CLKDivider);
}
}
/*-------------------------- HCLK Configuration --------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK)
{
if ((pRCC_ClkInitStruct->AHBCLKDivider) > (RCC->CFGR2 & RCC_CFGR2_HPRE))
{
assert_param(IS_RCC_HCLK(pRCC_ClkInitStruct->AHBCLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_HPRE, pRCC_ClkInitStruct->AHBCLKDivider);
}
}
/*------------------------- SYSCLK Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK)
{
assert_param(IS_RCC_SYSCLKSOURCE(pRCC_ClkInitStruct->SYSCLKSource));
FlagStatus pwrclkchanged = RESET;
/* PLL is selected as System Clock Source */
if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
{
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
tickstart = HAL_GetTick();
/* Check if EPOD is enabled */
if (READ_BIT(PWR->VOSR, PWR_VOSR_BOOSTEN) != 0U)
{
/* Wait till BOOST is ready */
while (READ_BIT(PWR->VOSR, PWR_VOSR_BOOSTRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > EPOD_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
/* Restore clock configuration if changed */
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
/* Check the PLL ready flag */
if (READ_BIT(RCC->CR, RCC_CR_PLL1RDY) == 0U)
{
return HAL_ERROR;
}
}
else
{
/* HSE is selected as System Clock Source */
if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
{
/* Check the HSE ready flag */
if (READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U)
{
return HAL_ERROR;
}
}
/* MSI is selected as System Clock Source */
else if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI)
{
/* Check the MSI ready flag */
if (READ_BIT(RCC->CR, RCC_CR_MSISRDY) == 0U)
{
return HAL_ERROR;
}
}
/* HSI is selected as System Clock Source */
else
{
/* Check the HSI ready flag */
if (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U)
{
return HAL_ERROR;
}
}
}
MODIFY_REG(RCC->CFGR1, RCC_CFGR1_SW, pRCC_ClkInitStruct->SYSCLKSource);
tickstart = HAL_GetTick();
if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
{
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK)
{
if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
{
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSE)
{
if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else if (pRCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI)
{
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_MSI)
{
if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
else
{
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI)
{
if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
}
}
/* Decreasing the BUS frequency divider */
/*-------------------------- HCLK Configuration --------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK)
{
if ((pRCC_ClkInitStruct->AHBCLKDivider) < (RCC->CFGR2 & RCC_CFGR2_HPRE))
{
assert_param(IS_RCC_HCLK(pRCC_ClkInitStruct->AHBCLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_HPRE, pRCC_ClkInitStruct->AHBCLKDivider);
}
}
/* Decreasing the number of wait states because of lower CPU frequency */
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)
{
return HAL_ERROR;
}
}
/*-------------------------- PCLK1 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)
{
if ((pRCC_ClkInitStruct->APB1CLKDivider) < (RCC->CFGR2 & RCC_CFGR2_PPRE1))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB1CLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PPRE1, pRCC_ClkInitStruct->APB1CLKDivider);
}
}
/*-------------------------- PCLK2 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)
{
if ((pRCC_ClkInitStruct->APB2CLKDivider) < ((RCC->CFGR2 & RCC_CFGR2_PPRE2) >> 4))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB2CLKDivider));
MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PPRE2, ((pRCC_ClkInitStruct->APB2CLKDivider) << 4));
}
}
/*-------------------------- PCLK3 Configuration ---------------------------*/
if (((pRCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK3) == RCC_CLOCKTYPE_PCLK3)
{
if ((pRCC_ClkInitStruct->APB3CLKDivider) < (RCC->CFGR3 & RCC_CFGR3_PPRE3))
{
assert_param(IS_RCC_PCLK(pRCC_ClkInitStruct->APB3CLKDivider));
MODIFY_REG(RCC->CFGR3, RCC_CFGR3_PPRE3, (pRCC_ClkInitStruct->APB3CLKDivider));
}
}
/* Update the SystemCoreClock global variable */
SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR2 & RCC_CFGR2_HPRE) >> RCC_CFGR2_HPRE_Pos];
/* Configure the source of time base considering new system clocks settings*/
status = HAL_InitTick(uwTickPrio);
return status;
}
/**
* @}
*/
/** @defgroup RCC_Exported_Functions_Group2 Peripheral Control functions
* @brief RCC clocks control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to:
(+) Output clock to MCO pin.
(+) Retrieve current clock frequencies.
(+) Enable the Clock Security System.
@endverbatim
* @{
*/
/**
* @brief Select the clock source to output on MCO pin(PA8).
* @note PA8 should be configured in alternate function mode.
* @param RCC_MCOx specifies the output direction for the clock source.
* For STM32U5xx family this parameter can have only one value:
* @arg @ref RCC_MCO1 Clock source to output on MCO1 pin(PA8).
* @param RCC_MCOSource specifies the clock source to output.
* This parameter can be one of the following values:
* @arg @ref RCC_MCO1SOURCE_NOCLOCK MCO output disabled, no clock on MCO
* @arg @ref RCC_MCO1SOURCE_SYSCLK system clock selected as MCO source
* @arg @ref RCC_MCO1SOURCE_MSI MSI clock selected as MCO source
* @arg @ref RCC_MCO1SOURCE_HSI HSI clock selected as MCO source
* @arg @ref RCC_MCO1SOURCE_HSE HSE clock selected as MCO sourcee
* @arg @ref RCC_MCO1SOURCE_PLL1CLK main PLL 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 RCC_MCODiv specifies the MCO prescaler.
* This parameter can be one of the following values:
* @arg @ref RCC_MCODIV_1 no division applied to MCO clock
* @arg @ref RCC_MCODIV_2 division by 2 applied to MCO clock
* @arg @ref RCC_MCODIV_4 division by 4 applied to MCO clock
* @arg @ref RCC_MCODIV_8 division by 8 applied to MCO clock
* @arg @ref RCC_MCODIV_16 division by 16 applied to MCO clock
* @retval None
*/
void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv)
{
GPIO_InitTypeDef gpio_initstruct;
/* Check the parameters */
assert_param(IS_RCC_MCO(RCC_MCOx));
assert_param(IS_RCC_MCODIV(RCC_MCODiv));
assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource));
/* MCO Clock Enable */
MCO1_CLK_ENABLE();
/* Configure the MCO1 pin in alternate function mode */
gpio_initstruct.Pin = MCO1_PIN;
gpio_initstruct.Mode = GPIO_MODE_AF_PP;
gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_initstruct.Pull = GPIO_NOPULL;
gpio_initstruct.Alternate = GPIO_AF0_MCO;
HAL_GPIO_Init(MCO1_GPIO_PORT, &gpio_initstruct);
/* Mask MCOSEL[] and MCOPRE[] bits then set MCO1 clock source and prescaler */
MODIFY_REG(RCC->CFGR1, (RCC_CFGR1_MCOSEL | RCC_CFGR1_MCOPRE), (RCC_MCOSource | RCC_MCODiv));
}
/**
* @brief Return the SYSCLK frequency.
* @note The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
* @note If SYSCLK source is MSI, function returns values based on MSI
* Value as defined by the MSI range.
* @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*)
* @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(**)
* @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(**),
* HSI_VALUE(*) or MSI Value multiplied/divided by the PLL factors.
* @note (*) HSI_VALUE is a constant defined in stm32u5xx_hal_conf.h file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
* @note (**) HSE_VALUE is a constant defined in stm32u5xx_hal_conf.h file (default value
* 8 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
* @note The result of this function could be not correct when using fractional
* value for HSE crystal.
* @note This function can be used by the user application to compute the
* baudrate for the communication peripherals or configure other parameters.
* @note Each time SYSCLK changes, this function must be called to update the
* right SYSCLK value. Otherwise, any configuration based on this function will be incorrect.
* @retval SYSCLK frequency
*/
uint32_t HAL_RCC_GetSysClockFreq(void)
{
uint32_t msirange = 0U;
uint32_t pllsource;
uint32_t pllr;
uint32_t pllm;
uint32_t pllfracen;
uint32_t sysclockfreq = 0U;
uint32_t sysclk_source;
uint32_t pll_oscsource;
float_t fracn1;
float_t pllvco;
sysclk_source = __HAL_RCC_GET_SYSCLK_SOURCE();
pll_oscsource = __HAL_RCC_GET_PLL_OSCSOURCE();
if ((sysclk_source == RCC_SYSCLKSOURCE_STATUS_MSI) ||
((sysclk_source == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (pll_oscsource == RCC_PLLSOURCE_MSI)))
{
/* MSI or PLL with MSI source used as system clock source */
/* Get SYSCLK source */
if (READ_BIT(RCC->ICSCR1, RCC_ICSCR1_MSIRGSEL) == 0U)
{
/* MSISRANGE from RCC_CSR applies */
msirange = (RCC->CSR & RCC_CSR_MSISSRANGE) >> RCC_CSR_MSISSRANGE_Pos;
}
else
{
/* MSIRANGE from RCC_CR applies */
msirange = (RCC->ICSCR1 & RCC_ICSCR1_MSISRANGE) >> RCC_ICSCR1_MSISRANGE_Pos;
}
/*MSI frequency range in HZ*/
msirange = MSIRangeTable[msirange];
if (sysclk_source == RCC_SYSCLKSOURCE_STATUS_MSI)
{
/* MSI used as system clock source */
sysclockfreq = msirange;
}
}
else if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI)
{
/* HSI used as system clock source */
sysclockfreq = HSI_VALUE;
}
else if (sysclk_source == RCC_SYSCLKSOURCE_STATUS_HSE)
{
/* HSE used as system clock source */
sysclockfreq = HSE_VALUE;
}
else
{
/* Nothing to do */
}
if (sysclk_source == RCC_SYSCLKSOURCE_STATUS_PLLCLK)
{
/* PLL used as system clock source
PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = (RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1SRC);
pllm = ((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1M) >> RCC_PLL1CFGR_PLL1M_Pos) + 1U;
pllfracen = ((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1FRACEN) >> RCC_PLL1CFGR_PLL1FRACEN_Pos);
fracn1 = (float_t)(uint32_t)(pllfracen * ((RCC->PLL1FRACR & RCC_PLL1FRACR_PLL1FRACN) >> \
RCC_PLL1FRACR_PLL1FRACN_Pos));
if (pllm != 0U)
{
switch (pllsource)
{
case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllvco = ((float_t)HSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1 / (float_t)0x2000) + (float_t)1U);
break;
case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1 / (float_t)0x2000) + (float_t)1U);
break;
case RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
default:
pllvco = ((float_t) msirange / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1 / (float_t)0x2000) + (float_t)1U);
break;
}
pllr = (((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1R) >> RCC_PLL1DIVR_PLL1R_Pos) + 1U);
sysclockfreq = (uint32_t)(float_t)((float_t)pllvco / (float_t)pllr);
}
else
{
sysclockfreq = 0;
}
}
return sysclockfreq;
}
/**
* @brief Return the HCLK frequency.
* @note Each time HCLK changes, this function must be called to update the
* right HCLK value. Otherwise, any configuration based on this function will be incorrect.
*
* @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency.
* @retval HCLK frequency in Hz
*/
uint32_t HAL_RCC_GetHCLKFreq(void)
{
SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR2 & RCC_CFGR2_HPRE) >> RCC_CFGR2_HPRE_Pos];
return SystemCoreClock;
}
/**
* @brief Return the PCLK1 frequency.
* @note Each time PCLK1 changes, this function must be called to update the
* right PCLK1 value. Otherwise, any configuration based on this function will be incorrect.
* @retval PCLK1 frequency in Hz
*/
uint32_t HAL_RCC_GetPCLK1Freq(void)
{
/* Get HCLK source and Compute PCLK1 frequency ---------------------------*/
return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR2 & RCC_CFGR2_PPRE1) >> RCC_CFGR2_PPRE1_Pos]);
}
/**
* @brief Return the PCLK2 frequency.
* @note Each time PCLK2 changes, this function must be called to update the
* right PCLK2 value. Otherwise, any configuration based on this function will be incorrect.
* @retval PCLK2 frequency in Hz
*/
uint32_t HAL_RCC_GetPCLK2Freq(void)
{
/* Get HCLK source and Compute PCLK2 frequency ---------------------------*/
return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR2 & RCC_CFGR2_PPRE2) >> RCC_CFGR2_PPRE2_Pos]);
}
/**
* @brief Return the PCLK3 frequency.
* @note Each time PCLK3 changes, this function must be called to update the
* right PCLK3 value. Otherwise, any configuration based on this function will be incorrect.
* @retval PCLK3 frequency in Hz
*/
uint32_t HAL_RCC_GetPCLK3Freq(void)
{
/* Get HCLK source and Compute PCLK2 frequency ---------------------------*/
return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR3 & RCC_CFGR3_PPRE3) >> RCC_CFGR3_PPRE3_Pos]);
}
/**
* @brief Get the pRCC_OscInitStruct according to the internal
* RCC configuration registers.
* @param pRCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
* will be configured.
* @retval None
*/
void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *pRCC_OscInitStruct)
{
/* Check the parameters */
assert_param(pRCC_OscInitStruct != (void *)NULL);
/* Set all possible values for the Oscillator type parameter ---------------*/
pRCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_MSI | \
RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_HSI48;
/* Get the HSE configuration -----------------------------------------------*/
if ((RCC->CR & (RCC_CR_HSEBYP | RCC_CR_HSEEXT)) == RCC_CR_HSEBYP)
{
pRCC_OscInitStruct->HSEState = RCC_HSE_BYPASS;
}
else if ((RCC->CR & (RCC_CR_HSEBYP | RCC_CR_HSEEXT)) == (RCC_CR_HSEBYP | RCC_CR_HSEEXT))
{
pRCC_OscInitStruct->HSEState = RCC_HSE_BYPASS_DIGITAL;
}
else if ((RCC->CR & RCC_CR_HSEON) == RCC_CR_HSEON)
{
pRCC_OscInitStruct->HSEState = RCC_HSE_ON;
}
else
{
pRCC_OscInitStruct->HSEState = RCC_HSE_OFF;
}
/* Get the MSI configuration -----------------------------------------------*/
if ((RCC->CR & RCC_CR_MSISON) == RCC_CR_MSISON)
{
pRCC_OscInitStruct->MSIState = RCC_MSI_ON;
}
else
{
pRCC_OscInitStruct->MSIState = RCC_MSI_OFF;
}
pRCC_OscInitStruct->MSIClockRange = (uint32_t)((RCC->CR & RCC_ICSCR1_MSISRANGE));
if (pRCC_OscInitStruct->MSIClockRange >= RCC_MSIRANGE_12)
{
pRCC_OscInitStruct->MSICalibrationValue = (uint32_t)((RCC->ICSCR2 & RCC_ICSCR2_MSITRIM3) >> \
RCC_ICSCR2_MSITRIM3_Pos);
}
else if (pRCC_OscInitStruct->MSIClockRange >= RCC_MSIRANGE_8)
{
pRCC_OscInitStruct->MSICalibrationValue = (uint32_t)((RCC->ICSCR2 & RCC_ICSCR2_MSITRIM2) >> \
RCC_ICSCR2_MSITRIM2_Pos);
}
else if (pRCC_OscInitStruct->MSIClockRange >= RCC_MSIRANGE_4)
{
pRCC_OscInitStruct->MSICalibrationValue = (uint32_t)((RCC->ICSCR2 & RCC_ICSCR2_MSITRIM1) >> \
RCC_ICSCR2_MSITRIM1_Pos);
}
else /*if (pRCC_OscInitStruct->MSIClockRange >= RCC_MSIRANGE_0)*/
{
pRCC_OscInitStruct->MSICalibrationValue = (uint32_t)((RCC->ICSCR2 & RCC_ICSCR2_MSITRIM0) >> \
RCC_ICSCR2_MSITRIM0_Pos);
}
/* Get the HSI configuration -----------------------------------------------*/
if ((RCC->CR & RCC_CR_HSION) == RCC_CR_HSION)
{
pRCC_OscInitStruct->HSIState = RCC_HSI_ON;
}
else
{
pRCC_OscInitStruct->HSIState = RCC_HSI_OFF;
}
pRCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->ICSCR3 & RCC_ICSCR3_HSITRIM) >> RCC_ICSCR3_HSITRIM_Pos);
/* Get the LSE configuration -----------------------------------------------*/
if ((RCC->BDCR & RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP)
{
pRCC_OscInitStruct->LSEState = RCC_LSE_BYPASS;
}
else if ((RCC->BDCR & RCC_BDCR_LSEON) == RCC_BDCR_LSEON)
{
pRCC_OscInitStruct->LSEState = RCC_LSE_ON;
}
else
{
pRCC_OscInitStruct->LSEState = RCC_LSE_OFF;
}
/* Get the LSI configuration -----------------------------------------------*/
if ((RCC->BDCR & RCC_BDCR_LSION) == RCC_BDCR_LSION)
{
pRCC_OscInitStruct->LSIState = RCC_LSI_ON;
}
else
{
pRCC_OscInitStruct->LSIState = RCC_LSI_OFF;
}
/* Get the HSI48 configuration ---------------------------------------------*/
if ((RCC->CR & RCC_CR_HSI48ON) == RCC_CR_HSI48ON)
{
pRCC_OscInitStruct->HSI48State = RCC_HSI48_ON;
}
else
{
pRCC_OscInitStruct->HSI48State = RCC_HSI48_OFF;
}
/* Get the PLL configuration -----------------------------------------------*/
if ((RCC->CR & RCC_CR_PLL1ON) == RCC_CR_PLL1ON)
{
pRCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON;
}
else
{
pRCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF;
}
pRCC_OscInitStruct->PLL.PLLSource = (uint32_t)(RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1SRC);
pRCC_OscInitStruct->PLL.PLLM = (uint32_t)(((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1M) >> RCC_PLL1CFGR_PLL1M_Pos) + 1U);
pRCC_OscInitStruct->PLL.PLLN = (uint32_t)(((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) >> RCC_PLL1DIVR_PLL1N_Pos) + 1U);
pRCC_OscInitStruct->PLL.PLLQ = (uint32_t)(((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1Q) >> RCC_PLL1DIVR_PLL1Q_Pos) + 1U);
pRCC_OscInitStruct->PLL.PLLR = (uint32_t)(((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1R) >> RCC_PLL1DIVR_PLL1R_Pos) + 1U);
pRCC_OscInitStruct->PLL.PLLP = (uint32_t)(((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1P) >> RCC_PLL1DIVR_PLL1P_Pos) + 1U);
pRCC_OscInitStruct->PLL.PLLRGE = (uint32_t)((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1RGE));
pRCC_OscInitStruct->PLL.PLLFRACN = (uint32_t)(((RCC->PLL1FRACR & RCC_PLL1FRACR_PLL1FRACN) >> \
RCC_PLL1FRACR_PLL1FRACN_Pos));
pRCC_OscInitStruct->PLL.PLLMBOOST = (uint32_t)(((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1MBOOST) >> \
RCC_PLL1CFGR_PLL1MBOOST_Pos) + 1U);
}
/**
* @brief Configure the pRCC_ClkInitStruct according to the internal
* RCC configuration registers.
* @param pRCC_ClkInitStruct pointer to an RCC_ClkInitTypeDef structure that
* will be configured.
* @param pFLatency Pointer on the Flash Latency.
* @retval None
*/
void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *pRCC_ClkInitStruct, uint32_t *pFLatency)
{
/* Check the parameters */
assert_param(pRCC_ClkInitStruct != (void *)NULL);
assert_param(pFLatency != (void *)NULL);
/* Set all possible values for the Clock type parameter --------------------*/
pRCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | \
RCC_CLOCKTYPE_PCLK2 | RCC_CLOCKTYPE_PCLK3;
/* Get the SYSCLK configuration --------------------------------------------*/
pRCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR1 & RCC_CFGR1_SW);
/* Get the HCLK configuration ----------------------------------------------*/
pRCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR2 & RCC_CFGR2_HPRE);
/* Get the APB1 configuration ----------------------------------------------*/
pRCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR2 & RCC_CFGR2_PPRE1);
/* Get the APB2 configuration ----------------------------------------------*/
pRCC_ClkInitStruct->APB2CLKDivider = (uint32_t)((RCC->CFGR2 & RCC_CFGR2_PPRE2) >> 4);
/* Get the APB3 configuration ----------------------------------------------*/
pRCC_ClkInitStruct->APB3CLKDivider = (uint32_t)(RCC->CFGR3 & RCC_CFGR3_PPRE3);
/* Get the Flash Wait State (Latency) configuration ------------------------*/
*pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY);
}
/**
* @brief Get and clear reset flags
* @note Once reset flags are retrieved, this API is clearing them in order
* to isolate next reset reason.
* @retval can be a combination of @ref RCC_Reset_Flag
*/
uint32_t HAL_RCC_GetResetSource(void)
{
uint32_t reset;
/* Get all reset flags */
reset = RCC->CSR & RCC_RESET_FLAG_ALL;
/* Clear Reset flags */
RCC->CSR |= RCC_CSR_RMVF;
return reset;
}
/**
* @brief Enable the Clock Security System.
* @note If a failure is detected on the HSE oscillator clock, this oscillator
* is automatically disabled and an interrupt is generated to inform the
* software about the failure (Clock Security System Interrupt, CSSI),
* allowing the MCU to perform rescue operations. The CSSI is linked to
* the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector.
* @note The Clock Security System can only be cleared by reset.
* @retval None
*/
void HAL_RCC_EnableCSS(void)
{
SET_BIT(RCC->CR, RCC_CR_CSSON);
}
/**
* @brief Handle the RCC Clock Security System interrupt request.
* @note This API should be called under the NMI_Handler().
* @retval None
*/
void HAL_RCC_NMI_IRQHandler(void)
{
/* Check RCC CSSF interrupt flag */
if (__HAL_RCC_GET_IT(RCC_IT_CSS))
{
/* RCC Clock Security System interrupt user callback */
HAL_RCC_CSSCallback();
/* Clear RCC CSS pending bit */
__HAL_RCC_CLEAR_IT(RCC_IT_CSS);
}
}
/**
* @brief RCC Clock Security System interrupt callback.
* @retval none
*/
__weak void HAL_RCC_CSSCallback(void)
{
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RCC_CSSCallback should be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup RCC_Exported_Functions_Group3 Attributes management functions
* @brief Attributes management functions.
*
@verbatim
===============================================================================
##### RCC attributes functions #####
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Configure the RCC item attribute(s).
* @note Available attributes are to secure items and set RCC as privileged.
* @param Item Item(s) to set attributes on.
* This parameter can be a one or a combination of @ref RCC_items
* @param Attributes specifies the RCC secure/privilege attributes.
* This parameter can be a value of @ref RCC_attributes
* @retval None
*/
void HAL_RCC_ConfigAttributes(uint32_t Item, uint32_t Attributes)
{
/* Check the parameters */
assert_param(IS_RCC_ITEM_ATTRIBUTES(Item));
assert_param(IS_RCC_ATTRIBUTES(Attributes));
switch (Attributes)
{
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/* Secure Privilege attribute */
case RCC_SEC_PRIV:
SET_BIT(RCC->SECCFGR, Item);
SET_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_SPRIV);
break;
/* Secure Non-Privilege attribute */
case RCC_SEC_NPRIV:
SET_BIT(RCC->SECCFGR, Item);
CLEAR_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_SPRIV);
break;
/* Non-secure Privilege attribute */
case RCC_NSEC_PRIV:
CLEAR_BIT(RCC->SECCFGR, Item);
SET_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_NSPRIV);
break;
/* Non-secure Non-Privilege attribute */
case RCC_NSEC_NPRIV:
CLEAR_BIT(RCC->SECCFGR, Item);
CLEAR_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_NSPRIV);
break;
#else
/* Non-secure Privilege attribute */
case RCC_NSEC_PRIV:
SET_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_NSPRIV);
break;
/* Non-secure Non-Privilege attribute */
case RCC_NSEC_NPRIV:
CLEAR_BIT(RCC->PRIVCFGR, RCC_PRIVCFGR_NSPRIV);
break;
#endif /* __ARM_FEATURE_CMSE */
default:
/* Nothing to do */
break;
}
}
/**
* @}
*/
/**
* @brief Get the attribute of a RCC item.
* @note Secure and non-secure attributes are only available from secure state
* when the system implements the security (TZEN=1)
* @param Item Single item to get secure/non-secure and privilege/non-privilege attribute from.
* This parameter can be a one value of @ref RCC_items except RCC_ALL.
* @param pAttributes pointer to return the attributes.
* @retval HAL Status.
*/
HAL_StatusTypeDef HAL_RCC_GetConfigAttributes(uint32_t Item, uint32_t *pAttributes)
{
uint32_t attributes;
/* Check null pointer */
if (pAttributes == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RCC_ITEM_ATTRIBUTES(Item));
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/* Check item security */
if ((RCC->SECCFGR & Item) == Item)
{
/* Get Secure privileges attribute */
attributes = ((RCC->PRIVCFGR & RCC_PRIVCFGR_SPRIV) == 0U) ? RCC_SEC_NPRIV : RCC_SEC_PRIV;
}
else
{
/* Get Non-Secure privileges attribute */
attributes = ((RCC->PRIVCFGR & RCC_PRIVCFGR_NSPRIV) == 0U) ? RCC_NSEC_NPRIV : RCC_NSEC_PRIV;
}
#else
/* Get Non-Secure privileges attribute */
attributes = ((RCC->PRIVCFGR & RCC_PRIVCFGR_NSPRIV) == 0U) ? RCC_NSEC_NPRIV : RCC_NSEC_PRIV;
#endif /* __ARM_FEATURE_CMSE */
/* return value */
*pAttributes = attributes;
return HAL_OK;
}
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup RCC_Private_Functions
* @{
*/
/**
* @brief Update number of Flash wait states in line with MSI range and current
voltage range.
* @param msirange MSI range value from RCC_MSIRANGE_0 to RCC_MSIRANGE_15
* @retval HAL status
*/
static HAL_StatusTypeDef RCC_SetFlashLatencyFromMSIRange(uint32_t msirange)
{
uint32_t vos;
uint32_t latency; /* default value 0WS */
if (__HAL_RCC_PWR_IS_CLK_ENABLED())
{
vos = HAL_PWREx_GetVoltageRange();
}
else
{
__HAL_RCC_PWR_CLK_ENABLE();
vos = HAL_PWREx_GetVoltageRange();
__HAL_RCC_PWR_CLK_DISABLE();
}
if ((vos == PWR_REGULATOR_VOLTAGE_SCALE1) || (vos == PWR_REGULATOR_VOLTAGE_SCALE2))
{
if (msirange < RCC_MSIRANGE_1)
{
/* MSI = 48Mhz */
latency = FLASH_LATENCY_1; /* 1WS */
}
else
{
/* MSI < 48Mhz */
latency = FLASH_LATENCY_0; /* 0WS */
}
}
else
{
if (msirange < RCC_MSIRANGE_1)
{
/* MSI = 48Mhz */
if (vos == PWR_REGULATOR_VOLTAGE_SCALE3)
{
latency = FLASH_LATENCY_3; /* 3WS */
}
else
{
return HAL_ERROR;
}
}
else
{
if (msirange > RCC_MSIRANGE_2)
{
if (vos == PWR_REGULATOR_VOLTAGE_SCALE4)
{
if (msirange > RCC_MSIRANGE_3)
{
latency = FLASH_LATENCY_0; /* 1WS */
}
else
{
latency = FLASH_LATENCY_1; /* 0WS */
}
}
else
{
latency = FLASH_LATENCY_0; /* 0WS */
}
}
else
{
if (msirange == RCC_MSIRANGE_1)
{
if (vos == PWR_REGULATOR_VOLTAGE_SCALE3)
{
latency = FLASH_LATENCY_1; /* 1WS */
}
else
{
latency = FLASH_LATENCY_2; /* 2WS */
}
}
else
{
latency = FLASH_LATENCY_1; /* 1WS */
}
}
}
}
__HAL_FLASH_SET_LATENCY(latency);
/* Check that the new number of wait states is taken into account to access the Flash
memory by reading the FLASH_ACR register */
if ((FLASH->ACR & FLASH_ACR_LATENCY) != latency)
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_RCC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rcc.c
|
C
|
apache-2.0
| 84,237
|
/**
******************************************************************************
* @file stm32u5xx_hal_rcc_ex.c
* @author MCD Application Team
* @brief Extended RCC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities RCC extended peripheral:
* + Extended Peripheral Control functions
* + Extended Clock management functions
* + Extended Clock Recovery System Control functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup RCCEx RCCEx
* @brief RCC Extended HAL module driver
* @{
*/
#ifdef HAL_RCC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/** @defgroup RCCEx_Private_Constants RCCEx Private Constants
* @{
*/
#define PLL1_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define PLL2_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define PLL3_TIMEOUT_VALUE 2UL /* 2 ms (minimum Tick + 1) */
#define LSCO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
#define LSCO_GPIO_PORT GPIOA
#define LSCO_PIN GPIO_PIN_2
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RCCEx_Private_Macros
* @{
*/
#define IS_RCC_PLL2CLOCKOUT_VALUE(VALUE) ((0x00010000U <= (VALUE)) && ((VALUE) <= 0x00070000U))
#define IS_RCC_PLL3CLOCKOUT_VALUE(VALUE) ((0x00010000U <= (VALUE)) && ((VALUE) <= 0x00070000U))
#define IS_RCC_LSCOSOURCE(__SOURCE__) (((__SOURCE__) == RCC_LSCOSOURCE_LSI) || \
((__SOURCE__) == RCC_LSCOSOURCE_LSE))
#define IS_RCC_MSIPLLMODE_SELECT(__SOURCE__) (((__SOURCE__) == RCC_MSISPLL_MODE_SEL) || \
((__SOURCE__) == RCC_MSIKPLL_MODE_SEL))
#define IS_RCC_PERIPHCLOCK(__SELECTION__) ((((__SELECTION__) & RCC_PERIPHCLOCK_ALL) != 0x00u) && \
(((__SELECTION__) & ~RCC_PERIPHCLOCK_ALL) == 0x00u))
#define IS_RCC_USART1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_USART1CLKSOURCE_PCLK2) || \
((__SOURCE__) == RCC_USART1CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_USART1CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_USART1CLKSOURCE_LSE))
#define IS_RCC_USART2CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_USART2CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_USART2CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_USART2CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_USART2CLKSOURCE_LSE))
#define IS_RCC_USART3CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_USART3CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_USART3CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_USART3CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_USART3CLKSOURCE_LSE))
#define IS_RCC_UART4CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_UART4CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_UART4CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_UART4CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_UART4CLKSOURCE_LSE))
#define IS_RCC_UART5CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_UART5CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_UART5CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_UART5CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_UART5CLKSOURCE_LSE))
#if defined(USART6)
#define IS_RCC_USART6CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_USART6CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_USART6CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_USART6CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_USART6CLKSOURCE_LSE))
#endif /* USART6 */
#define IS_RCC_LPUART1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_LPUART1CLKSOURCE_PCLK3) || \
((__SOURCE__) == RCC_LPUART1CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_LPUART1CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_LPUART1CLKSOURCE_LSE) || \
((__SOURCE__) == RCC_LPUART1CLKSOURCE_MSIK))
#define IS_RCC_I2C1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C1CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_I2C1CLKSOURCE_SYSCLK)|| \
((__SOURCE__) == RCC_I2C1CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_I2C1CLKSOURCE_MSIK))
#define IS_RCC_I2C2CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C2CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_I2C2CLKSOURCE_SYSCLK)|| \
((__SOURCE__) == RCC_I2C2CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_I2C2CLKSOURCE_MSIK))
#define IS_RCC_I2C3CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C3CLKSOURCE_PCLK3) || \
((__SOURCE__) == RCC_I2C3CLKSOURCE_SYSCLK ) || \
((__SOURCE__) == RCC_I2C3CLKSOURCE_HSI ) || \
((__SOURCE__) == RCC_I2C3CLKSOURCE_MSIK))
#define IS_RCC_I2C4CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C4CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_I2C4CLKSOURCE_SYSCLK)|| \
((__SOURCE__) == RCC_I2C4CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_I2C4CLKSOURCE_MSIK))
#if defined(I2C5)
#define IS_RCC_I2C5CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C5CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_I2C5CLKSOURCE_SYSCLK)|| \
((__SOURCE__) == RCC_I2C5CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_I2C5CLKSOURCE_MSIK))
#endif /* I2C5 */
#if defined(I2C6)
#define IS_RCC_I2C6CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_I2C6CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_I2C6CLKSOURCE_SYSCLK)|| \
((__SOURCE__) == RCC_I2C6CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_I2C6CLKSOURCE_MSIK))
#endif /* I2C6 */
#define IS_RCC_SAI1CLK(__SOURCE__) \
(((__SOURCE__) == RCC_SAI1CLKSOURCE_PLL2) || \
((__SOURCE__) == RCC_SAI1CLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_SAI1CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_SAI1CLKSOURCE_PIN) || \
((__SOURCE__) == RCC_SAI1CLKSOURCE_HSI))
#define IS_RCC_SAI2CLK(__SOURCE__) \
(((__SOURCE__) == RCC_SAI2CLKSOURCE_PLL2) || \
((__SOURCE__) == RCC_SAI2CLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_SAI2CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_SAI2CLKSOURCE_PIN) || \
((__SOURCE__) == RCC_SAI2CLKSOURCE_HSI))
#define IS_RCC_LPTIM1CLK(__SOURCE__) \
(((__SOURCE__) == RCC_LPTIM1CLKSOURCE_MSIK) || \
((__SOURCE__) == RCC_LPTIM1CLKSOURCE_LSI) || \
((__SOURCE__) == RCC_LPTIM1CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_LPTIM1CLKSOURCE_LSE))
#define IS_RCC_LPTIM2CLK(__SOURCE__) \
(((__SOURCE__) == RCC_LPTIM2CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_LPTIM2CLKSOURCE_LSI) || \
((__SOURCE__) == RCC_LPTIM2CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_LPTIM2CLKSOURCE_LSE))
#define IS_RCC_LPTIM34CLK(__SOURCE__) \
(((__SOURCE__) == RCC_LPTIM34CLKSOURCE_MSIK) || \
((__SOURCE__) == RCC_LPTIM34CLKSOURCE_LSI) || \
((__SOURCE__) == RCC_LPTIM34CLKSOURCE_HSI) || \
((__SOURCE__) == RCC_LPTIM34CLKSOURCE_LSE))
#define IS_RCC_FDCAN1CLK(__SOURCE__) \
(((__SOURCE__) == RCC_FDCAN1CLKSOURCE_HSE) || \
((__SOURCE__) == RCC_FDCAN1CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_FDCAN1CLKSOURCE_PLL2))
#define IS_RCC_SDMMCCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_SDMMCCLKSOURCE_CLK48) || \
((__SOURCE__) == RCC_SDMMCCLKSOURCE_PLL1))
#define IS_RCC_RNGCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_RNGCLKSOURCE_HSI48) || \
((__SOURCE__) == RCC_RNGCLKSOURCE_HSI48_DIV2) || \
((__SOURCE__) == RCC_RNGCLKSOURCE_HSI))
#define IS_RCC_SAESCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_SAESCLKSOURCE_SHSI) || \
((__SOURCE__) == RCC_SAESCLKSOURCE_SHSI_DIV2))
#define IS_RCC_ADCDACCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_ADCDACCLKSOURCE_HCLK) || \
((__SOURCE__) == RCC_ADCDACCLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_ADCDACCLKSOURCE_PLL2) || \
((__SOURCE__) == RCC_ADCDACCLKSOURCE_HSE) || \
((__SOURCE__) == RCC_ADCDACCLKSOURCE_HSI) || \
((__SOURCE__) == RCC_ADCDACCLKSOURCE_MSIK))
#define IS_RCC_MDF1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_MDF1CLKSOURCE_HCLK) || \
((__SOURCE__) == RCC_MDF1CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_MDF1CLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_MDF1CLKSOURCE_PIN) || \
((__SOURCE__) == RCC_MDF1CLKSOURCE_MSIK))
#define IS_RCC_ADF1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_ADF1CLKSOURCE_HCLK) || \
((__SOURCE__) == RCC_ADF1CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_ADF1CLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_ADF1CLKSOURCE_PIN) || \
((__SOURCE__) == RCC_ADF1CLKSOURCE_MSIK))
#define IS_RCC_OSPICLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_OSPICLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_OSPICLKSOURCE_MSIK) || \
((__SOURCE__) == RCC_OSPICLKSOURCE_PLL1) ||\
((__SOURCE__) == RCC_OSPICLKSOURCE_PLL2))
#if defined(HSPI1)
#define IS_RCC_HSPICLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_HSPICLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_HSPICLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_HSPICLKSOURCE_PLL2) || \
((__SOURCE__) == RCC_HSPICLKSOURCE_PLL3))
#endif /* HSPI1 */
#define IS_RCC_ICLKCLKSOURCE(__SOURCE__)\
(((__SOURCE__) == RCC_ICLK_CLKSOURCE_HSI48)|| \
((__SOURCE__) == RCC_ICLK_CLKSOURCE_PLL2) || \
((__SOURCE__) == RCC_ICLK_CLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_ICLK_CLKSOURCE_MSIK))
#define IS_RCC_SPI1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_SPI1CLKSOURCE_PCLK2) || \
((__SOURCE__) == RCC_SPI1CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_SPI1CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_SPI1CLKSOURCE_MSIK))
#define IS_RCC_SPI2CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_SPI2CLKSOURCE_PCLK1) || \
((__SOURCE__) == RCC_SPI2CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_SPI2CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_SPI2CLKSOURCE_MSIK))
#define IS_RCC_SPI3CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_SPI3CLKSOURCE_PCLK3) || \
((__SOURCE__) == RCC_SPI3CLKSOURCE_SYSCLK) || \
((__SOURCE__) == RCC_SPI3CLKSOURCE_HSI)|| \
((__SOURCE__) == RCC_SPI3CLKSOURCE_MSIK))
#define IS_RCC_DAC1CLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_DAC1CLKSOURCE_LSE) || \
((__SOURCE__) == RCC_DAC1CLKSOURCE_LSI))
#define IS_RCC_RTCCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_RTCCLKSOURCE_NO_CLK) || \
((__SOURCE__) == RCC_RTCCLKSOURCE_LSE) || \
((__SOURCE__) == RCC_RTCCLKSOURCE_LSI) || \
((__SOURCE__) == RCC_RTCCLKSOURCE_HSE_DIV32))
#if defined(LTDC)
#define IS_RCC_LTDCCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_LTDCCLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_LTDCCLKSOURCE_PLL2))
#endif /* LTDC */
#if defined(DSI)
#define IS_RCC_DSICLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_DSICLKSOURCE_PLL3) || \
((__SOURCE__) == RCC_DSICLKSOURCE_DSIPHY))
#endif /* DSI */
#if defined(USB_OTG_HS)
#define IS_RCC_USBPHYCLKSOURCE(__SOURCE__) \
(((__SOURCE__) == RCC_USBPHYCLKSOURCE_HSE) || \
((__SOURCE__) == RCC_USBPHYCLKSOURCE_HSE_DIV2) || \
((__SOURCE__) == RCC_USBPHYCLKSOURCE_PLL1) || \
((__SOURCE__) == RCC_USBPHYCLKSOURCE_PLL1_DIV2))
#endif /* USB_OTG_HS */
#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__) <= 0x3FU))
#define IS_RCC_CRS_FREQERRORDIR(__DIR__) (((__DIR__) == RCC_CRS_FREQERRORDIR_UP) || \
((__DIR__) == RCC_CRS_FREQERRORDIR_DOWN))
#endif /* CRS */
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup RCCEx_Private_Functions RCCEx Private Functions
* @{
*/
static HAL_StatusTypeDef RCCEx_PLLSource_Enable(uint32_t PllSource);
static HAL_StatusTypeDef RCCEx_PLL2_Config(RCC_PLL2InitTypeDef *Pll2);
static HAL_StatusTypeDef RCCEx_PLL3_Config(RCC_PLL3InitTypeDef *Pll3);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup RCCEx_Exported_Functions RCCEx Exported Functions
* @{
*/
/** @defgroup RCCEx_Exported_Functions_Group1 Extended Peripheral Control functions
* @brief Extended Peripheral Control functions
*
@verbatim
===============================================================================
##### Extended Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the RCC Clocks
frequencies.
[..]
(@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to
select the RTC clock source; in this case the Backup domain will be reset in
order to modify the RTC Clock source, as consequence RTC registers (including
the backup registers) are set to their reset values.
@endverbatim
* @{
*/
/**
* @brief Initialize the RCC extended peripherals clocks according to the specified
* parameters in the RCC_PeriphCLKInitTypeDef.
* @param pPeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
* contains a field PeriphClockSelection which can be a combination of the following values:
* @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock
* @arg @ref RCC_PERIPHCLK_USART2 USART2 peripheral clock
* @arg @ref RCC_PERIPHCLK_USART3 USART3 peripheral clock
* @arg @ref RCC_PERIPHCLK_UART4 UART4 peripheral clock
* @arg @ref RCC_PERIPHCLK_UART5 UART5 peripheral clock
* @arg @ref RCC_PERIPHCLK_USART6 USART6 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPUART1 LPUART1 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C2 I2C2 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C3 I2C3 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C4 I2C4 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C5 I2C5 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C6 I2C6 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPTIM34 LPTIM34 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPTIM2 LPTIM2 peripheral clock
* @arg @ref RCC_PERIPHCLK_SAES SAES peripheral clock
* @arg @ref RCC_PERIPHCLK_SAI1 SAI1 peripheral clock
* @arg @ref RCC_PERIPHCLK_SAI2 SAI2 peripheral clock
* @arg @ref RCC_PERIPHCLK_ADCDAC ADC1 ADC2 ADC4 DAC1 peripheral clock
* @arg @ref RCC_PERIPHCLK_MDF1 MDF1 peripheral clock
* @arg @ref RCC_PERIPHCLK_ADF1 ADF1 peripheral clock
* @arg @ref RCC_PERIPHCLK_RTC RTC peripheral clock
* @arg @ref RCC_PERIPHCLK_RNG RNG peripheral clock
* @arg @ref RCC_PERIPHCLK_ICLK ICLK peripheral clock
* @arg @ref RCC_PERIPHCLK_SDMMC SDMMC1 peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI1 SPI1 peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI2 SPI2 peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI3 SPI3 peripheral clock
* @arg @ref RCC_PERIPHCLK_OSPI OSPI peripheral clock
* @arg @ref RCC_PERIPHCLK_FDCAN1 FDCAN1 peripheral clock
* @arg @ref RCC_PERIPHCLK_DAC1 DAC1 peripheral clock
* @arg @ref RCC_PERIPHCLK_HSPI HSPI peripheral clock
* @arg @ref RCC_PERIPHCLK_LTDC LTDC peripheral clock
* @arg @ref RCC_PERIPHCLK_DSI DSI peripheral clock
* @arg @ref RCC_PERIPHCLK_USBPHY USBPHY peripheral clock
*
* @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
* the RTC clock source: in this case the access to Backup domain is enabled.
*
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *pPeriphClkInit)
{
uint32_t tmpregister;
uint32_t tickstart;
HAL_StatusTypeDef ret = HAL_OK; /* Intermediate status */
HAL_StatusTypeDef status = HAL_OK; /* Final status */
/* Check the parameters */
assert_param(IS_RCC_PERIPHCLOCK(pPeriphClkInit->PeriphClockSelection));
/*-------------------------- USART1 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1)
{
/* Check the parameters */
assert_param(IS_RCC_USART1CLKSOURCE(pPeriphClkInit->Usart1ClockSelection));
/* Configure the USART1 clock source */
__HAL_RCC_USART1_CONFIG(pPeriphClkInit->Usart1ClockSelection);
}
/*-------------------------- USART2 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2)
{
/* Check the parameters */
assert_param(IS_RCC_USART2CLKSOURCE(pPeriphClkInit->Usart2ClockSelection));
/* Configure the USART2 clock source */
__HAL_RCC_USART2_CONFIG(pPeriphClkInit->Usart2ClockSelection);
}
/*-------------------------- USART3 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART3) == RCC_PERIPHCLK_USART3)
{
/* Check the parameters */
assert_param(IS_RCC_USART3CLKSOURCE(pPeriphClkInit->Usart3ClockSelection));
/* Configure the USART3 clock source */
__HAL_RCC_USART3_CONFIG(pPeriphClkInit->Usart3ClockSelection);
}
/*-------------------------- UART4 clock source configuration --------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_UART4) == RCC_PERIPHCLK_UART4)
{
/* Check the parameters */
assert_param(IS_RCC_UART4CLKSOURCE(pPeriphClkInit->Uart4ClockSelection));
/* Configure the UART4 clock source */
__HAL_RCC_UART4_CONFIG(pPeriphClkInit->Uart4ClockSelection);
}
/*-------------------------- UART5 clock source configuration --------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_UART5) == RCC_PERIPHCLK_UART5)
{
/* Check the parameters */
assert_param(IS_RCC_UART5CLKSOURCE(pPeriphClkInit->Uart5ClockSelection));
/* Configure the UART5 clock source */
__HAL_RCC_UART5_CONFIG(pPeriphClkInit->Uart5ClockSelection);
}
#if defined(USART6)
/*-------------------------- USART6 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART6) == RCC_PERIPHCLK_USART6)
{
/* Check the parameters */
assert_param(IS_RCC_USART6CLKSOURCE(pPeriphClkInit->Usart6ClockSelection));
/* Configure the USART6 clock source */
__HAL_RCC_USART6_CONFIG(pPeriphClkInit->Usart6ClockSelection);
}
#endif /* USART6 */
/*-------------------------- LPUART1 clock source configuration ------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPUART1) == RCC_PERIPHCLK_LPUART1)
{
/* Check the parameters */
assert_param(IS_RCC_LPUART1CLKSOURCE(pPeriphClkInit->Lpuart1ClockSelection));
/* Configure the LPUART1 clock source */
__HAL_RCC_LPUART1_CONFIG(pPeriphClkInit->Lpuart1ClockSelection);
}
/*-------------------------- I2C1 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1)
{
/* Check the parameters */
assert_param(IS_RCC_I2C1CLKSOURCE(pPeriphClkInit->I2c1ClockSelection));
/* Configure the I2C1 clock source */
__HAL_RCC_I2C1_CONFIG(pPeriphClkInit->I2c1ClockSelection);
}
/*-------------------------- I2C2 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C2) == RCC_PERIPHCLK_I2C2)
{
/* Check the parameters */
assert_param(IS_RCC_I2C2CLKSOURCE(pPeriphClkInit->I2c2ClockSelection));
/* Configure the I2C2 clock source */
__HAL_RCC_I2C2_CONFIG(pPeriphClkInit->I2c2ClockSelection);
}
/*-------------------------- I2C3 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C3) == RCC_PERIPHCLK_I2C3)
{
/* Check the parameters */
assert_param(IS_RCC_I2C3CLKSOURCE(pPeriphClkInit->I2c3ClockSelection));
/* Configure the I2C3 clock source */
__HAL_RCC_I2C3_CONFIG(pPeriphClkInit->I2c3ClockSelection);
}
/*-------------------------- I2C4 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C4) == RCC_PERIPHCLK_I2C4)
{
/* Check the parameters */
assert_param(IS_RCC_I2C4CLKSOURCE(pPeriphClkInit->I2c4ClockSelection));
/* Configure the I2C4 clock source */
__HAL_RCC_I2C4_CONFIG(pPeriphClkInit->I2c4ClockSelection);
}
#if defined(I2C5)
/*-------------------------- I2C5 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C5) == RCC_PERIPHCLK_I2C5)
{
/* Check the parameters */
assert_param(IS_RCC_I2C5CLKSOURCE(pPeriphClkInit->I2c5ClockSelection));
/* Configure the I2C5 clock source */
__HAL_RCC_I2C5_CONFIG(pPeriphClkInit->I2c5ClockSelection);
}
#endif /* I2C5 */
#if defined(I2C6)
/*-------------------------- I2C6 clock source configuration ---------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C6) == RCC_PERIPHCLK_I2C6)
{
/* Check the parameters */
assert_param(IS_RCC_I2C6CLKSOURCE(pPeriphClkInit->I2c6ClockSelection));
/* Configure the I2C6 clock source */
__HAL_RCC_I2C6_CONFIG(pPeriphClkInit->I2c6ClockSelection);
}
#endif /* I2C6 */
/*-------------------------- LPTIM1 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == (RCC_PERIPHCLK_LPTIM1))
{
assert_param(IS_RCC_LPTIM1CLK(pPeriphClkInit->Lptim1ClockSelection));
__HAL_RCC_LPTIM1_CONFIG(pPeriphClkInit->Lptim1ClockSelection);
}
/*-------------------------- LPTIM2 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM2) == (RCC_PERIPHCLK_LPTIM2))
{
assert_param(IS_RCC_LPTIM2CLK(pPeriphClkInit->Lptim2ClockSelection));
__HAL_RCC_LPTIM2_CONFIG(pPeriphClkInit->Lptim2ClockSelection);
}
/*-------------------------- LPTIM34 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM34) == (RCC_PERIPHCLK_LPTIM34))
{
assert_param(IS_RCC_LPTIM34CLK(pPeriphClkInit->Lptim34ClockSelection));
__HAL_RCC_LPTIM34_CONFIG(pPeriphClkInit->Lptim34ClockSelection);
}
/*-------------------------- SAI1 clock source configuration ---------------------*/
if ((((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1))
{
/* Check the parameters */
assert_param(IS_RCC_SAI1CLK(pPeriphClkInit->Sai1ClockSelection));
switch (pPeriphClkInit->Sai1ClockSelection)
{
case RCC_SAI1CLKSOURCE_PLL1: /* PLL is used as clock source for SAI1*/
/* Enable SAI Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
/* SAI1 clock source config set later after clock selection check */
break;
case RCC_SAI1CLKSOURCE_PLL2: /* PLL2 is used as clock source for SAI1*/
/* PLL2 P input clock, parameters M, N & P configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
/* SAI1 clock source config set later after clock selection check */
break;
case RCC_SAI1CLKSOURCE_PLL3: /* PLL3 is used as clock source for SAI1*/
/* PLL3 P input clock, parameters M, N & P configuration clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
/* SAI1 clock source config set later after clock selection check */
break;
case RCC_SAI1CLKSOURCE_PIN: /* External clock is used as source of SAI1 clock*/
/* SAI1 clock source configuration done later after clock selection check */
break;
case RCC_SAI1CLKSOURCE_HSI: /* HSI is used as source of SAI1 clock*/
/* SAI1 clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of SAI1 clock*/
__HAL_RCC_SAI1_CONFIG(pPeriphClkInit->Sai1ClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- SAI2 clock source configuration ---------------------*/
if ((((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == RCC_PERIPHCLK_SAI2))
{
/* Check the parameters */
assert_param(IS_RCC_SAI2CLK(pPeriphClkInit->Sai2ClockSelection));
switch (pPeriphClkInit->Sai2ClockSelection)
{
case RCC_SAI2CLKSOURCE_PLL1: /* PLL is used as clock source for SAI2*/
/* Enable SAI Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
/* SAI2 clock source config set later after clock selection check */
break;
case RCC_SAI2CLKSOURCE_PLL2: /* PLL2 is used as clock source for SAI2*/
/* PLL2 P input clock, parameters M, N & P configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
/* SAI2 clock source config set later after clock selection check */
break;
case RCC_SAI2CLKSOURCE_PLL3: /* PLL3 is used as clock source for SAI2*/
/* PLL3 P input clock, parameters M, N & P configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
/* SAI2 clock source config set later after clock selection check */
break;
case RCC_SAI2CLKSOURCE_PIN: /* External clock is used as source of SAI2 clock*/
/* SAI2 clock source configuration done later after clock selection check */
break;
case RCC_SAI2CLKSOURCE_HSI: /* HSI is used as source of SAI2 clock*/
/* SAI2 clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of SAI2 clock*/
__HAL_RCC_SAI2_CONFIG(pPeriphClkInit->Sai2ClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- ADCDAC clock source configuration ----------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADCDAC) == RCC_PERIPHCLK_ADCDAC)
{
/* Check the parameters */
assert_param(IS_RCC_ADCDACCLKSOURCE(pPeriphClkInit->AdcDacClockSelection));
switch (pPeriphClkInit->AdcDacClockSelection)
{
case RCC_ADCDACCLKSOURCE_PLL2:
/* PLL2 input clock, parameters M, N,P, & R configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
break;
case RCC_ADCDACCLKSOURCE_SYSCLK:
case RCC_ADCDACCLKSOURCE_HCLK:
case RCC_ADCDACCLKSOURCE_HSE:
case RCC_ADCDACCLKSOURCE_HSI:
case RCC_ADCDACCLKSOURCE_MSIK:
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Configure the ADC1 interface clock source */
__HAL_RCC_ADCDAC_CONFIG(pPeriphClkInit->AdcDacClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- MDF1 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_MDF1) == RCC_PERIPHCLK_MDF1)
{
/* Check the parameters */
assert_param(IS_RCC_MDF1CLKSOURCE(pPeriphClkInit->Mdf1ClockSelection));
switch (pPeriphClkInit->Mdf1ClockSelection)
{
case RCC_MDF1CLKSOURCE_PLL1:
/* Enable PLL1 Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
break;
case RCC_MDF1CLKSOURCE_PLL3:
/* PLL3 Q input clock, parameters M, N & Q configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
break;
case RCC_MDF1CLKSOURCE_HCLK:
break;
case RCC_MDF1CLKSOURCE_PIN:
break;
case RCC_MDF1CLKSOURCE_MSIK:
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Configure the MDF1 interface clock source */
__HAL_RCC_MDF1_CONFIG(pPeriphClkInit->Mdf1ClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- ADF1 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADF1) == RCC_PERIPHCLK_ADF1)
{
/* Check the parameters */
assert_param(IS_RCC_ADF1CLKSOURCE(pPeriphClkInit->Adf1ClockSelection));
switch (pPeriphClkInit->Adf1ClockSelection)
{
case RCC_ADF1CLKSOURCE_PLL1:
/* Enable PLL1 Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
break;
case RCC_ADF1CLKSOURCE_PLL3:
/* PLL3 Q input clock, parameters M, N & Q configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
break;
case RCC_ADF1CLKSOURCE_HCLK:
break;
case RCC_ADF1CLKSOURCE_PIN:
break;
case RCC_ADF1CLKSOURCE_MSIK:
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Configure the ADF1 interface clock source */
__HAL_RCC_ADF1_CONFIG(pPeriphClkInit->Adf1ClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- RTC clock source configuration ----------------------*/
if ((pPeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC)
{
FlagStatus pwrclkchanged = RESET;
/* Check for RTC Parameters used to output RTCCLK */
assert_param(IS_RCC_RTCCLKSOURCE(pPeriphClkInit->RTCClockSelection));
/* Enable Power Clock */
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
/* Enable write access to Backup domain */
SET_BIT(PWR->DBPR, PWR_DBPR_DBP);
/* Wait for Backup domain Write protection disable */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE)
{
ret = HAL_TIMEOUT;
break;
}
}
if (ret == HAL_OK)
{
/* Reset the Backup domain only if the RTC Clock source selection is modified from default */
tmpregister = READ_BIT(RCC->BDCR, RCC_BDCR_RTCSEL);
if ((tmpregister != RCC_RTCCLKSOURCE_NO_CLK) && (tmpregister != pPeriphClkInit->RTCClockSelection))
{
/* Store the content of BDCR register before the reset of Backup Domain */
tmpregister = READ_BIT(RCC->BDCR, ~(RCC_BDCR_RTCSEL));
/* RTC Clock selection can be changed only if the Backup Domain is reset */
__HAL_RCC_BACKUPRESET_FORCE();
__HAL_RCC_BACKUPRESET_RELEASE();
/* Restore the Content of BDCR register */
RCC->BDCR = tmpregister;
}
/* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */
if (HAL_IS_BIT_SET(tmpregister, RCC_BDCR_LSEON))
{
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till LSE is ready */
while (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
{
ret = HAL_TIMEOUT;
break;
}
}
}
if (ret == HAL_OK)
{
/* Apply new RTC clock source selection */
__HAL_RCC_RTC_CONFIG(pPeriphClkInit->RTCClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
else
{
/* set overall return value */
status = ret;
}
/* Restore clock configuration if changed */
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
}
/*-------------------------------------- ICLK Configuration -----------------------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ICLK) == RCC_PERIPHCLK_ICLK)
{
/* Check the parameters */
assert_param(IS_RCC_ICLKCLKSOURCE(pPeriphClkInit->IclkClockSelection));
switch (pPeriphClkInit->IclkClockSelection)
{
case RCC_ICLK_CLKSOURCE_PLL2:
/* PLL2 input clock, parameters M, N,P,Q & R configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
break;
case RCC_ICLK_CLKSOURCE_PLL1:
/* Enable ICLK Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVQ);
break;
case RCC_ICLK_CLKSOURCE_HSI48:
break;
case RCC_ICLK_CLKSOURCE_MSIK:
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Configure the CLK48 source */
__HAL_RCC_CLK48_CONFIG(pPeriphClkInit->IclkClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*------------------------------ RNG Configuration -------------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RNG) == RCC_PERIPHCLK_RNG)
{
/* Check the parameters */
assert_param(IS_RCC_RNGCLKSOURCE(pPeriphClkInit->RngClockSelection));
switch (pPeriphClkInit->RngClockSelection)
{
case RCC_RNGCLKSOURCE_HSI48_DIV2: /* HSI48/2 is used as clock source for RNG*/
/* RNG clock source configuration done later after clock selection check */
break;
case RCC_RNGCLKSOURCE_HSI: /* HSI is used as clock source for RNG*/
/* RNG clock source configuration done later after clock selection check */
break;
case RCC_RNGCLKSOURCE_HSI48:
/* HSI48 oscillator is used as source of RNG clock */
/* RNG clock source configuration done later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of RNG clock*/
__HAL_RCC_RNG_CONFIG(pPeriphClkInit->RngClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- SAES clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAES) == RCC_PERIPHCLK_SAES)
{
/* Check the parameters */
assert_param(IS_RCC_SAESCLKSOURCE(pPeriphClkInit->SaesClockSelection));
/* Configure the SAES clock source */
__HAL_RCC_SAES_CONFIG(pPeriphClkInit->SaesClockSelection);
}
/*-------------------------- SDMMC1/2 clock source configuration -------------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDMMC) == (RCC_PERIPHCLK_SDMMC))
{
/* Check the parameters */
assert_param(IS_RCC_SDMMCCLKSOURCE(pPeriphClkInit->SdmmcClockSelection));
if (pPeriphClkInit->SdmmcClockSelection == RCC_SDMMCCLKSOURCE_PLL1)
{
/* Enable PLL1 P CLK output */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
}
/* Configure the SDMMC1/2 clock source */
__HAL_RCC_SDMMC_CONFIG(pPeriphClkInit->SdmmcClockSelection);
}
/*-------------------------- SPI1 clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPI1) == RCC_PERIPHCLK_SPI1)
{
/* Check the parameters */
assert_param(IS_RCC_SPI1CLKSOURCE(pPeriphClkInit->Spi1ClockSelection));
/* Configure the SPI1 clock source */
__HAL_RCC_SPI1_CONFIG(pPeriphClkInit->Spi1ClockSelection);
}
/*-------------------------- SPI2 clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPI2) == RCC_PERIPHCLK_SPI2)
{
/* Check the parameters */
assert_param(IS_RCC_SPI2CLKSOURCE(pPeriphClkInit->Spi2ClockSelection));
/* Configure the SPI2 clock source */
__HAL_RCC_SPI2_CONFIG(pPeriphClkInit->Spi2ClockSelection);
}
/*-------------------------- SPI3 clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPI3) == RCC_PERIPHCLK_SPI3)
{
/* Check the parameters */
assert_param(IS_RCC_SPI3CLKSOURCE(pPeriphClkInit->Spi3ClockSelection));
/* Configure the SPI3 clock source */
__HAL_RCC_SPI3_CONFIG(pPeriphClkInit->Spi3ClockSelection);
}
/*-------------------------- OctoSPIx clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_OSPI) == RCC_PERIPHCLK_OSPI)
{
/* Check the parameters */
assert_param(IS_RCC_OSPICLKSOURCE(pPeriphClkInit->OspiClockSelection));
if (pPeriphClkInit->OspiClockSelection == RCC_OSPICLKSOURCE_PLL1)
{
/* Enable PLL1 Q CLK output */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVQ);
}
if (pPeriphClkInit->OspiClockSelection == RCC_OSPICLKSOURCE_PLL2)
{
/* PLL2 input clock, parameters M, N & Q configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
}
if (ret == HAL_OK)
{
/* Configure the OctoSPI clock source */
__HAL_RCC_OSPI_CONFIG(pPeriphClkInit->OspiClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
#if defined(HSPI1)
/*-------------------------- HSPIx kernel clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_HSPI) == RCC_PERIPHCLK_HSPI)
{
/* Check the parameters */
assert_param(IS_RCC_HSPICLKSOURCE(pPeriphClkInit->HspiClockSelection));
switch (pPeriphClkInit->HspiClockSelection)
{
case RCC_HSPICLKSOURCE_SYSCLK: /* SYSCLK is used as clock source for HSPI kernel clock*/
/* HSPI kernel clock source config set later after clock selection check */
break;
case RCC_HSPICLKSOURCE_PLL1: /* PLL1 is used as clock source for HSPI kernel clock*/
/* Enable 48M2 Clock output generated from System PLL . */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVQ);
/* HSPI kernel clock source config set later after clock selection check */
break;
case RCC_HSPICLKSOURCE_PLL2: /* PLL2 is used as clock source for HSPI kernel clock*/
/* PLL2 input clock, parameters M, N & Q configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
/* HSPI kernel clock source config set later after clock selection check */
break;
case RCC_HSPICLKSOURCE_PLL3: /* PLL3 is used as clock source for HSPI kernel clock*/
/* PLL3 input clock, parameters M, N & R configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
/* HSPI kernel clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of HSPI kernel clock*/
__HAL_RCC_HSPI_CONFIG(pPeriphClkInit->HspiClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
#endif /* defined(HSPI1) */
/*-------------------------- FDCAN1 kernel clock source configuration -------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FDCAN1) == (RCC_PERIPHCLK_FDCAN1))
{
assert_param(IS_RCC_FDCAN1CLK(pPeriphClkInit->Fdcan1ClockSelection));
switch (pPeriphClkInit->Fdcan1ClockSelection)
{
case RCC_FDCAN1CLKSOURCE_HSE: /* HSE is used as source of FDCAN1 kernel clock*/
/* FDCAN1 kernel clock source config set later after clock selection check */
break;
case RCC_FDCAN1CLKSOURCE_PLL1: /* PLL1 is used as clock source for FDCAN1 kernel clock*/
/* Enable 48M2 Clock output generated from System PLL */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVQ);
/* FDCAN1 kernel clock source config set later after clock selection check */
break;
case RCC_FDCAN1CLKSOURCE_PLL2: /* PLL2 is used as clock source for FDCAN1 kernel clock*/
/* PLL2 input clock, parameters M, N & P configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
/* FDCAN1 kernel clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of FDCAN1 kernel clock*/
__HAL_RCC_FDCAN1_CONFIG(pPeriphClkInit->Fdcan1ClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
/*-------------------------- DAC1 clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DAC1) == RCC_PERIPHCLK_DAC1)
{
/* Check the parameters */
assert_param(IS_RCC_DAC1CLKSOURCE(pPeriphClkInit->Dac1ClockSelection));
/* Configure the DAC1 clock source */
__HAL_RCC_DAC1_CONFIG(pPeriphClkInit->Dac1ClockSelection);
}
#if defined(LTDC)
/*-------------------------- LTDC clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == RCC_PERIPHCLK_LTDC)
{
/* Check the parameters */
assert_param(IS_RCC_LTDCCLKSOURCE(pPeriphClkInit->LtdcClockSelection));
switch (pPeriphClkInit->LtdcClockSelection)
{
case RCC_LTDCCLKSOURCE_PLL2: /* PLL2 is used as clock source for LTDC clock*/
/* PLL2 input clock, parameters M, N & P configuration and clock output (PLL2ClockOut) */
ret = RCCEx_PLL2_Config(&(pPeriphClkInit->PLL2));
/* LTDC clock source config set later after clock selection check */
break;
case RCC_LTDCCLKSOURCE_PLL3: /* PLL3 is used as clock source for LTDC clock*/
/* PLL3 input clock, parameters M, N & P configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
/* LTDC clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of LTDC clock*/
__HAL_RCC_LTDC_CONFIG(pPeriphClkInit->LtdcClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
#endif /* defined(LTDC) */
#if defined(DSI)
/*-------------------------- DSI clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DSI) == RCC_PERIPHCLK_DSI)
{
/* Check the parameters */
assert_param(IS_RCC_DSICLKSOURCE(pPeriphClkInit->DsiClockSelection));
if (pPeriphClkInit->DsiClockSelection == RCC_DSICLKSOURCE_PLL3)
{
/* PLL3 is used as clock source for DSI clock*/
/* PLL3 input clock, parameters M, N & P configuration and clock output (PLL3ClockOut) */
ret = RCCEx_PLL3_Config(&(pPeriphClkInit->PLL3));
}
if (ret == HAL_OK)
{
/* Set the source of DSI clock*/
__HAL_RCC_DSI_CONFIG(pPeriphClkInit->DsiClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
#endif /* defined(DSI) */
#if defined(USB_OTG_HS)
/*-------------------------- USB PHY clock source configuration ----------------*/
if (((pPeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USBPHY) == RCC_PERIPHCLK_USBPHY)
{
/* Check the parameters */
assert_param(IS_RCC_USBPHYCLKSOURCE(pPeriphClkInit->UsbPhyClockSelection));
switch (pPeriphClkInit->UsbPhyClockSelection)
{
case RCC_USBPHYCLKSOURCE_HSE: /* HSE is used as clock source for USB PHY clock*/
case RCC_USBPHYCLKSOURCE_HSE_DIV2: /* HSE div 2 is used as clock source for USB PHY clock*/
/* USB-PHY clock source config set later after clock selection check */
break;
case RCC_USBPHYCLKSOURCE_PLL1: /* PLL1 P divider clock selected as USB PHY clock */
case RCC_USBPHYCLKSOURCE_PLL1_DIV2: /* PLL1 P divider clock div 2 selected as USB PHY clock */
/* Enable P Clock output generated from System PLL . */
__HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL1_DIVP);
/* USB-PHY clock source config set later after clock selection check */
break;
default:
ret = HAL_ERROR;
break;
}
if (ret == HAL_OK)
{
/* Set the source of USBPHY clock*/
__HAL_RCC_USBPHY_CONFIG(pPeriphClkInit->UsbPhyClockSelection);
}
else
{
/* set overall return value */
status = ret;
}
}
#endif /* defined(USB_OTG_HS) */
return status;
}
/**
* @brief Get the RCC_ClkInitStruct according to the internal RCC configuration registers.
* @param pPeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
* returns the configuration information for the Extended Peripherals
* clocks(USART1, USART2, USART3, UART4, UART5, LPUART, I2C1, I2C2, I2C3, LPTIM1, LPTIM2, SAI1, SAI2,
* ADC1, ADC2, MDF1, MDF2, RTC, CLK48, SDMMC1, I2C4, SPI12, SPI3, OSPI, FDCAN1, DAC1).
* @retval None
*/
void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *pPeriphClkInit)
{
/* Set all possible values for the extended clock type parameter------------*/
#if (defined(STM32U599xx) || defined(STM32U5A9xx))
pPeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | \
RCC_PERIPHCLK_UART4 | RCC_PERIPHCLK_UART5 | RCC_PERIPHCLK_USART6 | \
RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | \
RCC_PERIPHCLK_I2C3 | RCC_PERIPHCLK_I2C5 | RCC_PERIPHCLK_I2C6 | \
RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_LPTIM34 | RCC_PERIPHCLK_LPTIM2 | \
RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2 | RCC_PERIPHCLK_ADCDAC | \
RCC_PERIPHCLK_MDF1 | RCC_PERIPHCLK_ADF1 | RCC_PERIPHCLK_RTC | \
RCC_PERIPHCLK_ICLK | RCC_PERIPHCLK_SDMMC | RCC_PERIPHCLK_RNG | \
RCC_PERIPHCLK_I2C4 | RCC_PERIPHCLK_SPI1 | RCC_PERIPHCLK_SPI2 | \
RCC_PERIPHCLK_SPI3 | RCC_PERIPHCLK_OSPI | RCC_PERIPHCLK_FDCAN1 | \
RCC_PERIPHCLK_DAC1 | RCC_PERIPHCLK_HSPI | RCC_PERIPHCLK_LTDC | \
RCC_PERIPHCLK_DSI | RCC_PERIPHCLK_USBPHY;
#elif ( defined(STM32U595xx) || defined(STM32U5A5xx))
pPeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | \
RCC_PERIPHCLK_UART4 | RCC_PERIPHCLK_UART5 | RCC_PERIPHCLK_USART6 | \
RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | \
RCC_PERIPHCLK_I2C3 | RCC_PERIPHCLK_I2C5 | RCC_PERIPHCLK_I2C6 | \
RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_LPTIM34 | RCC_PERIPHCLK_LPTIM2 | \
RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2 | RCC_PERIPHCLK_ADCDAC | \
RCC_PERIPHCLK_MDF1 | RCC_PERIPHCLK_ADF1 | RCC_PERIPHCLK_RTC | \
RCC_PERIPHCLK_ICLK | RCC_PERIPHCLK_SDMMC | RCC_PERIPHCLK_RNG | \
RCC_PERIPHCLK_I2C4 | RCC_PERIPHCLK_SPI1 | RCC_PERIPHCLK_SPI2 | \
RCC_PERIPHCLK_SPI3 | RCC_PERIPHCLK_OSPI | RCC_PERIPHCLK_FDCAN1 | \
RCC_PERIPHCLK_DAC1 | RCC_PERIPHCLK_HSPI | RCC_PERIPHCLK_USBPHY;
#else
pPeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | \
RCC_PERIPHCLK_UART4 | RCC_PERIPHCLK_UART5 | RCC_PERIPHCLK_LPUART1 | \
RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \
RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_LPTIM34 | RCC_PERIPHCLK_LPTIM2 | \
RCC_PERIPHCLK_SAES | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2 | \
RCC_PERIPHCLK_ADCDAC | RCC_PERIPHCLK_MDF1 | RCC_PERIPHCLK_ADF1 | \
RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_ICLK | RCC_PERIPHCLK_SDMMC | \
RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_I2C4 | RCC_PERIPHCLK_SPI1 | \
RCC_PERIPHCLK_SPI2 | RCC_PERIPHCLK_SPI3 | RCC_PERIPHCLK_OSPI | \
RCC_PERIPHCLK_FDCAN1 | RCC_PERIPHCLK_DAC1;
#endif /* defined(STM32U599xx) || defined(STM32U5A9xx) */
/* Get the PLL2 Clock configuration -----------------------------------------------*/
pPeriphClkInit->PLL2.PLL2Source = (uint32_t)((RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2SRC) >> RCC_PLL2CFGR_PLL2SRC_Pos);
pPeriphClkInit->PLL2.PLL2M = (uint32_t)((RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2M) >> RCC_PLL2CFGR_PLL2M_Pos) + 1U;
pPeriphClkInit->PLL2.PLL2N = (uint32_t)((RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2N) >> RCC_PLL2DIVR_PLL2N_Pos) + 1U;
pPeriphClkInit->PLL2.PLL2P = (uint32_t)((RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2P) >> RCC_PLL2DIVR_PLL2P_Pos) + 1U;
pPeriphClkInit->PLL2.PLL2Q = (uint32_t)((RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2Q) >> RCC_PLL2DIVR_PLL2Q_Pos) + 1U;
pPeriphClkInit->PLL2.PLL2R = (uint32_t)((RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2R) >> RCC_PLL2DIVR_PLL2R_Pos) + 1U;
pPeriphClkInit->PLL2.PLL2RGE = (uint32_t)((RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2RGE) >> RCC_PLL2CFGR_PLL2RGE_Pos);
pPeriphClkInit->PLL2.PLL2FRACN = (uint32_t)((RCC->PLL2FRACR & RCC_PLL2FRACR_PLL2FRACN) >> \
RCC_PLL2FRACR_PLL2FRACN_Pos);
/* Get the PLL3 Clock configuration -----------------------------------------------*/
pPeriphClkInit->PLL3.PLL3Source = (uint32_t)((RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3SRC) >> RCC_PLL3CFGR_PLL3SRC_Pos);
pPeriphClkInit->PLL3.PLL3M = (uint32_t)((RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3M) >> RCC_PLL3CFGR_PLL3M_Pos) + 1U;
pPeriphClkInit->PLL3.PLL3N = (uint32_t)((RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3N) >> RCC_PLL3DIVR_PLL3N_Pos) + 1U;
pPeriphClkInit->PLL3.PLL3P = (uint32_t)((RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3P) >> RCC_PLL3DIVR_PLL3P_Pos) + 1U;
pPeriphClkInit->PLL3.PLL3Q = (uint32_t)((RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3Q) >> RCC_PLL3DIVR_PLL3Q_Pos) + 1U;
pPeriphClkInit->PLL3.PLL3R = (uint32_t)((RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3R) >> RCC_PLL3DIVR_PLL3R_Pos) + 1U;
pPeriphClkInit->PLL3.PLL3RGE = (uint32_t)((RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3RGE) >> RCC_PLL3CFGR_PLL3RGE_Pos);
pPeriphClkInit->PLL3.PLL3FRACN = (uint32_t)((RCC->PLL3FRACR & RCC_PLL3FRACR_PLL3FRACN) >> \
RCC_PLL3FRACR_PLL3FRACN_Pos);
/* Get the USART1 clock source ---------------------------------------------*/
pPeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE();
/* Get the USART2 clock source ---------------------------------------------*/
pPeriphClkInit->Usart2ClockSelection = __HAL_RCC_GET_USART2_SOURCE();
/* Get the USART3 clock source ---------------------------------------------*/
pPeriphClkInit->Usart3ClockSelection = __HAL_RCC_GET_USART3_SOURCE();
/* Get the UART4 clock source ----------------------------------------------*/
pPeriphClkInit->Uart4ClockSelection = __HAL_RCC_GET_UART4_SOURCE();
/* Get the UART5 clock source ----------------------------------------------*/
pPeriphClkInit->Uart5ClockSelection = __HAL_RCC_GET_UART5_SOURCE();
/* Get the LPUART1 clock source --------------------------------------------*/
pPeriphClkInit->Lpuart1ClockSelection = __HAL_RCC_GET_LPUART1_SOURCE();
#if defined(USART6)
/* Get the UART6 clock source ---------------------------------------------*/
pPeriphClkInit->Usart6ClockSelection = __HAL_RCC_GET_USART6_SOURCE();
#endif /* defined(USART6) */
/* Get the I2C1 clock source -----------------------------------------------*/
pPeriphClkInit->I2c1ClockSelection = __HAL_RCC_GET_I2C1_SOURCE();
/* Get the I2C2 clock source -----------------------------------------------*/
pPeriphClkInit->I2c2ClockSelection = __HAL_RCC_GET_I2C2_SOURCE();
/* Get the I2C3 clock source -----------------------------------------------*/
pPeriphClkInit->I2c3ClockSelection = __HAL_RCC_GET_I2C3_SOURCE();
/* Get the I2C4 clock source -----------------------------------------------*/
pPeriphClkInit->I2c4ClockSelection = __HAL_RCC_GET_I2C4_SOURCE();
#if defined(I2C5)
/* Get the clock source ---------------------------------------------*/
pPeriphClkInit->I2c5ClockSelection = __HAL_RCC_GET_I2C5_SOURCE();
#endif /* defined(I2C5) */
#if defined(I2C6)
/* Get the clock source ---------------------------------------------*/
pPeriphClkInit->I2c6ClockSelection = __HAL_RCC_GET_I2C6_SOURCE();
#endif /* defined(I2C6) */
/* Get the LPTIM1 clock source ---------------------------------------------*/
pPeriphClkInit->Lptim1ClockSelection = __HAL_RCC_GET_LPTIM1_SOURCE();
/* Get the LPTIM2 clock source ---------------------------------------------*/
pPeriphClkInit->Lptim2ClockSelection = __HAL_RCC_GET_LPTIM2_SOURCE();
/* Get the LPTIM34 clock source --------------------------------------------*/
pPeriphClkInit->Lptim34ClockSelection = __HAL_RCC_GET_LPTIM34_SOURCE();
/* Get the FDCAN1 clock source ---------------------------------------------*/
pPeriphClkInit->Fdcan1ClockSelection = __HAL_RCC_GET_FDCAN1_SOURCE();
/* Get the MDF1 clock source -----------------------------------------------*/
pPeriphClkInit->Mdf1ClockSelection = __HAL_RCC_GET_MDF1_SOURCE();
/* Get the ADF1 clock source -----------------------------------------------*/
pPeriphClkInit->Adf1ClockSelection = __HAL_RCC_GET_ADF1_SOURCE();
/* Get the SAES clock source -----------------------------------------------*/
pPeriphClkInit->SaesClockSelection = __HAL_RCC_GET_SAES_SOURCE();
/* Get the SAI1 clock source -----------------------------------------------*/
pPeriphClkInit->Sai1ClockSelection = __HAL_RCC_GET_SAI1_SOURCE();
/* Get the SAI2 clock source -----------------------------------------------*/
pPeriphClkInit->Sai2ClockSelection = __HAL_RCC_GET_SAI2_SOURCE();
/* Get the CLK48 clock source ----------------------------------------------*/
pPeriphClkInit->IclkClockSelection = __HAL_RCC_GET_ICLK_SOURCE();
/* Get the SDMMC clock source ----------------------------------------------*/
pPeriphClkInit->SdmmcClockSelection = __HAL_RCC_GET_SDMMC_SOURCE();
/* Get the ADCDAC clock source ---------------------------------------------*/
pPeriphClkInit->AdcDacClockSelection = __HAL_RCC_GET_ADCDAC_SOURCE();
/* Get the DAC1 clock source -----------------------------------------------*/
pPeriphClkInit->Dac1ClockSelection = __HAL_RCC_GET_DAC1_SOURCE();
/* Get the OSPI clock source -----------------------------------------------*/
pPeriphClkInit->OspiClockSelection = __HAL_RCC_GET_OSPI_SOURCE();
/* Get the SPI1 clock source -----------------------------------------------*/
pPeriphClkInit->Spi1ClockSelection = __HAL_RCC_GET_SPI1_SOURCE();
/* Get the SPI2 clock source -----------------------------------------------*/
pPeriphClkInit->Spi2ClockSelection = __HAL_RCC_GET_SPI2_SOURCE();
/* Get the SPI3 clock source -----------------------------------------------*/
pPeriphClkInit->Spi3ClockSelection = __HAL_RCC_GET_SPI3_SOURCE();
/* Get the RTC clock source ------------------------------------------------*/
pPeriphClkInit->RTCClockSelection = __HAL_RCC_GET_RTC_SOURCE();
/* Get the RNG clock source ------------------------------------------------*/
pPeriphClkInit->RngClockSelection = __HAL_RCC_GET_RNG_SOURCE();
#if defined(HSPI1)
/* Get the HSPI kernel clock source ------------------------------------------------*/
pPeriphClkInit->HspiClockSelection = __HAL_RCC_GET_HSPI_SOURCE();
#endif /* defined(HSPI1) */
#if defined(LTDC)
/* Get the LTDC clock source ------------------------------------------------*/
pPeriphClkInit->LtdcClockSelection = __HAL_RCC_GET_LTDC_SOURCE();
#endif /* defined(LTDC) */
#if defined(DSI)
/* Get the DSI clock source ------------------------------------------------*/
pPeriphClkInit->DsiClockSelection = __HAL_RCC_GET_DSI_SOURCE();
#endif /* defined(DSI) */
#if defined(USB_OTG_HS)
/* Get the USB PHY clock source ------------------------------------------------*/
pPeriphClkInit->UsbPhyClockSelection = __HAL_RCC_GET_USBPHY_SOURCE();
#endif /* defined(USB_OTG_HS) */
}
/**
* @brief Returns the PLL1 clock frequencies :PLL1_P_Frequency,PLL1_R_Frequency and PLL1_Q_Frequency
* @note The PLL1 clock frequencies computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
* @note The function returns values based on HSE_VALUE, HSI_VALUE or MSI Value multiplied/divided by the PLL
* factors.
* @note This function can be used by the user application to compute the
* baud-rate for the communication peripherals or configure other parameters.
*
* @note Each time PLL1CLK changes, this function must be called to update the
* right PLL1CLK value. Otherwise, any configuration based on this function will be incorrect.
* @param PLL1_Clocks structure.
* @retval None
*/
void HAL_RCCEx_GetPLL1ClockFreq(PLL1_ClocksTypeDef *PLL1_Clocks)
{
uint32_t pll1source;
uint32_t pll1m;
uint32_t pll1n;
uint32_t pll1fracen;
float_t fracn1;
float_t pll1vco;
pll1n = (RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N);
pll1source = (RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1SRC);
pll1m = ((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1M) >> RCC_PLL1CFGR_PLL1M_Pos) + 1U;
pll1fracen = RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1FRACEN;
fracn1 = (float_t)(uint32_t)(pll1fracen * ((RCC->PLL1FRACR & RCC_PLL1FRACR_PLL1FRACN) >> \
RCC_PLL1FRACR_PLL1FRACN_Pos));
if (pll1m != 0U)
{
switch (pll1source)
{
case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pll1vco = ((float_t)HSI_VALUE / (float_t)pll1m) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pll1vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t)pll1m) * \
((float_t)pll1n + (fracn1 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pll1vco = ((float_t)HSE_VALUE / (float_t)pll1m) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1 / (float_t)0x2000) + (float_t)1);
break;
default:
pll1vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t)pll1m) * \
((float_t)pll1n + (fracn1 / (float_t)0x2000) + (float_t)1);
break;
}
if (__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL1_DIVP) != 0U)
{
PLL1_Clocks->PLL1_P_Frequency = (uint32_t)(float_t)(pll1vco / ((float_t)(uint32_t)((RCC->PLL1DIVR & \
RCC_PLL1DIVR_PLL1P) >> RCC_PLL1DIVR_PLL1P_Pos) + \
(float_t)1));
}
else
{
PLL1_Clocks->PLL1_P_Frequency = 0U;
}
if (__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL1_DIVQ) != 0U)
{
PLL1_Clocks->PLL1_Q_Frequency = (uint32_t)(float_t)(pll1vco / ((float_t)(uint32_t)((RCC->PLL1DIVR & \
RCC_PLL1DIVR_PLL1Q) >> RCC_PLL1DIVR_PLL1Q_Pos) + \
(float_t)1));
}
else
{
PLL1_Clocks->PLL1_Q_Frequency = 0U;
}
if (__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL1_DIVR) != 0U)
{
PLL1_Clocks->PLL1_R_Frequency = (uint32_t)(float_t)(pll1vco / ((float_t)(uint32_t)((RCC->PLL1DIVR & \
RCC_PLL1DIVR_PLL1R) >> RCC_PLL1DIVR_PLL1R_Pos) + \
(float_t)1));
}
else
{
PLL1_Clocks->PLL1_R_Frequency = 0U;
}
}
else
{
PLL1_Clocks->PLL1_P_Frequency = 0U;
PLL1_Clocks->PLL1_Q_Frequency = 0U;
PLL1_Clocks->PLL1_R_Frequency = 0U;
}
}
/**
* @brief Returns the PLL2 clock frequencies :PLL2_P_Frequency,PLL2_R_Frequency and PLL2_Q_Frequency
* @note The PLL2 clock frequencies computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
* @note The function returns values based on HSE_VALUE, HSI_VALUE or CSI Value multiplied/divided by the PLL
* factors.
* @note This function can be used by the user application to compute the
* baud-rate for the communication peripherals or configure other parameters.
*
* @note Each time PLL2CLK changes, this function must be called to update the
* right PLL2CLK value. Otherwise, any configuration based on this function will be incorrect.
* @param PLL2_Clocks structure.
* @retval None
*/
void HAL_RCCEx_GetPLL2ClockFreq(PLL2_ClocksTypeDef *PLL2_Clocks)
{
uint32_t pll2source;
uint32_t pll2m;
uint32_t pll2n;
uint32_t pll2fracen;
float_t fracn2;
float_t pll2vco;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLL2M) * PLL2N
PLL2xCLK = PLL2_VCO / PLL2x */
pll2n = (RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2N);
pll2source = (RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2SRC);
pll2m = ((RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2M) >> RCC_PLL2CFGR_PLL2M_Pos) + 1U;
pll2fracen = RCC->PLL2CFGR & RCC_PLL2CFGR_PLL2FRACEN;
fracn2 = (float_t)(uint32_t)(pll2fracen * ((RCC->PLL2FRACR & RCC_PLL2FRACR_PLL2FRACN) >> \
RCC_PLL2FRACR_PLL2FRACN_Pos));
if (pll2m != 0U)
{
switch (pll2source)
{
case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pll2vco = ((float_t)HSI_VALUE / (float_t)pll2m) * ((float_t)(uint32_t)(RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2N) + \
(fracn2 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pll2vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t)pll2m) * \
((float_t)pll2n + (fracn2 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pll2vco = ((float_t)HSE_VALUE / (float_t)pll2m) * ((float_t)(uint32_t)(RCC->PLL2DIVR & RCC_PLL2DIVR_PLL2N) + \
(fracn2 / (float_t)0x2000) + (float_t)1);
break;
default:
pll2vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t) pll2m) \
* ((float_t)pll2n + (fracn2 / (float_t)0x2000) + (float_t)1);
break;
}
if (__HAL_RCC_GET_PLL2CLKOUT_CONFIG(RCC_PLL2_DIVP) != 0U)
{
PLL2_Clocks->PLL2_P_Frequency = (uint32_t)(float_t)(pll2vco / ((float_t)(uint32_t)((RCC->PLL2DIVR & \
RCC_PLL2DIVR_PLL2P) >> RCC_PLL2DIVR_PLL2P_Pos) + \
(float_t)1));
}
else
{
PLL2_Clocks->PLL2_P_Frequency = 0U;
}
if (__HAL_RCC_GET_PLL2CLKOUT_CONFIG(RCC_PLL2_DIVQ) != 0U)
{
PLL2_Clocks->PLL2_Q_Frequency = (uint32_t)(float_t)(pll2vco / ((float_t)(uint32_t)((RCC->PLL2DIVR & \
RCC_PLL2DIVR_PLL2Q) >> RCC_PLL2DIVR_PLL2Q_Pos) + \
(float_t)1));
}
else
{
PLL2_Clocks->PLL2_Q_Frequency = 0U;
}
if (__HAL_RCC_GET_PLL2CLKOUT_CONFIG(RCC_PLL2_DIVR) != 0U)
{
PLL2_Clocks->PLL2_R_Frequency = (uint32_t)(float_t)(pll2vco / ((float_t)(uint32_t)((RCC->PLL2DIVR & \
RCC_PLL2DIVR_PLL2R) >> RCC_PLL2DIVR_PLL2R_Pos) + \
(float_t)1));
}
else
{
PLL2_Clocks->PLL2_R_Frequency = 0U;
}
}
else
{
PLL2_Clocks->PLL2_P_Frequency = 0U;
PLL2_Clocks->PLL2_Q_Frequency = 0U;
PLL2_Clocks->PLL2_R_Frequency = 0U;
}
}
/**
* @brief Returns the PLL3 clock frequencies :PLL3_P_Frequency,PLL3_R_Frequency and PLL3_Q_Frequency
* @note The PLL3 clock frequencies computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
* @note The function returns values based on HSE_VALUE, HSI_VALUE or CSI Value multiplied/divided by the PLL
* factors.
* @note This function can be used by the user application to compute the
* baud-rate for the communication peripherals or configure other parameters.
*
* @note Each time PLL3CLK changes, this function must be called to update the
* right PLL3CLK value. Otherwise, any configuration based on this function will be incorrect.
* @param PLL3_Clocks structure.
* @retval None
*/
void HAL_RCCEx_GetPLL3ClockFreq(PLL3_ClocksTypeDef *PLL3_Clocks)
{
uint32_t pll3source;
uint32_t pll3m;
uint32_t pll3n;
uint32_t pll3fracen;
float_t fracn3;
float_t pll3vco;
/* PLL3_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLL3M) * PLL3N
PLL3xCLK = PLL3_VCO / PLLxR
*/
pll3n = (RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3N);
pll3source = (RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3SRC);
pll3m = ((RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3M) >> RCC_PLL3CFGR_PLL3M_Pos) + 1U;
pll3fracen = RCC->PLL3CFGR & RCC_PLL3CFGR_PLL3FRACEN;
fracn3 = (float_t)(uint32_t)(pll3fracen * ((RCC->PLL3FRACR & RCC_PLL3FRACR_PLL3FRACN) >> \
RCC_PLL3FRACR_PLL3FRACN_Pos));
if (pll3m != 0U)
{
switch (pll3source)
{
case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pll3vco = ((float_t)HSI_VALUE / (float_t)pll3m) * ((float_t)(uint32_t)(RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3N) + \
(fracn3 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pll3vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t)pll3m) * \
((float_t)pll3n + (fracn3 / (float_t)0x2000) + (float_t)1);
break;
case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pll3vco = ((float_t)HSE_VALUE / (float_t)pll3m) * ((float_t)(uint32_t)(RCC->PLL3DIVR & RCC_PLL3DIVR_PLL3N) + \
(fracn3 / (float_t)0x2000) + (float_t)1);
break;
default:
pll3vco = ((float_t)MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)] / (float_t)pll3m) * \
((float_t)pll3n + (fracn3 / (float_t)0x2000) + (float_t)1);
break;
}
if (__HAL_RCC_GET_PLL3CLKOUT_CONFIG(RCC_PLL3_DIVP) != 0U)
{
PLL3_Clocks->PLL3_P_Frequency = (uint32_t)(float_t)(pll3vco / ((float_t)(uint32_t)((RCC->PLL3DIVR & \
RCC_PLL3DIVR_PLL3P) >> RCC_PLL3DIVR_PLL3P_Pos) + \
(float_t)1));
}
else
{
PLL3_Clocks->PLL3_P_Frequency = 0U;
}
if (__HAL_RCC_GET_PLL3CLKOUT_CONFIG(RCC_PLL3_DIVQ) != 0U)
{
PLL3_Clocks->PLL3_Q_Frequency = (uint32_t)(float_t)(pll3vco / ((float_t)(uint32_t)((RCC->PLL3DIVR & \
RCC_PLL3DIVR_PLL3Q) >> RCC_PLL3DIVR_PLL3Q_Pos) + \
(float_t)1));
}
else
{
PLL3_Clocks->PLL3_Q_Frequency = 0U;
}
if (__HAL_RCC_GET_PLL3CLKOUT_CONFIG(RCC_PLL3_DIVR) != 0U)
{
PLL3_Clocks->PLL3_R_Frequency = (uint32_t)(float_t)(pll3vco / ((float_t)(uint32_t)((RCC->PLL3DIVR & \
RCC_PLL3DIVR_PLL3R) >> RCC_PLL3DIVR_PLL3R_Pos) + \
(float_t)1));
}
else
{
PLL3_Clocks->PLL3_R_Frequency = 0U;
}
}
else
{
PLL3_Clocks->PLL3_P_Frequency = 0U;
PLL3_Clocks->PLL3_Q_Frequency = 0U;
PLL3_Clocks->PLL3_R_Frequency = 0U;
}
}
/**
* @brief Return the peripheral clock frequency for peripherals
* @note Return 0 if peripheral clock identifier not managed by this API
* @param PeriphClk Peripheral clock identifier
* This parameter can be one of the following values:
* @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock
* @arg @ref RCC_PERIPHCLK_USART2 USART2 peripheral clock
* @arg @ref RCC_PERIPHCLK_USART3 USART3 peripheral clock
* @arg @ref RCC_PERIPHCLK_UART4 UART4 peripheral clock
* @arg @ref RCC_PERIPHCLK_UART5 UART5 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPUART1 LPUART1 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C2 I2C2 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C3 I2C3 peripheral clock
* @arg @ref RCC_PERIPHCLK_I2C4 I2C4 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPTIM34 LPTIM34 peripheral clock
* @arg @ref RCC_PERIPHCLK_LPTIM2 LPTIM2 peripheral clock
* @arg @ref RCC_PERIPHCLK_SAI1 SAI1 peripheral clock
* @arg @ref RCC_PERIPHCLK_SAI2 SAI2 peripheral clock
* @arg @ref RCC_PERIPHCLK_ADCDAC ADC1 ADC2 ADC4 DAC1 peripheral clock
* @arg @ref RCC_PERIPHCLK_MDF1 MDF1 peripheral clock
* @arg @ref RCC_PERIPHCLK_ADF1 ADF1 peripheral clock
* @arg @ref RCC_PERIPHCLK_RTC RTC peripheral clock
* @arg @ref RCC_PERIPHCLK_ICLK ICLK peripheral clock
* @arg @ref RCC_PERIPHCLK_SDMMC SDMMC peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI1 SPI1 peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI2 SPI2 peripheral clock
* @arg @ref RCC_PERIPHCLK_SPI3 SPI3 peripheral clock
* @arg @ref RCC_PERIPHCLK_OSPI OSPI peripheral clock
* @arg @ref RCC_PERIPHCLK_FDCAN1 FDCAN1 peripheral clock
* @arg @ref RCC_PERIPHCLK_DAC1 DAC1 peripheral clock
* @retval Frequency in Hz
*/
uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint64_t PeriphClk)
{
PLL1_ClocksTypeDef pll1_clocks;
PLL2_ClocksTypeDef pll2_clocks;
PLL3_ClocksTypeDef pll3_clocks;
uint32_t frequency;
uint32_t srcclk;
/* Check the parameters */
assert_param(IS_RCC_PERIPHCLOCK(PeriphClk));
if (PeriphClk == RCC_PERIPHCLK_RTC)
{
/* Get the current RTC source */
srcclk = __HAL_RCC_GET_RTC_SOURCE();
/* Check if LSE is ready and if RTC clock selection is LSE */
if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_RTCCLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Check if LSI is ready and if RTC clock selection is LSI */
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIRDY)) && (srcclk == RCC_RTCCLKSOURCE_LSI))
{
if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIPREDIV))
{
frequency = LSI_VALUE / 128U;
}
else
{
frequency = LSI_VALUE;
}
}
/* Check if HSE is ready and if RTC clock selection is HSI_DIV32*/
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)) && (srcclk == RCC_RTCCLKSOURCE_HSE_DIV32))
{
frequency = HSE_VALUE / 32U;
}
/* Clock not enabled for RTC*/
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SAI1)
{
srcclk = __HAL_RCC_GET_SAI1_SOURCE();
switch (srcclk)
{
case RCC_SAI1CLKSOURCE_PLL1: /* PLL1P is the clock source for SAI1 */
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_P_Frequency;
break;
case RCC_SAI1CLKSOURCE_PLL2: /* PLL2P is the clock source for SAI1 */
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_P_Frequency;
break;
case RCC_SAI1CLKSOURCE_PLL3: /* PLLI3P is the clock source for SAI1 */
HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks);
frequency = pll3_clocks.PLL3_P_Frequency;
break;
case RCC_SAI1CLKSOURCE_PIN:
frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case RCC_SAI1CLKSOURCE_HSI: /* HSI is the clock source for SAI1 */
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
default :
{
frequency = 0U;
break;
}
}
}
else if (PeriphClk == RCC_PERIPHCLK_SAI2)
{
srcclk = __HAL_RCC_GET_SAI2_SOURCE();
switch (srcclk)
{
case RCC_SAI2CLKSOURCE_PLL1: /* PLL1P is the clock source for SAI1 */
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_P_Frequency;
break;
case RCC_SAI2CLKSOURCE_PLL2: /* PLL2P is the clock source for SAI1 */
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_P_Frequency;
break;
case RCC_SAI2CLKSOURCE_PLL3: /* PLLI3P is the clock source for SAI1 */
HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks);
frequency = pll3_clocks.PLL3_P_Frequency;
break;
case RCC_SAI2CLKSOURCE_PIN:
frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case RCC_SAI2CLKSOURCE_HSI: /* HSI is the clock source for SAI1 */
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
default :
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SAES)
{
/* Get the current SAES source */
srcclk = __HAL_RCC_GET_SAES_SOURCE();
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY) && (srcclk == RCC_SAESCLKSOURCE_SHSI))
{
frequency = HSI_VALUE;
}
else if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY) && (srcclk == RCC_SAESCLKSOURCE_SHSI_DIV2))
{
frequency = HSI_VALUE >> 1U;
}
/* Clock not enabled for SAES */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_ICLK)
{
srcclk = __HAL_RCC_GET_ICLK_SOURCE();
switch (srcclk)
{
case RCC_ICLK_CLKSOURCE_PLL1: /* PLL1Q */
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_Q_Frequency;
break;
case RCC_ICLK_CLKSOURCE_PLL2: /* PLL2Q */
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_Q_Frequency;
break;
case RCC_ICLK_CLKSOURCE_HSI48: /* HSI48 */
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSI48RDY))
{
frequency = HSI48_VALUE;
}
else
{
frequency = 0U;
}
break;
case RCC_ICLK_CLKSOURCE_MSIK: /* MSIK frequency range in HZ */
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default :
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SDMMC)
{
srcclk = __HAL_RCC_GET_SDMMC_SOURCE();
if (srcclk == RCC_SDMMCCLKSOURCE_CLK48)
{
srcclk = __HAL_RCC_GET_ICLK_SOURCE();
switch (srcclk)
{
case RCC_ICLK_CLKSOURCE_PLL1: /* PLL1Q */
{
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_Q_Frequency;
break;
}
case RCC_ICLK_CLKSOURCE_PLL2: /* PLL2Q */
{
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_Q_Frequency;
break;
}
case RCC_ICLK_CLKSOURCE_HSI48: /* HSI48 */
{
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSI48RDY))
{
frequency = HSI48_VALUE;
}
else
{
frequency = 0U;
}
break;
}
case RCC_ICLK_CLKSOURCE_MSIK: /* MSIK frequency range in HZ */
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
}
default :
{
frequency = 0U;
break;
}
}
}
else if (srcclk == RCC_SDMMCCLKSOURCE_PLL1)
{
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_P_Frequency;
}
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_USART1)
{
/* Get the current USART1 source */
srcclk = __HAL_RCC_GET_USART1_SOURCE();
if (srcclk == RCC_USART1CLKSOURCE_PCLK2)
{
frequency = HAL_RCC_GetPCLK2Freq();
}
else if (srcclk == RCC_USART1CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART1CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART1CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for USART1 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_USART2)
{
/* Get the current USART2 source */
srcclk = __HAL_RCC_GET_USART2_SOURCE();
if (srcclk == RCC_USART2CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_USART2CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART2CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART2CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for USART2 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_USART3)
{
/* Get the current USART3 source */
srcclk = __HAL_RCC_GET_USART3_SOURCE();
if (srcclk == RCC_USART3CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_USART3CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART3CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART3CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for USART3 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_UART4)
{
/* Get the current UART4 source */
srcclk = __HAL_RCC_GET_UART4_SOURCE();
if (srcclk == RCC_UART4CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_UART4CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_UART4CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_UART4CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for UART4 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_UART5)
{
/* Get the current UART5 source */
srcclk = __HAL_RCC_GET_UART5_SOURCE();
if (srcclk == RCC_UART5CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_UART5CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_UART5CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_UART5CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for UART5 */
else
{
frequency = 0U;
}
}
#if defined(USART6)
else if (PeriphClk == RCC_PERIPHCLK_USART6)
{
/* Get the current USART6 source */
srcclk = __HAL_RCC_GET_USART6_SOURCE();
if (srcclk == RCC_USART6CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_USART6CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART6CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART6CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for UART5 */
else
{
frequency = 0U;
}
}
#endif /* USART6 */
else if (PeriphClk == RCC_PERIPHCLK_LPUART1)
{
/* Get the current LPUART1 source */
srcclk = __HAL_RCC_GET_LPUART1_SOURCE();
if (srcclk == RCC_LPUART1CLKSOURCE_PCLK3)
{
frequency = HAL_RCC_GetPCLK3Freq();
}
else if (srcclk == RCC_LPUART1CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPUART1CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPUART1CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_LPUART1CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for LPUART1 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_ADCDAC)
{
srcclk = __HAL_RCC_GET_ADCDAC_SOURCE();
if (srcclk == RCC_ADCDACCLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if (srcclk == RCC_ADCDACCLKSOURCE_PLL2)
{
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_R_Frequency;
}
else if (srcclk == RCC_ADCDACCLKSOURCE_HCLK)
{
frequency = HAL_RCC_GetHCLKFreq();
}
else if (srcclk == RCC_ADCDACCLKSOURCE_MSIK)
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)];
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)) && (srcclk == RCC_ADCDACCLKSOURCE_HSE))
{
frequency = HSE_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_ADCDACCLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
/* Clock not enabled for ADC */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_MDF1)
{
/* Get the current MDF1 source */
srcclk = __HAL_RCC_GET_MDF1_SOURCE();
switch (srcclk)
{
case RCC_MDF1CLKSOURCE_PLL1:
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_P_Frequency;
break;
case RCC_MDF1CLKSOURCE_PLL3:
HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks);
frequency = pll3_clocks.PLL3_Q_Frequency;
break;
case RCC_MDF1CLKSOURCE_HCLK:
frequency = HAL_RCC_GetHCLKFreq();
break;
case RCC_MDF1CLKSOURCE_PIN:
frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case RCC_MDF1CLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_ADF1)
{
/* Get the current ADF1 source */
srcclk = __HAL_RCC_GET_ADF1_SOURCE();
switch (srcclk)
{
case RCC_ADF1CLKSOURCE_PLL1:
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_P_Frequency;
break;
case RCC_ADF1CLKSOURCE_PLL3:
HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks);
frequency = pll3_clocks.PLL3_Q_Frequency;
break;
case RCC_ADF1CLKSOURCE_HCLK:
frequency = HAL_RCC_GetHCLKFreq();
break;
case RCC_ADF1CLKSOURCE_PIN:
frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case RCC_ADF1CLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_I2C1)
{
/* Get the current I2C1 source */
srcclk = __HAL_RCC_GET_I2C1_SOURCE();
if (srcclk == RCC_I2C1CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_I2C1CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C1CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_I2C1CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for I2C1 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_I2C2)
{
/* Get the current I2C2 source */
srcclk = __HAL_RCC_GET_I2C2_SOURCE();
if (srcclk == RCC_I2C2CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_I2C2CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C2CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_I2C2CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for I2C2 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_I2C3)
{
/* Get the current I2C3 source */
srcclk = __HAL_RCC_GET_I2C3_SOURCE();
switch (srcclk)
{
case RCC_I2C3CLKSOURCE_PCLK3:
{
frequency = HAL_RCC_GetPCLK3Freq();
break;
}
case RCC_I2C3CLKSOURCE_HSI:
{
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
}
case RCC_I2C3CLKSOURCE_SYSCLK:
{
frequency = HAL_RCC_GetSysClockFreq();
break;
}
case RCC_I2C3CLKSOURCE_MSIK:
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSI_RANGE() >> RCC_ICSCR1_MSISRANGE_Pos)];
break;
}
default:
{
frequency = 0U;
break;
}
}
}
else if (PeriphClk == RCC_PERIPHCLK_I2C4)
{
/* Get the current I2C4 source */
srcclk = __HAL_RCC_GET_I2C4_SOURCE();
if (srcclk == RCC_I2C4CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_I2C4CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C4CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_I2C4CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for I2C4 */
else
{
frequency = 0U;
}
}
#if defined (I2C5)
else if (PeriphClk == RCC_PERIPHCLK_I2C5)
{
/* Get the current I2C5 source */
srcclk = __HAL_RCC_GET_I2C5_SOURCE();
if (srcclk == RCC_I2C5CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_I2C5CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C5CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_I2C5CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for I2C5 */
else
{
frequency = 0U;
}
}
#endif /* I2C5 */
#if defined (I2C6)
else if (PeriphClk == RCC_PERIPHCLK_I2C6)
{
/* Get the current I2C6 source */
srcclk = __HAL_RCC_GET_I2C6_SOURCE();
if (srcclk == RCC_I2C6CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if (srcclk == RCC_I2C6CLKSOURCE_SYSCLK)
{
frequency = HAL_RCC_GetSysClockFreq();
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C6CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_MSIKRDY)) && (srcclk == RCC_I2C6CLKSOURCE_MSIK))
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
/* Clock not enabled for I2C6 */
else
{
frequency = 0U;
}
}
#endif /* I2C6 */
else if (PeriphClk == RCC_PERIPHCLK_LPTIM34)
{
/* Get the current LPTIM34 source */
srcclk = __HAL_RCC_GET_LPTIM34_SOURCE();
if (srcclk == RCC_LPTIM34CLKSOURCE_MSIK)
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIRDY)) && (srcclk == RCC_LPTIM34CLKSOURCE_LSI))
{
if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIPREDIV))
{
frequency = LSI_VALUE / 128U;
}
else
{
frequency = LSI_VALUE;
}
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPTIM34CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPTIM34CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for LPTIM34 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_LPTIM1)
{
/* Get the current LPTIM1 source */
srcclk = __HAL_RCC_GET_LPTIM1_SOURCE();
if (srcclk == RCC_LPTIM1CLKSOURCE_MSIK)
{
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIRDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_LSI))
{
if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIPREDIV))
{
frequency = LSI_VALUE / 128U;
}
else
{
frequency = LSI_VALUE;
}
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for LPTIM1 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_LPTIM2)
{
/* Get the current LPTIM2 source */
srcclk = __HAL_RCC_GET_LPTIM2_SOURCE();
if (srcclk == RCC_LPTIM2CLKSOURCE_PCLK1)
{
frequency = HAL_RCC_GetPCLK1Freq();
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIRDY)) && (srcclk == RCC_LPTIM2CLKSOURCE_LSI))
{
if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIPREDIV))
{
frequency = LSI_VALUE / 128U;
}
else
{
frequency = LSI_VALUE;
}
}
else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPTIM2CLKSOURCE_HSI))
{
frequency = HSI_VALUE;
}
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPTIM2CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Clock not enabled for LPTIM2 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_FDCAN1)
{
/* Get the current FDCAN1 kernel source */
srcclk = __HAL_RCC_GET_FDCAN1_SOURCE();
if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)) && (srcclk == RCC_FDCAN1CLKSOURCE_HSE))
{
frequency = HSE_VALUE;
}
else if (srcclk == RCC_FDCAN1CLKSOURCE_PLL1) /* PLL1 ? */
{
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_Q_Frequency;
}
else if (srcclk == RCC_FDCAN1CLKSOURCE_PLL2) /* PLL2 ? */
{
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_P_Frequency;
}
/* Clock not enabled for FDCAN1 */
else
{
frequency = 0U;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SPI1)
{
/* Get the current SPI1 kernel source */
srcclk = __HAL_RCC_GET_SPI1_SOURCE();
switch (srcclk)
{
case RCC_SPI1CLKSOURCE_PCLK2:
frequency = HAL_RCC_GetPCLK2Freq();
break;
case RCC_SPI1CLKSOURCE_SYSCLK:
frequency = HAL_RCC_GetSysClockFreq();
break;
case RCC_SPI1CLKSOURCE_HSI:
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
case RCC_SPI1CLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SPI2)
{
/* Get the current SPI2 kernel source */
srcclk = __HAL_RCC_GET_SPI2_SOURCE();
switch (srcclk)
{
case RCC_SPI2CLKSOURCE_PCLK1:
frequency = HAL_RCC_GetPCLK1Freq();
break;
case RCC_SPI2CLKSOURCE_SYSCLK:
frequency = HAL_RCC_GetSysClockFreq();
break;
case RCC_SPI2CLKSOURCE_HSI:
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
case RCC_SPI2CLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_SPI3)
{
/* Get the current SPI3 kernel source */
srcclk = __HAL_RCC_GET_SPI3_SOURCE();
switch (srcclk)
{
case RCC_SPI3CLKSOURCE_PCLK3:
frequency = HAL_RCC_GetPCLK3Freq();
break;
case RCC_SPI3CLKSOURCE_SYSCLK:
frequency = HAL_RCC_GetSysClockFreq();
break;
case RCC_SPI3CLKSOURCE_HSI:
if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY))
{
frequency = HSI_VALUE;
}
else
{
frequency = 0U;
}
break;
case RCC_SPI3CLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
else if (PeriphClk == RCC_PERIPHCLK_OSPI)
{
/* Get the current OSPI kernel source */
srcclk = __HAL_RCC_GET_OSPI_SOURCE();
switch (srcclk)
{
case RCC_OSPICLKSOURCE_PLL2:
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_Q_Frequency;
break;
case RCC_OSPICLKSOURCE_PLL1:
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_Q_Frequency;
break;
case RCC_OSPICLKSOURCE_SYSCLK:
frequency = HAL_RCC_GetSysClockFreq();
break;
case RCC_OSPICLKSOURCE_MSIK:
frequency = MSIRangeTable[(__HAL_RCC_GET_MSIK_RANGE() >> RCC_ICSCR1_MSIKRANGE_Pos)];
break;
default:
frequency = 0U;
break;
}
}
#if defined(HSPI1)
else if (PeriphClk == RCC_PERIPHCLK_HSPI)
{
/* Get the current HSPI kernel source */
srcclk = __HAL_RCC_GET_HSPI_SOURCE();
switch (srcclk)
{
case RCC_HSPICLKSOURCE_SYSCLK:
frequency = HAL_RCC_GetSysClockFreq();
break;
case RCC_HSPICLKSOURCE_PLL1:
HAL_RCCEx_GetPLL1ClockFreq(&pll1_clocks);
frequency = pll1_clocks.PLL1_Q_Frequency;
break;
case RCC_HSPICLKSOURCE_PLL2:
HAL_RCCEx_GetPLL2ClockFreq(&pll2_clocks);
frequency = pll2_clocks.PLL2_Q_Frequency;
break;
case RCC_HSPICLKSOURCE_PLL3:
HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks);
frequency = pll3_clocks.PLL3_R_Frequency;
break;
default:
frequency = 0U;
break;
}
}
#endif /* defined(HSPI1) */
else if (PeriphClk == RCC_PERIPHCLK_DAC1)
{
/* Get the current DAC1 kernel source */
srcclk = __HAL_RCC_GET_DAC1_SOURCE();
/* Check if LSE is ready and if DAC1 clock selection is LSE */
if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_DAC1CLKSOURCE_LSE))
{
frequency = LSE_VALUE;
}
/* Check if LSI is ready and if DAC1 clock selection is LSI */
else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIRDY)) && (srcclk == RCC_DAC1CLKSOURCE_LSI))
{
if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSIPREDIV))
{
frequency = LSI_VALUE / 128U;
}
else
{
frequency = LSI_VALUE;
}
}
/* Clock not enabled for DAC1*/
else
{
frequency = 0U;
}
}
else
{
frequency = 0;
}
return (frequency);
}
/** @defgroup RCCEx_Exported_Functions_Group2 Extended Clock management functions
* @brief Extended Clock management functions
*
@verbatim
===============================================================================
##### Extended clock management functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the
activation or deactivation of MSI PLL-mode, PLL2, PLL3, LSE CSS,
Low speed clock output and clock after wake-up from STOP mode.
@endverbatim
* @{
*/
/**
* @brief Enable PLL2.
* @param PLL2Init pointer to an RCC_PLL2InitTypeDef structure that
* contains the configuration information for the PLL2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
/* check for PLL2 Parameters used to output PLL2CLK */
assert_param(IS_RCC_PLLSOURCE(PLL2Init->PLL2Source));
assert_param(IS_RCC_PLLM_VALUE(PLL2Init->PLL2M));
assert_param(IS_RCC_PLLN_VALUE(PLL2Init->PLL2N));
assert_param(IS_RCC_PLLP_VALUE(PLL2Init->PLL2P));
assert_param(IS_RCC_PLLQ_VALUE(PLL2Init->PLL2Q));
assert_param(IS_RCC_PLLR_VALUE(PLL2Init->PLL2R));
assert_param(IS_RCC_PLL2CLOCKOUT_VALUE(PLL2Init->PLL2ClockOut));
/* Disable the PLL2 */
__HAL_RCC_PLL2_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL2 is ready to be updated */
while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
if (status == HAL_OK)
{
/* Make sure PLL2Source is ready */
status = RCCEx_PLLSource_Enable(PLL2Init->PLL2Source);
if (status == HAL_OK)
{
/* Configure the PLL2 clock source, multiplication factor N, */
/* and division factors M, P, Q and R */
__HAL_RCC_PLL2_CONFIG(PLL2Init->PLL2Source, PLL2Init->PLL2M, PLL2Init->PLL2N,
PLL2Init->PLL2P, PLL2Init->PLL2Q, PLL2Init->PLL2R);
/* Disable PLL2FRACN */
__HAL_RCC_PLL2FRACN_DISABLE();
/* Configure PLL PLL2FRACN */
__HAL_RCC_PLL2FRACN_CONFIG(PLL2Init->PLL2FRACN);
/* Enable PLL2FRACN */
__HAL_RCC_PLL2FRACN_ENABLE();
/* Select PLL2 input reference frequency range: VCI */
__HAL_RCC_PLL2_VCIRANGE(PLL2Init->PLL2RGE);
/* Configure the PLL2 Clock output(s) */
__HAL_RCC_PLL2CLKOUT_ENABLE(PLL2Init->PLL2ClockOut);
/* Enable the PLL2 again by setting PLL2ON to 1*/
__HAL_RCC_PLL2_ENABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL2 is ready */
while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
}
}
return status;
}
/**
* @brief Disable PLL2.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
/* Disable the PLL2 */
__HAL_RCC_PLL2_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL2 is ready */
while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
/* To save power disable the PLL2 Source, FRACN and Clock outputs */
CLEAR_BIT(RCC->PLL2CFGR, RCC_PLL2CFGR_PLL2PEN | RCC_PLL2CFGR_PLL2QEN | RCC_PLL2CFGR_PLL2REN | RCC_PLL2CFGR_PLL2SRC | \
RCC_PLL2CFGR_PLL2FRACEN);
return status;
}
/**
* @brief Enable PLL3.
* @param PLL3Init pointer to an RCC_PLL3InitTypeDef structure that
* contains the configuration information for the PLL3
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_EnablePLL3(RCC_PLL3InitTypeDef *PLL3Init)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
/* check for PLL3 Parameters used to output PLL3CLK */
assert_param(IS_RCC_PLLSOURCE(PLL3Init->PLL3Source));
assert_param(IS_RCC_PLLM_VALUE(PLL3Init->PLL3M));
assert_param(IS_RCC_PLLN_VALUE(PLL3Init->PLL3N));
assert_param(IS_RCC_PLLP_VALUE(PLL3Init->PLL3P));
assert_param(IS_RCC_PLL3CLOCKOUT_VALUE(PLL3Init->PLL3ClockOut));
/* Disable the PLL3 */
__HAL_RCC_PLL3_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL3 is ready to be updated */
while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL3_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
if (status == HAL_OK)
{
/* Make sure PLL3Source is ready */
status = RCCEx_PLLSource_Enable(PLL3Init->PLL3Source);
if (status == HAL_OK)
{
/* Configure the PLL3 clock source, multiplication factor N, */
/* and division factors M and P */
__HAL_RCC_PLL3_CONFIG(PLL3Init->PLL3Source, PLL3Init->PLL3M, PLL3Init->PLL3N, PLL3Init->PLL3P, PLL3Init->PLL3Q, \
PLL3Init->PLL3R);
/* Disable PLL3FRACN . */
__HAL_RCC_PLL3FRACN_DISABLE();
/* Configure PLL PLL3FRACN */
__HAL_RCC_PLL3FRACN_CONFIG(PLL3Init->PLL3FRACN);
/* Enable PLL3FRACN . */
__HAL_RCC_PLL3FRACN_ENABLE();
/* Select PLL3 input reference frequency range: VCI */
__HAL_RCC_PLL3_VCIRANGE(PLL3Init->PLL3RGE);
/* Configure the PLL3 Clock output(s) */
__HAL_RCC_PLL3CLKOUT_ENABLE(PLL3Init->PLL3ClockOut);
/* Enable the PLL3 again by setting PLL3ON to 1*/
__HAL_RCC_PLL3_ENABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL3 is ready */
while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > PLL3_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
}
}
return status;
}
/**
* @brief Disable PLL3.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_DisablePLL3(void)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
/* Disable the PLL3 */
__HAL_RCC_PLL3_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL3 is ready */
while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL3_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
/* To save power disable the PLL3 Source and Clock outputs */
CLEAR_BIT(RCC->PLL3CFGR, RCC_PLL3CFGR_PLL3PEN | RCC_PLL3CFGR_PLL3QEN | RCC_PLL3CFGR_PLL3REN | RCC_PLL3CFGR_PLL3SRC | \
RCC_PLL3CFGR_PLL3FRACEN);
return status;
}
/**
* @brief Select which MSI output clock uses the PLL mode.
* @note Prior to disable PLL-mode (MSIPLLEN = 0) before call HAL_RCCEx_EnableMSIPLLModeSelection.
* @note The MSI kernel clock output uses the same oscillator source than the MSI system
* clock output, then the PLL mode is applied to the both clocks outputs.
* @param MSIPLLModeSelection specifies which MSI output clock uses the PLL mode.
* This parameter can be one of the following values:
* @arg @ref RCC_MSISPLL_MODE_SEL PLL mode applied to MSIS (MSI system) clock output
* @arg @ref RCC_MSIKPLL_MODE_SEL PLL mode applied to MSIK (MSI kernel) clock output
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_EnableMSIPLLModeSelection(uint32_t MSIPLLModeSelection)
{
HAL_StatusTypeDef status = HAL_ERROR;
assert_param(IS_RCC_MSIPLLMODE_SELECT(MSIPLLModeSelection));
if (READ_BIT(RCC->CR, RCC_CR_MSIPLLEN) == 0U)
{
/* This bit is used only if PLL mode is disabled (MSIPLLEN = 0) */
if (MSIPLLModeSelection == RCC_MSISPLL_MODE_SEL)
{
SET_BIT(RCC->CR, RCC_CR_MSIPLLSEL);
}
else
{
CLEAR_BIT(RCC->CR, RCC_CR_MSIPLLSEL);
}
status = HAL_OK;
}
return status;
}
/**
* @brief Enable the fast PLL mode start-up of the MSI clock
* @note Prior to enable PLL-mode (MSIPLLEN = 1) before call HAL_RCCEx_EnableMSIPLLFastStartup.
* @note The fast start-up feature is not active the first time the PLL mode is selected. The
* fast start-up is active when the MSI in PLL mode returns from switch off.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_EnableMSIPLLFastStartup(void)
{
HAL_StatusTypeDef status = HAL_ERROR;
if (READ_BIT(RCC->CR, RCC_CR_MSIPLLEN) == RCC_CR_MSIPLLEN)
{
/* This bit is used only if PLL mode is selected (MSIPLLEN = 1) */
SET_BIT(RCC->CR, RCC_CR_MSIPLLFAST);
status = HAL_OK;
}
return status;
}
/**
* @brief Disable the fast PLL mode start-up of the MSI clock
* @note the MSI fast startup mode disabled only when PLL-mode is enabled
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RCCEx_DisableMSIPLLFastStartup(void)
{
HAL_StatusTypeDef status = HAL_ERROR;
if (READ_BIT(RCC->CR, RCC_CR_MSIPLLEN) == RCC_CR_MSIPLLEN)
{
/* This bit is used only if PLL mode is selected (MSIPLLEN = 1) */
CLEAR_BIT(RCC->CR, RCC_CR_MSIPLLFAST);
status = HAL_OK;
}
return status;
}
/**
* @brief Configure the oscillator clock source for wakeup from Stop and CSS backup clock.
* @param WakeUpClk Wakeup clock
* This parameter can be one of the following values:
* @arg @ref RCC_STOP_WAKEUPCLOCK_MSI MSI oscillator selection
* @arg @ref RCC_STOP_WAKEUPCLOCK_HSI HSI oscillator selection
* @note This function shall not be called after the Clock Security System on HSE has been
* enabled.
* @retval None
*/
void HAL_RCCEx_WakeUpStopCLKConfig(uint32_t WakeUpClk)
{
assert_param(IS_RCC_STOP_WAKEUPCLOCK(WakeUpClk));
__HAL_RCC_WAKEUPSTOP_CLK_CONFIG(WakeUpClk);
}
/**
* @brief Configure the oscillator Kernel clock source for wakeup from Stop
* @param WakeUpClk: Kernel Wakeup clock
* This parameter can be one of the following values:
* @arg RCC_STOP_KERWAKEUPCLOCK_MSI: MSI oscillator selection
* @arg RCC_STOP_KERWAKEUPCLOCK_HSI: HSI oscillator selection
* @retval None
*/
void HAL_RCCEx_KerWakeUpStopCLKConfig(uint32_t WakeUpClk)
{
assert_param(IS_RCC_STOP_KERWAKEUPCLOCK(WakeUpClk));
__HAL_RCC_KERWAKEUPSTOP_CLK_CONFIG(WakeUpClk);
}
/**
* @brief Configure the MSI range after standby mode.
* @note After Standby its frequency can be selected between 3 possible values (1, 3.072 or 4 MHz).
* @param MSIRange MSI range
* This parameter can be one of the following values:
* @arg @ref RCC_MSIRANGE_4 Range 4 around 4 MHz (reset value)
* @arg @ref RCC_MSIRANGE_5 Range 5 around 2 MHz
* @arg @ref RCC_MSIRANGE_6 Range 6 around 1.5 MHz
* @arg @ref RCC_MSIRANGE_7 Range 7 around 1 MHz
* @arg @ref RCC_MSIRANGE_8 Range 8 around 3.072 MHz
* @retval None
*/
void HAL_RCCEx_StandbyMSIRangeConfig(uint32_t MSIRange)
{
assert_param(IS_RCC_MSI_STANDBY_CLOCK_RANGE(MSIRange));
__HAL_RCC_MSI_STANDBY_RANGE_CONFIG(MSIRange);
}
/**
* @brief Enable the LSE Clock Security System.
* @note Prior to enable the LSE Clock Security System, LSE oscillator is to be enabled
* with HAL_RCC_OscConfig() and the LSE oscillator clock is to be selected as RTC
* clock with HAL_RCCEx_PeriphCLKConfig().
* @retval None
*/
void HAL_RCCEx_EnableLSECSS(void)
{
SET_BIT(RCC->BDCR, RCC_BDCR_LSECSSON);
}
/**
* @brief Disable the LSE Clock Security System.
* @note LSE Clock Security System can only be disabled after a LSE failure detection.
* @retval None
*/
void HAL_RCCEx_DisableLSECSS(void)
{
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSECSSON);
}
/**
* @brief Handle the RCC LSE Clock Security System interrupt request.
* @retval None
*/
void HAL_RCCEx_LSECSS_IRQHandler(void)
{
if (READ_BIT(RCC->BDCR, RCC_BDCR_LSECSSD) != 0U)
{
/* RCC LSE Clock Security System interrupt user callback */
HAL_RCCEx_LSECSS_Callback();
}
}
/**
* @brief RCCEx LSE Clock Security System interrupt callback.
* @retval none
*/
__weak void HAL_RCCEx_LSECSS_Callback(void)
{
/* NOTE : This function should not be modified, when the callback is needed,
the @ref HAL_RCCEx_LSECSS_Callback should be implemented in the user file
*/
}
/**
* @brief Select the Low Speed clock source to output on LSCO pin (PA2).
* @param LSCOSource specifies the Low Speed clock source to output.
* This parameter can be one of the following values:
* @arg @ref RCC_LSCOSOURCE_LSI LSI clock selected as LSCO source
* @arg @ref RCC_LSCOSOURCE_LSE LSE clock selected as LSCO source
* @retval None
*/
void HAL_RCCEx_EnableLSCO(uint32_t LSCOSource)
{
GPIO_InitTypeDef gpio_initstruct;
FlagStatus pwrclkchanged = RESET;
FlagStatus backupchanged = RESET;
/* Check the parameters */
assert_param(IS_RCC_LSCOSOURCE(LSCOSource));
/* LSCO Pin Clock Enable */
LSCO_CLK_ENABLE();
/* Configure the LSCO pin in analog mode */
gpio_initstruct.Pin = LSCO_PIN;
gpio_initstruct.Mode = GPIO_MODE_ANALOG;
gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_initstruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(LSCO_GPIO_PORT, &gpio_initstruct);
/* Update LSCOSEL clock source in Backup Domain control register */
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
if (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
HAL_PWR_EnableBkUpAccess();
backupchanged = SET;
}
MODIFY_REG(RCC->BDCR, RCC_BDCR_LSCOSEL | RCC_BDCR_LSCOEN, LSCOSource | RCC_BDCR_LSCOEN);
if (backupchanged == SET)
{
HAL_PWR_DisableBkUpAccess();
}
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
}
/**
* @brief Disable the Low Speed clock output.
* @retval None
*/
void HAL_RCCEx_DisableLSCO(void)
{
FlagStatus pwrclkchanged = RESET;
FlagStatus backupchanged = RESET;
/* Update LSCOEN bit in Backup Domain control register */
if (__HAL_RCC_PWR_IS_CLK_DISABLED())
{
__HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
if (HAL_IS_BIT_CLR(PWR->DBPR, PWR_DBPR_DBP))
{
/* Enable access to the backup domain */
HAL_PWR_EnableBkUpAccess();
backupchanged = SET;
}
CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSCOEN);
/* Restore previous configuration */
if (backupchanged == SET)
{
/* Disable access to the backup domain */
HAL_PWR_DisableBkUpAccess();
}
if (pwrclkchanged == SET)
{
__HAL_RCC_PWR_CLK_DISABLE();
}
}
/**
* @brief Enable the PLL-mode of the MSI.
* @note Prior to enable the PLL-mode of the MSI for automatic hardware
* calibration LSE oscillator is to be enabled with HAL_RCC_OscConfig().
* @retval None
*/
void HAL_RCCEx_EnableMSIPLLMode(void)
{
SET_BIT(RCC->CR, RCC_CR_MSIPLLEN);
}
/**
* @brief Disable the PLL-mode of the MSI.
* @note PLL-mode of the MSI is automatically reset when LSE oscillator is disabled.
* @retval None
*/
void HAL_RCCEx_DisableMSIPLLMode(void)
{
CLEAR_BIT(RCC->CR, RCC_CR_MSIPLLEN);
}
/**
* @}
*/
#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(const RCC_CRSInitTypeDef *const pInit)
{
uint32_t value;
/* 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[5: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 = (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_RELOAD));
/* Get HSI48 oscillator smooth trimming */
pSynchroInfo->HSI48CalibrationValue = (uint32_t)(READ_BIT(CRS->CR, CRS_CR_TRIM) >> CRS_CR_TRIM_Pos);
/* Get Frequency error capture */
pSynchroInfo->FreqErrorCapture = (uint32_t)(READ_BIT(CRS->ISR, CRS_ISR_FECAP) >> CRS_ISR_FECAP_Pos);
/* Get Frequency error direction */
pSynchroInfo->FreqErrorDirection = (uint32_t)(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 */
/**
* @}
*/
/** @addtogroup RCCEx_Private_Functions
* @{
*/
/**
* @brief Configure the PLL 1 source clock.
* @param PllSource PLL1 source clock it can be :
* RCC_PLLSOURCE_NONE
* RCC_PLLSOURCE_MSI
* RCC_PLLSOURCE_HSI
* RCC_PLLSOURCE_HSE
*
* @retval HAL status
*/
static HAL_StatusTypeDef RCCEx_PLLSource_Enable(uint32_t PllSource)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
switch (PllSource)
{
case RCC_PLLSOURCE_MSI:
/* Check whether MSI in not ready and enable it */
if (READ_BIT(RCC->CR, RCC_CR_MSISRDY) == 0U)
{
/* Enable the Internal Multi Speed oscillator (MSI). */
__HAL_RCC_MSI_ENABLE();
/* Get timeout */
tickstart = HAL_GetTick();
/* Wait till MSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_MSISRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > MSI_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
}
break;
case RCC_PLLSOURCE_HSI:
/* Check whether HSI in not ready and enable it */
if (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U)
{
/* Enable the Internal High Speed oscillator (HSI) */
__HAL_RCC_HSI_ENABLE();
/* Get timeout */
tickstart = HAL_GetTick();
/* Wait till MSI is ready */
while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
}
break;
case RCC_PLLSOURCE_HSE:
/* Check whether HSE in not ready and enable it */
if (READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U)
{
/* Enable the External High Speed oscillator (HSE) */
SET_BIT(RCC->CR, RCC_CR_HSEON);
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till HSE is ready */
while (READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE)
{
status = HAL_TIMEOUT;
break;
}
}
}
break;
default:
status = HAL_ERROR;
break;
}
return status;
}
/**
* @brief Configure the PLL2 VCI ranges, multiplication and division factors and enable it
* @param pll2: Pointer to an RCC_PLL2InitTypeDef structure that
* contains the configuration parameters as well as VCI clock ranges.
* @note PLL2 is temporary disabled to apply new parameters
*
* @retval HAL status
*/
static HAL_StatusTypeDef RCCEx_PLL2_Config(RCC_PLL2InitTypeDef *pll2)
{
uint32_t tickstart;
assert_param(IS_RCC_PLLSOURCE(pll2->PLL2Source));
assert_param(IS_RCC_PLLM_VALUE(pll2->PLL2M));
assert_param(IS_RCC_PLLN_VALUE(pll2->PLL2N));
assert_param(IS_RCC_PLLP_VALUE(pll2->PLL2P));
assert_param(IS_RCC_PLLQ_VALUE(pll2->PLL2Q));
assert_param(IS_RCC_PLLR_VALUE(pll2->PLL2R));
/* Disable PLL2 */
__HAL_RCC_PLL2_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL is ready */
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Configure PLL2 multiplication and division factors */
__HAL_RCC_PLL2_CONFIG(pll2->PLL2Source,
pll2->PLL2M,
pll2->PLL2N,
pll2->PLL2P,
pll2->PLL2Q,
pll2->PLL2R);
/* Select PLL2 input reference frequency range: VCI */
__HAL_RCC_PLL2_VCIRANGE(pll2->PLL2RGE);
/* Configure the PLL2 Clock output(s) */
__HAL_RCC_PLL2CLKOUT_ENABLE(pll2->PLL2ClockOut);
/* Disable PLL2FRACN */
__HAL_RCC_PLL2FRACN_DISABLE();
/* Configures PLL2 clock Fractional Part Of The Multiplication Factor */
__HAL_RCC_PLL2FRACN_CONFIG(pll2->PLL2FRACN);
/* Enable PLL2FRACN */
__HAL_RCC_PLL2FRACN_ENABLE();
/* Enable PLL2 */
__HAL_RCC_PLL2_ENABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL2 is ready */
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @brief Configure the PLL3 VCI ranges, multiplication and division factors and enable it
* @param pll3: Pointer to an RCC_PLL3InitTypeDef structure that
* contains the configuration parameters as well as VCI clock ranges.
* @note PLL3 is temporary disabled to apply new parameters
* @retval HAL status
*/
static HAL_StatusTypeDef RCCEx_PLL3_Config(RCC_PLL3InitTypeDef *pll3)
{
uint32_t tickstart;
assert_param(IS_RCC_PLLSOURCE(pll3->PLL3Source));
assert_param(IS_RCC_PLLM_VALUE(pll3->PLL3M));
assert_param(IS_RCC_PLLN_VALUE(pll3->PLL3N));
assert_param(IS_RCC_PLLP_VALUE(pll3->PLL3P));
assert_param(IS_RCC_PLLQ_VALUE(pll3->PLL3Q));
assert_param(IS_RCC_PLLR_VALUE(pll3->PLL3R));
/* Disable PLL3 */
__HAL_RCC_PLL3_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL is ready */
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL3RDY) != 0U)
{
if ((HAL_GetTick() - tickstart) > PLL3_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
/* Configure PLL3 multiplication and division factors */
__HAL_RCC_PLL3_CONFIG(pll3->PLL3Source,
pll3->PLL3M,
pll3->PLL3N,
pll3->PLL3P,
pll3->PLL3Q,
pll3->PLL3R);
/* Select PLL3 input reference frequency range: VCI */
__HAL_RCC_PLL3_VCIRANGE(pll3->PLL3RGE);
/* Configure the PLL3 Clock output(s) */
__HAL_RCC_PLL3CLKOUT_ENABLE(pll3->PLL3ClockOut);
/* Disable PLL3FRACN */
__HAL_RCC_PLL3FRACN_DISABLE();
/* Configures PLL3 clock Fractional Part Of The Multiplication Factor */
__HAL_RCC_PLL3FRACN_CONFIG(pll3->PLL3FRACN);
/* Enable PLL3FRACN */
__HAL_RCC_PLL3FRACN_ENABLE();
/* Enable PLL3 */
__HAL_RCC_PLL3_ENABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
/* Wait till PLL3 is ready */
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL3RDY) == 0U)
{
if ((HAL_GetTick() - tickstart) > PLL3_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_RCC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rcc_ex.c
|
C
|
apache-2.0
| 134,746
|
/**
******************************************************************************
* @file stm32u5xx_hal_rng.c
* @author MCD Application Team
* @brief RNG HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Random Number Generator (RNG) peripheral:
* + Initialization and configuration functions
* + Peripheral Control functions
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 RNG HAL driver can be used as follows:
(#) Enable the RNG controller clock using __HAL_RCC_RNG_CLK_ENABLE() macro
in HAL_RNG_MspInit().
(#) Activate the RNG peripheral using HAL_RNG_Init() function.
(#) Wait until the 32 bit Random Number Generator contains a valid
random data using (polling/interrupt) mode.
(#) Get the 32 bit random number using HAL_RNG_GenerateRandomNumber() function.
##### Callback registration #####
==================================
[..]
The compilation define USE_HAL_RNG_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
[..]
Use Function @ref HAL_RNG_RegisterCallback() to register a user callback.
Function @ref HAL_RNG_RegisterCallback() allows to register following callbacks:
(+) ErrorCallback : RNG Error Callback.
(+) MspInitCallback : RNG MspInit.
(+) MspDeInitCallback : RNG 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_RNG_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function.
@ref HAL_RNG_UnRegisterCallback() takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) ErrorCallback : RNG Error Callback.
(+) MspInitCallback : RNG MspInit.
(+) MspDeInitCallback : RNG MspDeInit.
[..]
For specific callback ReadyDataCallback, use dedicated register callbacks:
respectively @ref HAL_RNG_RegisterReadyDataCallback() , @ref HAL_RNG_UnRegisterReadyDataCallback().
[..]
By default, after the @ref HAL_RNG_Init() and when the state is HAL_RNG_STATE_RESET
all callbacks are set to the corresponding weak (surcharged) functions:
example @ref HAL_RNG_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) functions in the @ref HAL_RNG_Init()
and @ref HAL_RNG_DeInit() only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the @ref HAL_RNG_Init() and @ref HAL_RNG_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand).
[..]
Callbacks can be registered/unregistered in HAL_RNG_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_RNG_STATE_READY or HAL_RNG_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_RNG_RegisterCallback() before calling @ref HAL_RNG_DeInit()
or @ref HAL_RNG_Init() function.
[..]
When The compilation define USE_HAL_RNG_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available
and weak (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
#if defined (RNG)
/** @addtogroup RNG
* @brief RNG HAL module driver.
* @{
*/
#ifdef HAL_RNG_MODULE_ENABLED
/* Private types -------------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup RNG_Private_Constants RNG Private Constants
* @{
*/
#define RNG_TIMEOUT_VALUE 4U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private functions prototypes ----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RNG_Exported_Functions
* @{
*/
/** @addtogroup RNG_Exported_Functions_Group1
* @brief Initialization and configuration functions
*
@verbatim
===============================================================================
##### Initialization and configuration functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize the RNG according to the specified parameters
in the RNG_InitTypeDef and create the associated handle
(+) DeInitialize the RNG peripheral
(+) Initialize the RNG MSP
(+) DeInitialize RNG MSP
@endverbatim
* @{
*/
/**
* @brief Initializes the RNG peripheral and creates the associated handle.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng)
{
uint32_t tickstart;
/* Check the RNG handle allocation */
if (hrng == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RNG_ALL_INSTANCE(hrng->Instance));
assert_param(IS_RNG_CED(hrng->Init.ClockErrorDetection));
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
if (hrng->State == HAL_RNG_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hrng->Lock = HAL_UNLOCKED;
hrng->ReadyDataCallback = HAL_RNG_ReadyDataCallback; /* Legacy weak ReadyDataCallback */
hrng->ErrorCallback = HAL_RNG_ErrorCallback; /* Legacy weak ErrorCallback */
if (hrng->MspInitCallback == NULL)
{
hrng->MspInitCallback = HAL_RNG_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware */
hrng->MspInitCallback(hrng);
}
#else
if (hrng->State == HAL_RNG_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hrng->Lock = HAL_UNLOCKED;
/* Init the low level hardware */
HAL_RNG_MspInit(hrng);
}
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Disable RNG */
__HAL_RNG_DISABLE(hrng);
/* Clock Error Detection Configuration when CONDRT bit is set to 1 */
MODIFY_REG(hrng->Instance->CR, RNG_CR_CED | RNG_CR_CONDRST, hrng->Init.ClockErrorDetection | RNG_CR_CONDRST);
/* Writing bit CONDRST=0 */
CLEAR_BIT(hrng->Instance->CR, RNG_CR_CONDRST);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait for conditioning reset process to be completed */
while (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
if ((HAL_GetTick() - tickstart) > RNG_TIMEOUT_VALUE)
{
/* New check to avoid false timeout detection in case of preemption */
if (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
}
/* Enable the RNG Peripheral */
__HAL_RNG_ENABLE(hrng);
/* verify that no seed error */
if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)
{
hrng->State = HAL_RNG_STATE_ERROR;
return HAL_ERROR;
}
/* Get tick */
tickstart = HAL_GetTick();
/* Check if data register contains valid random data */
while (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_SECS) != RESET)
{
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)
{
hrng->State = HAL_RNG_STATE_ERROR;
hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
}
/* Initialize the RNG state */
hrng->State = HAL_RNG_STATE_READY;
/* Initialise the error code */
hrng->ErrorCode = HAL_RNG_ERROR_NONE;
/* Return function status */
return HAL_OK;
}
/**
* @brief DeInitializes the RNG peripheral.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng)
{
uint32_t tickstart;
/* Check the RNG handle allocation */
if (hrng == NULL)
{
return HAL_ERROR;
}
/* Clear Clock Error Detection bit when CONDRT bit is set to 1 */
MODIFY_REG(hrng->Instance->CR, RNG_CR_CED | RNG_CR_CONDRST, RNG_CED_ENABLE | RNG_CR_CONDRST);
/* Writing bit CONDRST=0 */
CLEAR_BIT(hrng->Instance->CR, RNG_CR_CONDRST);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait for conditioning reset process to be completed */
while (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
if ((HAL_GetTick() - tickstart) > RNG_TIMEOUT_VALUE)
{
/* New check to avoid false timeout detection in case of preemption */
if (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
return HAL_ERROR;
}
}
}
/* Disable the RNG Peripheral */
CLEAR_BIT(hrng->Instance->CR, RNG_CR_IE | RNG_CR_RNGEN);
/* Clear RNG interrupt status flags */
CLEAR_BIT(hrng->Instance->SR, RNG_SR_CEIS | RNG_SR_SEIS);
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
if (hrng->MspDeInitCallback == NULL)
{
hrng->MspDeInitCallback = HAL_RNG_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware */
hrng->MspDeInitCallback(hrng);
#else
/* DeInit the low level hardware */
HAL_RNG_MspDeInit(hrng);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
/* Update the RNG state */
hrng->State = HAL_RNG_STATE_RESET;
/* Initialise the error code */
hrng->ErrorCode = HAL_RNG_ERROR_NONE;
/* Release Lock */
__HAL_UNLOCK(hrng);
/* Return the function status */
return HAL_OK;
}
/**
* @brief Initializes the RNG MSP.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval None
*/
__weak void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrng);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_RNG_MspInit must be implemented in the user file.
*/
}
/**
* @brief DeInitializes the RNG MSP.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval None
*/
__weak void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrng);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_RNG_MspDeInit must be implemented in the user file.
*/
}
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User RNG Callback
* To be used instead of the weak predefined callback
* @param hrng RNG handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_RNG_ERROR_CB_ID Error callback ID
* @arg @ref HAL_RNG_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_RNG_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_RegisterCallback(RNG_HandleTypeDef *hrng, HAL_RNG_CallbackIDTypeDef CallbackID,
pRNG_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hrng);
if (HAL_RNG_STATE_READY == hrng->State)
{
switch (CallbackID)
{
case HAL_RNG_ERROR_CB_ID :
hrng->ErrorCallback = pCallback;
break;
case HAL_RNG_MSPINIT_CB_ID :
hrng->MspInitCallback = pCallback;
break;
case HAL_RNG_MSPDEINIT_CB_ID :
hrng->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_RNG_STATE_RESET == hrng->State)
{
switch (CallbackID)
{
case HAL_RNG_MSPINIT_CB_ID :
hrng->MspInitCallback = pCallback;
break;
case HAL_RNG_MSPDEINIT_CB_ID :
hrng->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hrng);
return status;
}
/**
* @brief Unregister an RNG Callback
* RNG callback is redirected to the weak predefined callback
* @param hrng RNG handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_RNG_ERROR_CB_ID Error callback ID
* @arg @ref HAL_RNG_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_RNG_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_UnRegisterCallback(RNG_HandleTypeDef *hrng, HAL_RNG_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hrng);
if (HAL_RNG_STATE_READY == hrng->State)
{
switch (CallbackID)
{
case HAL_RNG_ERROR_CB_ID :
hrng->ErrorCallback = HAL_RNG_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_RNG_MSPINIT_CB_ID :
hrng->MspInitCallback = HAL_RNG_MspInit; /* Legacy weak MspInit */
break;
case HAL_RNG_MSPDEINIT_CB_ID :
hrng->MspDeInitCallback = HAL_RNG_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_RNG_STATE_RESET == hrng->State)
{
switch (CallbackID)
{
case HAL_RNG_MSPINIT_CB_ID :
hrng->MspInitCallback = HAL_RNG_MspInit; /* Legacy weak MspInit */
break;
case HAL_RNG_MSPDEINIT_CB_ID :
hrng->MspDeInitCallback = HAL_RNG_MspDeInit; /* Legacy weak MspInit */
break;
default :
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hrng);
return status;
}
/**
* @brief Register Data Ready RNG Callback
* To be used instead of the weak HAL_RNG_ReadyDataCallback() predefined callback
* @param hrng RNG handle
* @param pCallback pointer to the Data Ready Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_RegisterReadyDataCallback(RNG_HandleTypeDef *hrng, pRNG_ReadyDataCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hrng);
if (HAL_RNG_STATE_READY == hrng->State)
{
hrng->ReadyDataCallback = pCallback;
}
else
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hrng);
return status;
}
/**
* @brief UnRegister the Data Ready RNG Callback
* Data Ready RNG Callback is redirected to the weak HAL_RNG_ReadyDataCallback() predefined callback
* @param hrng RNG handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_UnRegisterReadyDataCallback(RNG_HandleTypeDef *hrng)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hrng);
if (HAL_RNG_STATE_READY == hrng->State)
{
hrng->ReadyDataCallback = HAL_RNG_ReadyDataCallback; /* Legacy weak ReadyDataCallback */
}
else
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hrng);
return status;
}
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
/**
* @}
*/
/** @addtogroup RNG_Exported_Functions_Group2
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Get the 32 bit Random number
(+) Get the 32 bit Random number with interrupt enabled
(+) Handle RNG interrupt request
@endverbatim
* @{
*/
/**
* @brief Generates a 32-bit random number.
* @note This function checks value of RNG_FLAG_DRDY flag to know if valid
* random number is available in the DR register (RNG_FLAG_DRDY flag set
* whenever a random number is available through the RNG_DR register).
* After transitioning from 0 to 1 (random number available),
* RNG_FLAG_DRDY flag remains high until output buffer becomes empty after reading
* four words from the RNG_DR register, i.e. further function calls
* will immediately return a new u32 random number (additional words are
* available and can be read by the application, till RNG_FLAG_DRDY flag remains high).
* @note When no more random number data is available in DR register, RNG_FLAG_DRDY
* flag is automatically cleared.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @param random32bit pointer to generated random number variable if successful.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit)
{
uint32_t tickstart;
HAL_StatusTypeDef status = HAL_OK;
/* Process Locked */
__HAL_LOCK(hrng);
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Check if there is a seed error */
if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_SEED;
/* Reset from seed error */
status = RNG_RecoverSeedError(hrng);
if (status == HAL_ERROR)
{
return status;
}
}
/* Get tick */
tickstart = HAL_GetTick();
/* Check if data register contains valid random data */
while (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET)
{
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_DRDY) == RESET)
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
return HAL_ERROR;
}
}
}
/* Get a 32bit Random number */
hrng->RandomNumber = hrng->Instance->DR;
/* In case of seed error, the value available in the RNG_DR register must not
be used as it may not have enough entropy */
if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_SEED;
/* Clear bit DRDY */
CLEAR_BIT(hrng->Instance->SR, RNG_FLAG_DRDY);
}
else /* No seed error */
{
*random32bit = hrng->RandomNumber;
}
hrng->State = HAL_RNG_STATE_READY;
}
else
{
hrng->ErrorCode = HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hrng);
return status;
}
/**
* @brief Generates a 32-bit random number in interrupt mode.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process Locked */
__HAL_LOCK(hrng);
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */
__HAL_RNG_ENABLE_IT(hrng);
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hrng);
hrng->ErrorCode = HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
return status;
}
/**
* @brief Handles RNG interrupt request.
* @note In the case of a clock error, the RNG is no more able to generate
* random numbers because the PLL48CLK clock is not correct. User has
* to check that the clock controller is correctly configured to provide
* the RNG clock and clear the CEIS bit using __HAL_RNG_CLEAR_IT().
* The clock error has no impact on the previously generated
* random numbers, and the RNG_DR register contents can be used.
* @note In the case of a seed error, the generation of random numbers is
* interrupted as long as the SECS bit is '1'. If a number is
* available in the RNG_DR register, it must not be used because it may
* not have enough entropy. In this case, it is recommended to clear the
* SEIS bit using __HAL_RNG_CLEAR_IT(), then disable and enable
* the RNG peripheral to reinitialize and restart the RNG.
* @note User-written HAL_RNG_ErrorCallback() API is called once whether SEIS
* or CEIS are set.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval None
*/
void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng)
{
uint32_t rngclockerror = 0U;
/* RNG clock error interrupt occurred */
if (__HAL_RNG_GET_IT(hrng, RNG_IT_CEI) != RESET)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_CLOCK;
rngclockerror = 1U;
}
else if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)
{
/* Check if Seed Error Current Status (SECS) is set */
if (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_SECS) == RESET)
{
/* RNG IP performed the reset automatically (auto-reset) */
/* Clear bit SEIS */
CLEAR_BIT(hrng->Instance->SR, RNG_IT_SEI);
}
else
{
/* Seed Error has not been recovered : Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_SEED;
rngclockerror = 1U;
/* Disable the IT */
__HAL_RNG_DISABLE_IT(hrng);
}
}
else
{
/* Nothing to do */
}
if (rngclockerror == 1U)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_ERROR;
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/* Call registered Error callback */
hrng->ErrorCallback(hrng);
#else
/* Call legacy weak Error callback */
HAL_RNG_ErrorCallback(hrng);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
/* Clear the clock error flag */
__HAL_RNG_CLEAR_IT(hrng, RNG_IT_CEI | RNG_IT_SEI);
return;
}
/* Check RNG data ready interrupt occurred */
if (__HAL_RNG_GET_IT(hrng, RNG_IT_DRDY) != RESET)
{
/* Generate random number once, so disable the IT */
__HAL_RNG_DISABLE_IT(hrng);
/* Get the 32bit Random number (DRDY flag automatically cleared) */
hrng->RandomNumber = hrng->Instance->DR;
if (hrng->State != HAL_RNG_STATE_ERROR)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/* Call registered Data Ready callback */
hrng->ReadyDataCallback(hrng, hrng->RandomNumber);
#else
/* Call legacy weak Data Ready callback */
HAL_RNG_ReadyDataCallback(hrng, hrng->RandomNumber);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
}
}
}
/**
* @brief Read latest generated random number.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval random value
*/
uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng)
{
return (hrng->RandomNumber);
}
/**
* @brief Data Ready callback in non-blocking mode.
* @note When RNG_FLAG_DRDY flag value is set, first random number has been read
* from DR register in IRQ Handler and is provided as callback parameter.
* Depending on valid data available in the conditioning output buffer,
* additional words can be read by the application from DR register till
* DRDY bit remains high.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @param random32bit generated random number.
* @retval None
*/
__weak void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrng);
UNUSED(random32bit);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_RNG_ReadyDataCallback must be implemented in the user file.
*/
}
/**
* @brief RNG error callbacks.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval None
*/
__weak void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrng);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_RNG_ErrorCallback must be implemented in the user file.
*/
}
/**
* @}
*/
/** @addtogroup RNG_Exported_Functions_Group3
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Returns the RNG state.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval HAL state
*/
HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng)
{
return hrng->State;
}
/**
* @brief Return the RNG handle error code.
* @param hrng: pointer to a RNG_HandleTypeDef structure.
* @retval RNG Error Code
*/
uint32_t HAL_RNG_GetError(RNG_HandleTypeDef *hrng)
{
/* Return RNG Error Code */
return hrng->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup RNG_Private_Functions
* @{
*/
/**
* @brief RNG sequence to recover from a seed error
* @param hrng pointer to a RNG_HandleTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef RNG_RecoverSeedError(RNG_HandleTypeDef *hrng)
{
__IO uint32_t count = 0U;
/*Check if seed error current status (SECS)is set */
if (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_SECS) == RESET)
{
/* RNG performed the reset automatically (auto-reset) */
/* Clear bit SEIS */
CLEAR_BIT(hrng->Instance->SR, RNG_IT_SEI);
}
else /* Sequence to fully recover from a seed error*/
{
/* Writing bit CONDRST=1*/
SET_BIT(hrng->Instance->CR, RNG_CR_CONDRST);
/* Writing bit CONDRST=0*/
CLEAR_BIT(hrng->Instance->CR, RNG_CR_CONDRST);
/* Wait for conditioning reset process to be completed */
count = RNG_TIMEOUT_VALUE;
do
{
count-- ;
if (count == 0U)
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode |= HAL_RNG_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/* Call registered Error callback */
hrng->ErrorCallback(hrng);
#else
/* Call legacy weak Error callback */
HAL_RNG_ErrorCallback(hrng);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
return HAL_ERROR;
}
} while (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST));
if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)
{
/* Clear bit SEIS */
CLEAR_BIT(hrng->Instance->SR, RNG_IT_SEI);
}
/* Wait for SECS to be cleared */
count = RNG_TIMEOUT_VALUE;
do
{
count-- ;
if (count == 0U)
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode |= HAL_RNG_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/* Call registered Error callback */
hrng->ErrorCallback(hrng);
#else
/* Call legacy weak Error callback */
HAL_RNG_ErrorCallback(hrng);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
return HAL_ERROR;
}
} while (HAL_IS_BIT_SET(hrng->Instance->SR, RNG_FLAG_SECS));
}
/* Update the error code */
hrng->ErrorCode &= ~ HAL_RNG_ERROR_SEED;
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_RNG_MODULE_ENABLED */
/**
* @}
*/
#endif /* RNG */
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rng.c
|
C
|
apache-2.0
| 31,511
|
/**
******************************************************************************
* @file stm32u5xx_hal_rng_ex.c
* @author MCD Application Team
* @brief Extended RNG HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Random Number Generator (RNG) peripheral:
* + Lock configuration functions
* + Reset the RNG
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
#if defined(RNG)
/** @addtogroup RNGEx
* @brief RNG Extended HAL module driver.
* @{
*/
#ifdef HAL_RNG_MODULE_ENABLED
#if defined(RNG_CR_CONDRST)
/* Private types -------------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup RNGEx_Private_Constants RNGEx Private Constants
* @{
*/
#define RNG_TIMEOUT_VALUE 2U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private functions prototypes ----------------------------------------------*/
/* Private functions --------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RNGEx_Exported_Functions
* @{
*/
/** @addtogroup RNGEx_Exported_Functions_Group1
* @brief Configuration functions
*
@verbatim
===============================================================================
##### Configuration and lock functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure the RNG with the specified parameters in the RNG_ConfigTypeDef
(+) Lock RNG configuration Allows user to lock a configuration until next reset.
@endverbatim
* @{
*/
/**
* @brief Configure the RNG with the specified parameters in the
* RNG_ConfigTypeDef.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @param pConf: pointer to a RNG_ConfigTypeDef structure that contains
* the configuration information for RNG module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNGEx_SetConfig(RNG_HandleTypeDef *hrng, RNG_ConfigTypeDef *pConf)
{
uint32_t tickstart;
uint32_t cr_value;
HAL_StatusTypeDef status ;
/* Check the RNG handle allocation */
if ((hrng == NULL) || (pConf == NULL))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RNG_ALL_INSTANCE(hrng->Instance));
assert_param(IS_RNG_CLOCK_DIVIDER(pConf->ClockDivider));
assert_param(IS_RNG_NIST_COMPLIANCE(pConf->NistCompliance));
assert_param(IS_RNG_CONFIG1(pConf->Config1));
assert_param(IS_RNG_CONFIG2(pConf->Config2));
assert_param(IS_RNG_CONFIG3(pConf->Config3));
assert_param(IS_RNG_ARDIS(pConf->AutoReset));
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Disable RNG */
__HAL_RNG_DISABLE(hrng);
/* RNG CR register configuration. Set value in CR register for :
- NIST Compliance setting
- Clock divider value
- Automatic reset to clear SECS bit
- CONFIG 1, CONFIG 2 and CONFIG 3 values */
cr_value = (uint32_t)(pConf->ClockDivider | pConf->NistCompliance | pConf->AutoReset
| (pConf->Config1 << RNG_CR_RNG_CONFIG1_Pos)
| (pConf->Config2 << RNG_CR_RNG_CONFIG2_Pos)
| (pConf->Config3 << RNG_CR_RNG_CONFIG3_Pos));
MODIFY_REG(hrng->Instance->CR, RNG_CR_NISTC | RNG_CR_CLKDIV | RNG_CR_RNG_CONFIG1
| RNG_CR_RNG_CONFIG2 | RNG_CR_RNG_CONFIG3,
(uint32_t)(RNG_CR_CONDRST | cr_value));
/* RNG health test control in accordance with NIST */
WRITE_REG(hrng->Instance->HTCR, pConf->HealthTest);
/* Writing bit CONDRST=0*/
CLEAR_BIT(hrng->Instance->CR, RNG_CR_CONDRST);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait for conditioning reset process to be completed */
while (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
if ((HAL_GetTick() - tickstart) > RNG_TIMEOUT_VALUE)
{
/* New check to avoid false timeout detection in case of prememption */
if (HAL_IS_BIT_SET(hrng->Instance->CR, RNG_CR_CONDRST))
{
hrng->State = HAL_RNG_STATE_READY;
hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
}
/* Enable RNG */
__HAL_RNG_ENABLE(hrng);
/* Initialize the RNG state */
hrng->State = HAL_RNG_STATE_READY;
/* function status */
status = HAL_OK;
}
else
{
hrng->ErrorCode = HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return the function status */
return status;
}
/**
* @brief Get the RNG Configuration and fill parameters in the
* RNG_ConfigTypeDef.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @param pConf: pointer to a RNG_ConfigTypeDef structure that contains
* the configuration information for RNG module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNGEx_GetConfig(RNG_HandleTypeDef *hrng, RNG_ConfigTypeDef *pConf)
{
HAL_StatusTypeDef status ;
/* Check the RNG handle allocation */
if ((hrng == NULL) || (pConf == NULL))
{
return HAL_ERROR;
}
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Get RNG parameters */
pConf->Config1 = (uint32_t)((hrng->Instance->CR & RNG_CR_RNG_CONFIG1) >> RNG_CR_RNG_CONFIG1_Pos) ;
pConf->Config2 = (uint32_t)((hrng->Instance->CR & RNG_CR_RNG_CONFIG2) >> RNG_CR_RNG_CONFIG2_Pos);
pConf->Config3 = (uint32_t)((hrng->Instance->CR & RNG_CR_RNG_CONFIG3) >> RNG_CR_RNG_CONFIG3_Pos);
pConf->ClockDivider = (hrng->Instance->CR & RNG_CR_CLKDIV);
pConf->NistCompliance = (hrng->Instance->CR & RNG_CR_NISTC);
pConf->AutoReset = (hrng->Instance->CR & RNG_CR_ARDIS);
pConf->HealthTest = (hrng->Instance->HTCR);
/* Initialize the RNG state */
hrng->State = HAL_RNG_STATE_READY;
/* function status */
status = HAL_OK;
}
else
{
hrng->ErrorCode |= HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return the function status */
return status;
}
/**
* @brief RNG current configuration lock.
* @note This function allows to lock RNG peripheral configuration.
* Once locked, HW RNG reset has to be performed prior any further
* configuration update.
* @param hrng pointer to a RNG_HandleTypeDef structure that contains
* the configuration information for RNG.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNGEx_LockConfig(RNG_HandleTypeDef *hrng)
{
HAL_StatusTypeDef status;
/* Check the RNG handle allocation */
if (hrng == NULL)
{
return HAL_ERROR;
}
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Perform RNG configuration Lock */
MODIFY_REG(hrng->Instance->CR, RNG_CR_CONFIGLOCK, RNG_CR_CONFIGLOCK);
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_READY;
/* function status */
status = HAL_OK;
}
else
{
hrng->ErrorCode = HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return the function status */
return status;
}
/**
* @}
*/
/** @addtogroup RNGEx_Exported_Functions_Group2
* @brief Recover from seed error function
*
@verbatim
===============================================================================
##### Configuration and lock functions #####
===============================================================================
[..] This section provide function allowing to:
(+) Recover from a seed error
@endverbatim
* @{
*/
/**
* @brief RNG sequence to recover from a seed error
* @param hrng: pointer to a RNG_HandleTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RNGEx_RecoverSeedError(RNG_HandleTypeDef *hrng)
{
HAL_StatusTypeDef status;
/* Check the RNG handle allocation */
if (hrng == NULL)
{
return HAL_ERROR;
}
/* Check RNG peripheral state */
if (hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* sequence to fully recover from a seed error */
status = RNG_RecoverSeedError(hrng);
}
else
{
hrng->ErrorCode = HAL_RNG_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return the function status */
return status;
}
/**
* @}
*/
/**
* @}
*/
#endif /* RNG_CR_CONDRST */
#endif /* HAL_RNG_MODULE_ENABLED */
/**
* @}
*/
#endif /* RNG */
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rng_ex.c
|
C
|
apache-2.0
| 9,774
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 the Power Controller (PWR) APB1 interface clock using the
__HAL_RCC_PWR_CLK_ENABLE() function.
(+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function.
(+) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function.
(+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function.
[..] To enable access to the RTC Domain and RTC registers, proceed as follows:
(#) 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() macro.
##### 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 @ref HAL_RTC_RegisterCallback() to register an interrupt callback.
Function @ref 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.
(+) 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.
(+) InternalTamper12EventCallback : RTC InternalTamper 12 Event callback.
(+) InternalTamper13EventCallback : RTC InternalTamper 13 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 @ref HAL_RTC_UnRegisterCallback() to reset a callback to the default
weak function.
@ref 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.
(+) 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.
(+) InternalTamper12EventCallback : RTC InternalTamper 12 Event callback.
(+) InternalTamper13EventCallback : RTC InternalTamper 13 Event callback.
(+) MspInitCallback : RTC MspInit callback.
(+) MspDeInitCallback : RTC MspDeInit callback.
By default, after the @ref HAL_RTC_Init() and when the state is HAL_RTC_STATE_RESET,
all callbacks are set to the corresponding weak functions :
examples @ref AlarmAEventCallback(), @ref TimeStampEventCallback().
Exception done for MspInit and MspDeInit callbacks that are reset to the legacy weak function
in the @ref HAL_RTC_Init()/@ref HAL_RTC_DeInit() only when these callbacks are null
(not registered beforehand).
If not, MspInit or MspDeInit are not null, @ref HAL_RTC_Init()/@ref 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 @ref HAL_RTC_RegisterCallback() before calling @ref HAL_RTC_DeInit()
or @ref 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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));
assert_param(IS_RTC_OUTPUT(hrtc->Init.OutPut));
assert_param(IS_RTC_OUTPUT_REMAP(hrtc->Init.OutPutRemap));
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));
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 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 InternalTamper12EventCallback */
hrtc->InternalTamper12EventCallback = HAL_RTCEx_InternalTamper12EventCallback;
/* Legacy weak InternalTamper13EventCallback */
hrtc->InternalTamper13EventCallback = HAL_RTCEx_InternalTamper13EventCallback;
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;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Enter Initialization mode */
status = RTC_EnterInitMode(hrtc);
if (status == HAL_OK)
{
/* 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));
/* 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 (status == HAL_OK)
{
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);
if (status == HAL_OK)
{
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;
/* 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 RTC CR register bits */
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->WUTR, RTC_WUTR_WUT);
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);
WRITE_REG(RTC->SCR, RTC_SCR_CITSF | RTC_SCR_CTSOVF | RTC_SCR_CTSF | RTC_SCR_CWUTF | RTC_SCR_CALRBF | \
RTC_SCR_CALRAF);
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
WRITE_REG(RTC->SECCFGR, (RTC_SECCFGR_SEC | RTC_SECCFGR_INITSEC | RTC_SECCFGR_CALSEC | RTC_SECCFGR_TSSEC \
| RTC_SECCFGR_WUTSEC | RTC_SECCFGR_ALRBSEC | RTC_SECCFGR_ALRASEC));
#endif /* (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
CLEAR_REG(RTC->PRIVCFGR);
/* Exit initialization mode */
status = RTC_ExitInitMode(hrtc);
if (status == HAL_OK)
{
/* Reset TAMP registers */
WRITE_REG(TAMP->CR1, RTC_INT_TAMPER_ALL);
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);
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
WRITE_REG(TAMP->SECCFGR, TAMP_SECCFGR_TAMPSEC);
#endif /* (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
CLEAR_REG(TAMP->PRIVCFGR);
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
if (status == HAL_OK)
{
#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) */
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_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_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_TAMPER12_EVENT_CB_ID Internal Tamper 12 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER13_EVENT_CB_ID Internal Tamper 13 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
*/
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;
}
/* Process locked */
__HAL_LOCK(hrtc);
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_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_TAMPER12_EVENT_CB_ID :
hrtc->InternalTamper12EventCallback = pCallback;
break;
case HAL_RTC_INTERNAL_TAMPER13_EVENT_CB_ID :
hrtc->InternalTamper13EventCallback = 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;
}
/* Release Lock */
__HAL_UNLOCK(hrtc);
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_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_TAMPER12_EVENT_CB_ID Internal Tamper 12 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER13_EVENT_CB_ID Internal Tamper 13 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)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hrtc);
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_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_TAMPER12_EVENT_CB_ID :
/* Legacy weak InternalTamper12EventCallback */
hrtc->InternalTamper12EventCallback = HAL_RTCEx_InternalTamper12EventCallback;
break;
case HAL_RTC_INTERNAL_TAMPER13_EVENT_CB_ID :
/* Legacy weak InternalTamper13EventCallback */
hrtc->InternalTamper13EventCallback = HAL_RTCEx_InternalTamper13EventCallback;
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;
}
/* Release Lock */
__HAL_UNLOCK(hrtc);
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);
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));
/* This interface is deprecated. To manage Daylight Saving Time, please use HAL_RTC_DST_xxx functions */
CLEAR_BIT(RTC->CR, RTC_CR_BKP);
/* This interface is deprecated. To manage Daylight Saving Time, please use HAL_RTC_DST_xxx functions */
SET_BIT(RTC->CR, (sTime->DayLightSaving | sTime->StoreOperation));
}
/* Exit Initialization mode */
status = RTC_ExitInitMode(hrtc);
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
if (status == HAL_OK)
{
hrtc->State = HAL_RTC_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return status;
}
/**
* @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(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(RTC->CR, RTC_CR_ADD1H);
__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(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(RTC->CR, RTC_CR_SUB1H);
__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(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(RTC->CR, RTC_CR_BKP);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/**
* @brief Daylight Saving Time, Clear the store operation bit.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTC_DST_ClearStoreOperation(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
CLEAR_BIT(RTC->CR, RTC_CR_BKP);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/**
* @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(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
return READ_BIT(RTC->CR, RTC_CR_BKP);
}
/**
* @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(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t tmpreg;
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);
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)
{
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(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
uint32_t datetmpreg;
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;
}
/**
* @}
*/
/** @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 binaryMode;
/* Process Locked */
__HAL_LOCK(hrtc);
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) */
binaryMode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN);
if (binaryMode != 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));
}
}
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Alarm register */
if (sAlarm->Alarm == RTC_ALARM_A)
{
/* Disable the Alarm A interrupt */
/* 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 (binaryMode == 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_ALRAOCLR);
}
else
{
/* Disable the Alarm A output clear */
CLEAR_BIT(RTC->CR, RTC_CR_ALRAOCLR);
}
/* 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 (binaryMode == 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_ALRBOCLR);
}
else
{
/* Disable the Alarm B output clear */
CLEAR_BIT(RTC->CR, RTC_CR_ALRBOCLR);
}
/* Configure the Alarm state: Enable Alarm */
SET_BIT(RTC->CR, RTC_CR_ALRBE);
}
/* 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 Set the specified RTC Alarm with Interrupt.
* @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 binaryMode;
/* Process Locked */
__HAL_LOCK(hrtc);
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) */
binaryMode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN);
if (binaryMode != 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));
}
}
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* 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 (binaryMode == 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_ALRAOCLR);
}
else
{
/* Disable the Alarm A output clear*/
CLEAR_BIT(RTC->CR, RTC_CR_ALRAOCLR);
}
/* 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 (binaryMode == 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_ALRBOCLR);
}
else
{
/* Disable the Alarm B Output clear */
CLEAR_BIT(RTC->CR, RTC_CR_ALRBOCLR);
}
/* Configure the Alarm interrupt */
SET_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE);
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
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);
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format)
{
uint32_t tmpreg;
uint32_t subsecondtmpreg;
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;
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/**
* @brief Handle Alarm secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get interrupt status */
uint32_t tmp = READ_REG(RTC->SMISR);
if ((tmp & RTC_SMISR_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_SMISR_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;
}
#else /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @brief Handle Alarm non-secure interrupt request.
* @note Alarm non-secure is available in non-secure 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;
}
#endif /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @brief Alarm A secure secure 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 secure secure callback is needed,
the HAL_RTC_AlarmAEventCallback could be implemented in the user file
*/
}
/**
* @brief Handle AlarmA Polling request.
* @param hrtc RTC handle
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while (READ_BIT(RTC->SR, RTC_SR_ALRAF) == 0U)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Alarm interrupt pending bit */
WRITE_REG(RTC->SCR, RTC_SCR_CALRAF);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
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;
UNUSED(hrtc);
/* 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)
{
return HAL_TIMEOUT;
}
}
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(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;
UNUSED(hrtc);
/* 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)
{
status = HAL_TIMEOUT;
hrtc->State = HAL_RTC_STATE_TIMEOUT;
}
}
}
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)
{
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)
{
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 bcdhigh = 0U;
uint8_t tmp_Value = Value;
while (tmp_Value >= 10U)
{
bcdhigh++;
tmp_Value -= 10U;
}
return ((uint8_t)(bcdhigh << 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rtc.c
|
C
|
apache-2.0
| 80,513
|
/**
******************************************************************************
* @file stm32u5xx_hal_rtc_ex.c
* @author MCD 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) 2021 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 different outputs:
(+) RTC_ALARM: this output is used to manage the RTC Alarm A, Alarm B
and WaKeUp signals.
To output the selected RTC signal, use the HAL_RTC_Init() function.
(+) RTC_CALIB: this output is 512Hz signal or 1Hz.
To enable the RTC_CALIB, use the HAL_RTCEx_SetCalibrationOutPut() function.
(+) Two pins can be used as RTC_ALARM or RTC_CALIB (PC13, PB2) managed on
the RTC_OR register.
(+) When the RTC_CALIB or RTC_ALARM output is selected, the RTC_OUT pin is
automatically configured in output alternate function.
*** 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.
*** 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 NoErase field on the RTC_TAMPCR register.
(+) With new RTC tamper configuration, you have to call HAL_RTC_Init() in order to
perform TAMP base address offset calculation.
(+) If you do not intend to have tamper using RTC clock, you can bypass its initialization
by setting ClockEnable inti field to RTC_CLOCK_DISABLE.
(+) Enable Internal tamper using HAL_RTCEx_SetInternalTamper. IT mode can be chosen using
setting Interrupt field.
*** Backup Data Registers configuration ***
===========================================
[..]
(+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite()
function.
(+) To read the RTC Backup Data registers, use the HAL_RTCEx_BKUPRead()
function.
(+) Before calling these functions you have to call HAL_RTC_Init() in order to
perform TAMP base address offset calculation.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @addtogroup RTCEx
* @brief RTC Extended HAL module driver
* @{
*/
#ifdef HAL_RTC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define TAMP_ALL (TAMP_CR1_TAMP1E | TAMP_CR1_TAMP2E | TAMP_CR1_TAMP3E | TAMP_CR1_TAMP4E | \
TAMP_CR1_TAMP5E | TAMP_CR1_TAMP6E | TAMP_CR1_TAMP7E | TAMP_CR1_TAMP8E)
/* 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
* @{
*/
/**
* @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 */
assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
UNUSED(RTC_TimeStampPin);
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Get the RTC_CR register and clear the bits to be configured */
CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Time Stamp TSEDGE and Enable bits */
SET_BIT(RTC->CR, (uint32_t)TimeStampEdge | RTC_CR_TSE);
/* 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 Set TimeStamp with Interrupt.
* @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_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin)
{
/* Check the parameters */
assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge));
assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin));
UNUSED(RTC_TimeStampPin);
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Get the RTC_CR register and clear the bits to be configured */
CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* 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);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate TimeStamp.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE));
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the internal Time Stamp Enable bits */
SET_BIT(RTC->CR, RTC_CR_ITSE);
/* 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 Deactivate Internal TimeStamp.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTimeStamp(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the internal Time Stamp Enable bits */
CLEAR_BIT(RTC->CR, RTC_CR_ITSE);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp,
RTC_DateTypeDef *sTimeStampDate, uint32_t Format)
{
uint32_t tmptime;
uint32_t tmpdate;
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);
}
/* Clear the TIMESTAMP Flags */
WRITE_REG(RTC->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF));
return HAL_OK;
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/**
* @brief Handle TimeStamp secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc)
{
if (READ_BIT(RTC->SMISR, RTC_SMISR_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 == 1)*/
/* 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;
}
#else /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @brief Handle TimeStamp non-secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc)
{
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 == 1 */
/* 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;
}
#endif /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @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(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while (READ_BIT(RTC->SR, RTC_SR_TSF) == 0U)
{
if (READ_BIT(RTC->SR, RTC_SR_TSOVF) != 0U)
{
/* Clear the TIMESTAMP OverRun Flag */
WRITE_REG(RTC->SCR, RTC_SCR_CTSOVF);
/* Change TIMESTAMP state */
hrtc->State = HAL_RTC_STATE_ERROR;
return HAL_ERROR;
}
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* 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)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Configure the 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);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Set wake up timer with interrupt.
* @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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* 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)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Configure the Wakeup Timer counter 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));
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate wake up timer counter.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc)
{
uint32_t tickstart;
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Disable the Wakeup Timer */
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(RTC->CR, (RTC_CR_WUTE | RTC_CR_WUTIE));
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is set and if Time out is reached exit */
while (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U)
{
if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Get wake up timer counter.
* @param hrtc RTC handle
* @retval Counter value
*/
uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
/* Get the counter value */
return (uint32_t)(READ_BIT(RTC->WUTR, RTC_WUTR_WUT));
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/**
* @brief Handle Wake Up Timer secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc)
{
if ((RTC->SMISR & RTC_SMISR_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 == 1 */
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
#else /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @brief Handle Wake Up Timer non-secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get the pending status of the WAKEUPTIMER Interrupt */
if (READ_BIT(RTC->MISR, RTC_MISR_WUTMF) != 0U)
{
/* Clear the WAKEUPTIMER interrupt pending bit */
WRITE_REG(RTC->SCR, RTC_SCR_CWUTF);
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call WakeUpTimerEvent registered Callback */
hrtc->WakeUpTimerEventCallback(hrtc);
#else
/* WAKEUPTIMER callback */
HAL_RTCEx_WakeUpTimerEventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
#endif /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @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(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
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))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the WAKEUPTIMER Flag */
WRITE_REG(RTC->SCR, RTC_SCR_CWUTF);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
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 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* check if a calibration is pending*/
if (READ_BIT(RTC->ICSR, RTC_ICSR_RECALPF) != 0U)
{
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)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Configure the Smooth calibration settings */
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 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);
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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
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)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
/* Check if the reference clock detection is disabled */
if (READ_BIT(RTC->CR, RTC_CR_REFCKON) == 0U)
{
/* 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);
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
}
}
else
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the RTC_CR register */
MODIFY_REG(RTC->CR, RTC_CR_COSEL, CalibOutput);
/* Enable calibration output */
SET_BIT(RTC->CR, RTC_CR_COE);
/* 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 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Disable calibration output */
CLEAR_BIT(RTC->CR, RTC_CR_COE);
/* 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 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);
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)
{
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);
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)
{
hrtc->State = HAL_RTC_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return status;
}
/**
* @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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set the BYPSHAD bit */
SET_BIT(RTC->CR, RTC_CR_BYPSHAD);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief 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);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Reset the BYPSHAD bit */
CLEAR_BIT(RTC->CR, RTC_CR_BYPSHAD);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Increment Monotonic counter.
* @param hrtc RTC handle
* @param Instance Monotonic counter Instance
* This parameter can be can be one of the following values :
* @arg RTC_MONOTONIC_COUNTER_1
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterIncrement(RTC_HandleTypeDef *hrtc, uint32_t Instance)
{
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->COUNTR);
return HAL_OK;
}
/**
* @brief Monotonic counter incrementation.
* @param hrtc RTC handle
* @param Instance Monotonic counter Instance
* This parameter can be can be one of the following values :
* @arg RTC_MONOTONIC_COUNTER_1
* @param Value Pointer to the counter monotonic counter value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterGet(RTC_HandleTypeDef *hrtc, uint32_t Instance, uint32_t *Value)
{
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. */
*Value = READ_REG(TAMP->COUNTR);
return HAL_OK;
}
/**
* @brief Set SSR Underflow detection with Interrupt.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetSSRU_IT(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Enable IT SSRU */
__HAL_RTC_SSRU_ENABLE_IT(hrtc, RTC_IT_SSRU);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate SSR Underflow.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateSSRU(RTC_HandleTypeDef *hrtc)
{
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_SSRU_DISABLE_IT(hrtc, RTC_IT_TS);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/**
* @brief Handle SSR underflow interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_SSRUIRQHandler(RTC_HandleTypeDef *hrtc)
{
if ((RTC->SMISR & RTC_SMISR_SSRUMF) != 0u)
{
/* Immediately clear flags */
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;
}
#else
/**
* @brief Handle SSR underflow interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_SSRUIRQHandler(RTC_HandleTypeDef *hrtc)
{
if ((RTC->MISR & RTC_MISR_SSRUMF) != 0u)
{
/* Immediately clear flags */
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 == 1 */
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @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(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
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))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Alarm Flag */
WRITE_REG(RTC->SCR, RTC_SCR_CALRBF);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
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 ine 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(RTC_HandleTypeDef *hrtc, 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));
/* Mask flag only supported by TAMPER 1, 2 and 3 */
assert_param(!((sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) && (sTamper->Tamper > RTC_TAMPER_3)));
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_TAMP1NOERASE_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_TAMP1NOERASE_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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* Control register 1 */
SET_BIT(TAMP->CR1, sTamper->Tamper);
return HAL_OK;
}
/**
* @brief Set Tamper in IT mode
* @param hrtc RTC handle
* @param sTamper Pointer to Tamper Structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, 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_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));
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection));
/* 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_TAMP1NOERASE_Pos));
if (sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE)
{
tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos);
}
if (sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE)
{
/* Feature only supported by TAMPER 1, 2 and 3 */
if (sTamper->Tamper < RTC_TAMPER_4)
{
tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos);
}
else
{
return HAL_ERROR;
}
}
if (sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE)
{
tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1NOERASE_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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* 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(RTC_HandleTypeDef *hrtc, uint32_t Tamper)
{
UNUSED(hrtc);
assert_param(IS_RTC_TAMPER(Tamper));
/* Disable the selected Tamper pin */
CLEAR_BIT(TAMP->CR1, Tamper);
/* Clear tamper mask/noerase/trigger configuration */
CLEAR_BIT(TAMP->CR2, (Tamper << TAMP_CR2_TAMP1TRG_Pos) | (Tamper << TAMP_CR2_TAMP1MSK_Pos) | \
(Tamper << TAMP_CR2_TAMP1NOERASE_Pos));
/* Clear tamper interrupt mode configuration */
CLEAR_BIT(TAMP->IER, Tamper);
/* Clear tamper interrupt and event flags (WO register) */
WRITE_REG(TAMP->SCR, Tamper);
return HAL_OK;
}
/**
* @brief Set all active Tampers at the same time.
* @param hrtc RTC handle
* @param sAllTamper Pointer to active Tamper Structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetActiveTampers(RTC_HandleTypeDef *hrtc, RTC_ActiveTampersTypeDef *sAllTamper)
{
uint32_t IER;
uint32_t CR1;
uint32_t CR2;
uint32_t ATCR1;
uint32_t ATCR2;
uint32_t 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_DISABLE) && (i > RTC_TAMPER_3)));
}
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sAllTamper->TimeStampOnTamperDetection));
#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 */
CR = READ_REG(RTC->CR);
if ((CR & RTC_CR_TAMPTS) != (sAllTamper->TimeStampOnTamperDetection))
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sAllTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
CR1 = READ_REG(TAMP->CR1);
CR2 = READ_REG(TAMP->CR2);
ATCR2 = 0U;
IER = READ_REG(TAMP->IER);
/* Set common parameters */
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)
{
CR1 |= (TAMP_CR1_TAMP1E << i);
ATCR1 |= (TAMP_ATCR1_TAMP1AM << i);
if (sAllTamper->TampInput[i].Interrupt != RTC_ATAMP_INTERRUPT_DISABLE)
{
/* Interrupt enable register */
IER |= (TAMP_IER_TAMP1IE << i);
}
if (sAllTamper->TampInput[i].MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE)
{
CR2 |= (TAMP_CR2_TAMP1MSK << i);
}
if (sAllTamper->TampInput[i].NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE)
{
CR2 |= (TAMP_CR2_TAMP1NOERASE << i);
}
/* Configure ATOSELx[] in case of output sharing */
ATCR2 |= sAllTamper->TampInput[i].Output << ((3u * i) + TAMP_ATCR2_ATOSEL1_Pos);
if (i != sAllTamper->TampInput[i].Output)
{
ATCR1 |= TAMP_ATCR1_ATOSHARE;
}
}
}
WRITE_REG(TAMP->IER, IER);
WRITE_REG(TAMP->IER, IER);
WRITE_REG(TAMP->ATCR1, ATCR1);
WRITE_REG(TAMP->ATCR2, ATCR2);
WRITE_REG(TAMP->CR2, CR2);
WRITE_REG(TAMP->CR1, 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 set 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)
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @brief Get active Tampers configuration.
* @param sAllTamper Pointer to active Tamper Structure.
* @retval none
*/
void HAL_RTCEx_GetActiveTampers(RTC_ActiveTampersTypeDef *sAllTamper)
{
uint32_t i ;
sAllTamper->ActiveFilter = (uint32_t)(TAMP->ATCR1 & TAMP_ATCR1_FLTEN);
sAllTamper->ActiveOutputChangePeriod = (uint32_t)((TAMP->ATCR1 & TAMP_ATCR1_ATPER) >> TAMP_ATCR1_ATPER_Pos);
sAllTamper->ActiveAsyncPrescaler = (uint32_t)(TAMP->ATCR1 & TAMP_ATCR1_ATCKSEL);
sAllTamper->TimeStampOnTamperDetection = (uint32_t)(RTC->CR & RTC_CR_TAMPTS);
/* Set specific parameters for each active tamper inputs if enable */
for (i = 0; i < RTC_TAMP_NB; i++)
{
sAllTamper->TampInput[i].Enable = (uint32_t)(((TAMP->CR1 & (TAMP_CR1_TAMP1E << i))) >> i);
sAllTamper->TampInput[i].Interrupt = (uint32_t)(((TAMP->IER & (TAMP_IER_TAMP1IE << i))) >> i);
sAllTamper->TampInput[i].MaskFlag = (uint32_t)(((TAMP->CR2 & (TAMP_CR2_TAMP1MSK << i))) >> i);
sAllTamper->TampInput[i].NoErase = (uint32_t)(((TAMP->CR2 & (TAMP_CR2_TAMP1NOERASE << i))) >> i);
sAllTamper->TampInput[i].Output = (uint32_t)(((TAMP->ATCR2 & (TAMP_ATCR2_ATOSEL1 << ((3u * i)))) \
>> ((3u * i) + TAMP_ATCR2_ATOSEL1_Pos)));
}
}
/**
* @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, 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 set 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)
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @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_SetBoothardwareKey(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
WRITE_REG(TAMP->SECCFGR, TAMP_SECCFGR_BHKLOCK);
return HAL_OK;
}
/**
* @brief Deactivate all Active Tampers at the same time.
* @param hrtc RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateActiveTampers(RTC_HandleTypeDef *hrtc)
{
/* Get Active tampers */
uint32_t ATamp_mask = READ_BIT(TAMP->ATCR1, TAMP_ALL);
UNUSED(hrtc);
/* Disable all actives tampers but not passives tampers */
CLEAR_BIT(TAMP->CR1, 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 tamper interrupt and event flags (WO register) of all actives tampers but not passives tampers */
WRITE_REG(TAMP->SCR, ATamp_mask);
/* Clear all active tampers interrupt mode configuration but not passives tampers */
CLEAR_BIT(TAMP->IER, ATamp_mask);
CLEAR_BIT(TAMP->ATCR1, TAMP_ALL | TAMP_ATCR1_ATCKSEL | TAMP_ATCR1_ATPER | \
TAMP_ATCR1_ATOSHARE | TAMP_ATCR1_FLTEN);
CLEAR_BIT(TAMP->ATCR2, TAMP_ATCR2_ATOSEL1 | TAMP_ATCR2_ATOSEL2 | TAMP_ATCR2_ATOSEL3 | TAMP_ATCR2_ATOSEL4 |
TAMP_ATCR2_ATOSEL5 | TAMP_ATCR2_ATOSEL6 | TAMP_ATCR2_ATOSEL7 | TAMP_ATCR2_ATOSEL8);
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(RTC_HandleTypeDef *hrtc, uint32_t Tamper, uint32_t Timeout)
{
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))
{
return HAL_TIMEOUT;
}
}
}
/* 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(RTC_HandleTypeDef *hrtc, 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 on internal tamper */
if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE)
{
/* Control register 3 */
SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1NOER_Pos)));
}
else
{
CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1NOER_Pos)));
}
/* Control register 1 */
SET_BIT(TAMP->CR1, sIntTamper->IntTamper);
return HAL_OK;
}
/**
* @brief Get Internal Tamper Configuration
* @param sIntTamper Pointer to Internal Tamper Structure.
* @retval HAL status
*/
void HAL_RTCEx_GetInternalTampers(RTC_InternalTamperTypeDef *sIntTamper)
{
sIntTamper->IntTamper = (uint32_t)(TAMP->CR1 & (RTC_INT_TAMPER_ALL));
sIntTamper->TimeStampOnTamperDetection = (uint32_t)(RTC->CR & RTC_CR_TAMPTS);
if ((uint32_t)(TAMP->CR3 & (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1NOER_Pos))) != 0U)
{
sIntTamper->NoErase = RTC_TAMPER_ERASE_BACKUP_DISABLE;
}
else
{
sIntTamper->NoErase = RTC_TAMPER_ERASE_BACKUP_ENABLE;
}
}
/**
* @brief Set Internal Tamper in interrupt mode
* @param hrtc RTC handle
* @param sIntTamper Pointer to Internal Tamper Structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetInternalTamper_IT(RTC_HandleTypeDef *hrtc, 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 on internal tamper */
if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* Interrupt enable register */
SET_BIT(TAMP->IER, sIntTamper->IntTamper);
if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE)
{
/* Control register 3 */
SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1NOER_Pos)));
}
else
{
CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1NOER_Pos)));
}
/* Control register 1 */
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(RTC_HandleTypeDef *hrtc, uint32_t IntTamper)
{
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(RTC_HandleTypeDef *hrtc, uint32_t IntTamper, uint32_t Timeout)
{
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))
{
return HAL_TIMEOUT;
}
}
}
/* Clear the Tamper Flag */
WRITE_REG(TAMP->SCR, IntTamper);
return HAL_OK;
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/** @brief Handle Tamper secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TamperIRQHandler(RTC_HandleTypeDef *hrtc)
{
uint32_t tmp;
/* Get secure interrupt status */
tmp = READ_REG(TAMP->SMISR);
/* Immediately clear flags */
WRITE_REG(TAMP->SCR, tmp);
/* Check Tamper1 status */
if ((tmp & RTC_TAMPER_1) == RTC_TAMPER_1)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 1 Event registered secure Callback */
hrtc->Tamper1EventCallback(hrtc);
#else
/* Tamper1 secure callback */
HAL_RTCEx_Tamper1EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper2 status */
if ((tmp & RTC_TAMPER_2) == RTC_TAMPER_2)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 2 Event registered secure Callback */
hrtc->Tamper2EventCallback(hrtc);
#else
/* Tamper2 secure callback */
HAL_RTCEx_Tamper2EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper3 status */
if ((tmp & RTC_TAMPER_3) == RTC_TAMPER_3)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 3 Event registered secure Callback */
hrtc->Tamper3EventCallback(hrtc);
#else
/* Tamper3 secure callback */
HAL_RTCEx_Tamper3EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper4 status */
if ((tmp & RTC_TAMPER_4) == RTC_TAMPER_4)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 4 Event registered secure Callback */
hrtc->Tamper4EventCallback(hrtc);
#else
/* Tamper4 secure callback */
HAL_RTCEx_Tamper4EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper5 status */
if ((tmp & RTC_TAMPER_5) == RTC_TAMPER_5)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 5 Event registered secure Callback */
hrtc->Tamper5EventCallback(hrtc);
#else
/* Tamper5 secure callback */
HAL_RTCEx_Tamper5EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper6 status */
if ((tmp & RTC_TAMPER_6) == RTC_TAMPER_6)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 6 Event registered secure Callback */
hrtc->Tamper6EventCallback(hrtc);
#else
/* Tamper6 secure callback */
HAL_RTCEx_Tamper6EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper7 status */
if ((tmp & RTC_TAMPER_7) == RTC_TAMPER_7)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 7 Event registered secure Callback */
hrtc->Tamper7EventCallback(hrtc);
#else
/* Tamper7 secure callback */
HAL_RTCEx_Tamper7EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Tamper8 status */
if ((tmp & RTC_TAMPER_8) == RTC_TAMPER_8)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 8 Event registered secure Callback */
hrtc->Tamper8EventCallback(hrtc);
#else
/* Tamper8 secure callback */
HAL_RTCEx_Tamper8EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper1EventCallback(hrtc);
#else
/* Internal Tamper1 secure callback */
HAL_RTCEx_InternalTamper1EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper2EventCallback(hrtc);
#else
/* Internal Tamper2 secure callback */
HAL_RTCEx_InternalTamper2EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper3EventCallback(hrtc);
#else
/* Internal Tamper3 secure callback */
HAL_RTCEx_InternalTamper3EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper5EventCallback(hrtc);
#else
/* Internal Tamper5 secure callback */
HAL_RTCEx_InternalTamper5EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper6EventCallback(hrtc);
#else
/* Internal Tamper6 secure callback */
HAL_RTCEx_InternalTamper6EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper7EventCallback(hrtc);
#else
/* Internal Tamper7 secure callback */
HAL_RTCEx_InternalTamper7EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper8EventCallback(hrtc);
#else
/* Internal Tamper8 secure callback */
HAL_RTCEx_InternalTamper8EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper9EventCallback(hrtc);
#else
/* Internal Tamper9 secure callback */
HAL_RTCEx_InternalTamper9EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* 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 secure Callback */
hrtc->InternalTamper11EventCallback(hrtc);
#else
/* Internal Tamper11 secure callback */
HAL_RTCEx_InternalTamper11EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Check Internal Tamper12 status */
if ((tmp & RTC_INT_TAMPER_12) == RTC_INT_TAMPER_12)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 12 Event registered secure Callback */
hrtc->InternalTamper12EventCallback(hrtc);
#else
/* Internal Tamper 12 secure callback */
HAL_RTCEx_InternalTamper12EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Check Internal Tamper13 status */
if ((tmp & RTC_INT_TAMPER_13) == RTC_INT_TAMPER_13)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 13 Event registered secure Callback */
hrtc->InternalTamper13EventCallback(hrtc);
#else
/* Internal Tamper 13 secure callback */
HAL_RTCEx_InternalTamper13EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
}
#else
/**
* @brief Handle Tamper non-secure interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TamperIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get interrupt status */
uint32_t tmp = READ_REG(TAMP->MISR);
/* Immediately clear flags */
WRITE_REG(TAMP->SCR, tmp);
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1) */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1) */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* 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 == 1 */
}
/* Check Internal Tamper12 status */
if ((tmp & RTC_INT_TAMPER_12) == RTC_INT_TAMPER_12)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 12 Event registered Callback */
hrtc->InternalTamper12EventCallback(hrtc);
#else
/* Internal Tamper12 callback */
HAL_RTCEx_InternalTamper12EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
/* Check Internal Tamper13 status */
if ((tmp & RTC_INT_TAMPER_13) == RTC_INT_TAMPER_13)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 13 Event registered Callback */
hrtc->InternalTamper13EventCallback(hrtc);
#else
/* Internal Tamper13 callback */
HAL_RTCEx_InternalTamper13EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS == 1 */
}
}
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @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 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 12 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_InternalTamper12EventCallback(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_InternalTamper12EventCallback could be implemented in the user file
*/
}
/**
* @brief Internal Tamper 13 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_InternalTamper13EventCallback(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_InternalTamper13EventCallback 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 ine 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(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data)
{
uint32_t tmp;
UNUSED(hrtc);
/* Check the parameters */
assert_param(IS_RTC_BKP(BackupRegister));
tmp = (uint32_t) &(TAMP->BKP0R);
tmp += (BackupRegister * 4U);
/* Write the specified register */
*(__IO uint32_t *)tmp = (uint32_t)Data;
}
/**
* @brief Reads data from the specified RTC Backup data Register.
* @param hrtc RTC handle
* @param BackupRegister RTC Backup data Register number.
* This parameter can be RTC_BKP_DRx where x can be from 0 to RTC_BACKUP_NB
* @retval Read value
*/
uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister)
{
uint32_t tmp;
UNUSED(hrtc);
/* Check the parameters */
assert_param(IS_RTC_BKP(BackupRegister));
tmp = (uint32_t) &(TAMP->BKP0R);
tmp += (BackupRegister * 4U);
/* Read the specified register */
return (*(__IO uint32_t *)tmp);
}
/**
* @brief Reset the RTC Backup data Register and the device secrets.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_BKUPErase(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
WRITE_REG(TAMP->CR2, TAMP_CR2_BKERASE);
}
/**
* @brief Block the access to the RTC Backup data Register and the device secrets.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_BKUPBlock_Enable(RTC_HandleTypeDef *hrtc)
{
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_BKUPBlock_Disable(RTC_HandleTypeDef *hrtc)
{
UNUSED(hrtc);
CLEAR_BIT(TAMP->CR2, TAMP_CR2_BKBLOCK);
}
/**
* @brief Enable and Disable the erase of the configurable Device Secerts
* @note This API must be called before enabling the Tamper.
* @param hrtc RTC handle
* @param SecretDeviceConf Specifies the configuration of the Secrets Devices
* This parameter can be one of the following values:
* @arg TAMP_SECRETDEVICE_ERASE_ENABLE: Configurable device secrets are is included in the device secrets
* protected by TAMP peripheral.
* @arg TAMP_SECRETDEVICE_ERASE_DISABLE: Configurable device secrets are not included in the device
* secrets protected by TAMP peripheral.
* @retval None
*/
void HAL_RTCEx_Erase_SecretDev_Conf(RTC_HandleTypeDef *hrtc, uint32_t SecretDeviceConf)
{
UNUSED(hrtc);
if (SecretDeviceConf != TAMP_SECRETDEVICE_ERASE_ENABLE)
{
CLEAR_BIT(TAMP->ERCFGR, TAMP_ERCFGR0);
}
else
{
SET_BIT(TAMP->ERCFGR, TAMP_ERCFGR0);
}
}
/**
* @brief Get the erase configuration of the Device Secerts
* @retval RTCEx_TAMP_Secret_Device_Conf_Erase
*/
uint32_t HAL_RTCEx_Get_Erase_SecretDev_Conf(void)
{
if (READ_BIT(TAMP->ERCFGR, TAMP_ERCFGR0) == TAMP_ERCFGR0)
{
return TAMP_SECRETDEVICE_ERASE_ENABLE;
}
else
{
return TAMP_SECRETDEVICE_ERASE_DISABLE;
}
}
/**
* @}
*/
/** @addtogroup RTCEx_Exported_Functions_Group7
* @brief Extended RTC security functions
*
@verbatim
===============================================================================
##### Extended RTC security functions #####
===============================================================================
[..]
(+) Before calling security function, you have to call first
HAL_RTC_Init() function.
@endverbatim
* @{
*/
/**
* @brief Get the security level of the RTC.
* To set the secure level please call HAL_RTCEx_SecureModeSet.
* @param hrtc RTC handle
* @param secureState Secure state
* @retval HAL_StatusTypeDef
*/
HAL_StatusTypeDef HAL_RTCEx_SecureModeGet(RTC_HandleTypeDef *hrtc, RTC_SecureStateTypeDef *secureState)
{
UNUSED(hrtc);
/* Read registers */
uint32_t rtc_seccfgr = READ_REG(RTC->SECCFGR);
uint32_t tamp_seccfgr = READ_REG(TAMP->SECCFGR);
/* RTC */
secureState->rtcSecureFull = READ_BIT(rtc_seccfgr, RTC_SECCFGR_SEC);
/* Warning, rtcNonSecureFeatures is only relevant if secureState->rtcSecureFull == RTC_SECURE_FULL_NO */
secureState->rtcNonSecureFeatures = READ_BIT(rtc_seccfgr, RTC_NONSECURE_FEATURE_NONE);
/* TAMP */
secureState->tampSecureFull = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_TAMPSEC);
/* Monotonic Counter */
secureState->MonotonicCounterSecure = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_CNT1SEC);
/* Backup register start zones
Warning : Backup register start zones are shared with privilege configuration */
secureState->backupRegisterStartZone2 = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_BKPRWSEC) >> TAMP_SECCFGR_BKPRWSEC_Pos;
secureState->backupRegisterStartZone3 = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_BKPWSEC) >> TAMP_SECCFGR_BKPWSEC_Pos;
return HAL_OK;
}
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/**
* @brief Set the security level of the RTC/TAMP/Backup registers.
* To get the current security level call HAL_RTCEx_SecureModeGet.
* @param hrtc RTC handle
* @param secureState Secure state
* @retval HAL_StatusTypeDef
*/
HAL_StatusTypeDef HAL_RTCEx_SecureModeSet(RTC_HandleTypeDef *hrtc, RTC_SecureStateTypeDef *secureState)
{
UNUSED(hrtc);
assert_param(IS_RTC_SECURE_FULL(secureState->rtcSecureFull));
assert_param(IS_RTC_NONSECURE_FEATURES(secureState->rtcNonSecureFeatures));
assert_param(IS_TAMP_SECURE_FULL(secureState->tampSecureFull));
assert_param(IS_RTC_BKP(secureState->backupRegisterStartZone2));
assert_param(IS_RTC_BKP(secureState->backupRegisterStartZone3));
assert_param(IS_TAMP_MONOTONIC_CNT_SECURE(secureState->MonotonicCounterSecure));
/* RTC, rtcNonSecureFeatures is only relevant if secureState->rtcSecureFull == RTC_SECURE_FULL_NO */
WRITE_REG(RTC->SECCFGR, secureState->rtcSecureFull | secureState->rtcNonSecureFeatures);
/* Tamper + Backup register + Monotonic counter
Warning : Backup register start zone are Shared with privilege configuration */
WRITE_REG(TAMP->SECCFGR,
secureState->tampSecureFull | secureState->MonotonicCounterSecure |
(TAMP_SECCFGR_BKPRWSEC & (secureState->backupRegisterStartZone2 << TAMP_SECCFGR_BKPRWSEC_Pos)) |
(TAMP_SECCFGR_BKPWSEC & (secureState->backupRegisterStartZone3 << TAMP_SECCFGR_BKPWSEC_Pos)));
return HAL_OK;
}
#endif /* #if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @}
*/
/** @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 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(RTC_HandleTypeDef *hrtc, RTC_PrivilegeStateTypeDef *privilegeState)
{
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
Warning : privilegeState->backupRegisterPrivZone is only writable in secure mode or if trustzone is disabled.
In non secure mode, a notification is generated through a flag/interrupt in the TZIC
(TrustZone interrupt controller). The bits are not written. */
WRITE_REG(TAMP->PRIVCFGR, privilegeState->tampPrivilegeFull | privilegeState->backupRegisterPrivZone | \
privilegeState->MonotonicCounterPrivilege);
/* Backup register start zone
Warning : This parameter is only writable in secure mode or if trustzone is disabled.
In non secure mode, a notification is generated through a flag/interrupt in the TZIC
(TrustZone interrupt controller). The bits are not written.
Warning : Backup register start zones are shared with secure configuration */
MODIFY_REG(TAMP->SECCFGR,
(TAMP_SECCFGR_BKPRWSEC | TAMP_SECCFGR_BKPWSEC),
((privilegeState->backupRegisterStartZone2 << TAMP_SECCFGR_BKPRWSEC_Pos) | \
(privilegeState->backupRegisterStartZone3 << TAMP_SECCFGR_BKPWSEC_Pos)));
return HAL_OK;
}
/**
* @brief Get the privilege level of the RTC.
* 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(RTC_HandleTypeDef *hrtc, RTC_PrivilegeStateTypeDef *privilegeState)
{
/* Read registers */
uint32_t rtc_privcfgr = READ_REG(RTC->PRIVCFGR);
uint32_t tamp_privcfgr = READ_REG(TAMP->PRIVCFGR);
uint32_t tamp_seccfgr = READ_REG(TAMP->SECCFGR);
UNUSED(hrtc);
/* 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 register start zones
Warning : Shared with secure configuration */
privilegeState->backupRegisterStartZone2 = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_BKPRWSEC) >> TAMP_SECCFGR_BKPRWSEC_Pos;
privilegeState->backupRegisterStartZone3 = READ_BIT(tamp_seccfgr, TAMP_SECCFGR_BKPWSEC) >> TAMP_SECCFGR_BKPWSEC_Pos;
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_RTC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_rtc_ex.c
|
C
|
apache-2.0
| 101,618
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 stm32u5xx_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 (surcharged) 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 (surcharged) functions:
examples HAL_SAI_RxCpltCallback(), HAL_SAI_ErrorCallback().
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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
/**
* @}
*/
/* 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 = 64U;
}
else if (hsai->Init.Protocol == SAI_AC97_PROTOCOL)
{
/* For AC97 protocol, frame length is set by hardware to 256 */
tmpframelength = 256U;
}
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 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;
}
}
}
/* Disable SAI peripheral */
if (SAI_Disable(hsai) != HAL_OK)
{
status = HAL_ERROR;
}
/* 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);
/* 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;
/* Disable SAI peripheral */
if (SAI_Disable(hsai) != HAL_OK)
{
status = HAL_ERROR;
}
/* 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(SAI_HandleTypeDef *hsai)
{
return hsai->State;
}
/**
* @brief Return the SAI error code.
* @param hsai pointer to a SAI_HandleTypeDef structure that contains
* the configuration information for the specified SAI Block.
* @retval SAI Error Code
*/
uint32_t HAL_SAI_GetError(SAI_HandleTypeDef *hsai)
{
return hsai->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_sai.c
|
C
|
apache-2.0
| 91,846
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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(SAI_HandleTypeDef *hsai, 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 */
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_sai_ex.c
|
C
|
apache-2.0
| 3,789
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 (surcharged) 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 (surcharged) functions.
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @addtogroup SD
* @{
*/
#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_HighSpeed(SD_HandleTypeDef *hsd);
#if (USE_SD_TRANSCEIVER != 0U)
static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd);
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_DATATIMEOUT)
{
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 = 0U;
/* 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*/
if ((hsd->Instance == SDMMC1) || (hsd->Instance == SDMMC2))
{
sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC);
}
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 */
sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv);
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 *= 512U;
}
/* 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 >= 32U))
{
/* Read data from SDMMC Rx FIFO */
for (count = 0U; count < 8U; 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 -= 32U;
}
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, 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 *= 512U;
}
/* 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 >= 32U))
{
/* Write data to SDMMC Tx FIFO */
for (count = 0U; count < 8U; 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 -= 32U;
}
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 *= 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);
__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, 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 *= 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);
/* 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 *= 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);
__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, 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 *= 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->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 *= 512U;
end_add *= 512U;
}
/* 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(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(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 (surcharged) predefined callback
* @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;
}
/* Process locked */
__HAL_LOCK(hsd);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsd);
return status;
}
/**
* @brief Unregister a User SD Callback
* SD Callback is redirected to the weak (surcharged) predefined callback
* @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;
/* Process locked */
__HAL_LOCK(hsd);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsd);
return status;
}
#if (USE_SD_TRANSCEIVER != 0U)
/**
* @brief Register a User SD Transceiver Callback
* To be used instead of the weak (surcharged) 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 (surcharged) 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) / 512U);
hsd->SdCard.LogBlockSize = 512U;
}
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 = 512U;
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 = 0U;
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
{
/* MMC 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
{
if ((hsd->Instance == SDMMC1) || (hsd->Instance == SDMMC2))
{
sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC);
}
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) != HAL_SD_ERROR_NONE)
{
if (SD_HighSpeed(hsd) != 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_HighSpeed(hsd) != 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:
{
if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) ||
(hsd->SdCard.CardType == CARD_SDHC_SDXC))
{
/* Enable UltraHigh Speed */
if (SD_UltraHighSpeed(hsd) != 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_HighSpeed(hsd) != 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:
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_HighSpeed(hsd) != 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_HighSpeed(hsd) != 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:
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_HighSpeed(hsd) != 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_HighSpeed(hsd) != 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:
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_DATATIMEOUT)
{
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)
{
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);
/* Clear All flags */
__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;
CardState = HAL_SD_GetCardState(hsd);
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;
}
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_DATATIMEOUT)
{
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_DATATIMEOUT)
{
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_DATATIMEOUT)
{
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_DATATIMEOUT)
{
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_DATATIMEOUT)
{
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) << 24) | ((tempscr[1] & SDMMC_8TO15BITS) << 8) | \
((tempscr[1] & SDMMC_16TO23BITS) >> 8) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24));
scr++;
*scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24) | ((tempscr[0] & SDMMC_8TO15BITS) << 8) | \
((tempscr[0] & SDMMC_16TO23BITS) >> 8) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24));
}
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 >= 32U)
{
/* Read data from SDMMC Rx FIFO */
for (count = 0U; count < 8U; 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 -= 32U;
}
}
/**
* @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;
uint8_t *tmp;
tmp = hsd->pTxBuffPtr;
if (hsd->TxXferSize >= 32U)
{
/* Write data to SDMMC Tx FIFO */
for (count = 0U; count < 8U; 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 -= 32U;
}
}
/**
* @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 50 and 120 MHz
* @param hsd: SD handle
* @retval SD Card error state
*/
uint32_t SD_HighSpeed(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_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, SDMMC_SDR25_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_DATATIMEOUT)
{
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
* @retval SD Card error state
*/
static uint32_t SD_UltraHighSpeed(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_SDR104_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_DATATIMEOUT)
{
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_DATATIMEOUT)
{
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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_sd.c
|
C
|
apache-2.0
| 122,462
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup SDEx SDEx
* @brief SD Extended HAL module driver
* @{
*/
#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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_sd_ex.c
|
C
|
apache-2.0
| 11,898
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 (surcharged) 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 (surcharged) functions:
examples HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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);
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);
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 instead of the weak predefined callback
* @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;
}
/* Process locked */
__HAL_LOCK(hsmartcard);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmartcard);
return status;
}
/**
* @brief Unregister an SMARTCARD callback
* SMARTCARD callback is redirected to the weak predefined callback
* @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;
/* Process locked */
__HAL_LOCK(hsmartcard);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmartcard);
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;
}
}
/**
* @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;
}
}
/**
* @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));
/* 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;
}
}
}
}
/* 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);
}
/* 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;
}
}
}
}
/* 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);
}
/* 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;
}
}
}
}
/* 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 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;
}
}
}
/* 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);
}
/* 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
{
/* 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);
}
/* 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
{
/* 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);
/* 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
{
#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);
/* 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
{
#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(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(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;
}
MODIFY_REG(hsmartcard->Instance->RTOR, (USART_RTOR_RTO | USART_RTOR_BLEN), 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_HSI:
tmpreg = (uint32_t)(((HSI_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) +
(hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate);
break;
case SMARTCARD_CLOCKSOURCE_SYSCLK:
pclk = HAL_RCC_GetSysClockFreq();
tmpreg = (uint32_t)(((pclk / 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;
}
/**
* @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 */
}
/**
* @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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_smartcard.c
|
C
|
apache-2.0
| 126,167
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 8U
/* UART TX FIFO depth */
#define TX_FIFO_DEPTH 8U
/**
* @}
*/
/* 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_smartcard_ex.c
|
C
|
apache-2.0
| 16,044
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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
* @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;
}
/* Process locked */
__HAL_LOCK(hsmbus);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmbus);
return status;
}
/**
* @brief Unregister an SMBUS Callback
* SMBUS callback is redirected to the weak predefined callback
* @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;
/* Process locked */
__HAL_LOCK(hsmbus);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmbus);
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;
}
/* Process locked */
__HAL_LOCK(hsmbus);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmbus);
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;
/* Process locked */
__HAL_LOCK(hsmbus);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsmbus);
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))
{
/* Check if the Autonomous mode is enabled */
if ((hsmbus->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
{
SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize,
SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE),
SMBUS_GENERATE_NO_START_WRITE);
}
else
{
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 */
/* Check if the Autonomous mode is enabled */
if ((hsmbus->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
{
SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize,
hsmbus->XferOptions,
SMBUS_GENERATE_NO_START_WRITE);
}
else
{
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)
{
hsmbus->XferSize--;
hsmbus->XferCount--;
}
}
/* 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))
{
/* Check if the Autonomous mode is enabled */
if ((hsmbus->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
{
SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize,
SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE),
SMBUS_GENERATE_NO_START_READ);
}
else
{
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 */
/* Check if the Autonomous mode is enabled */
if ((hsmbus->Instance->AUTOCR & I2C_AUTOCR_TRIGEN) == I2C_AUTOCR_TRIGEN)
{
SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize,
hsmbus->XferOptions,
SMBUS_GENERATE_NO_START_READ);
}
else
{
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(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(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);
}
/* 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_smbus.c
|
C
|
apache-2.0
| 98,348
|
/**
******************************************************************************
* @file stm32u5xx_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
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 STM32U5xx
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()
(#) Set or get or clear the autonomous mode configuration using these functions :
(++) HAL_SMBUSEx_SetConfigAutonomousMode()
(++) HAL_SMBUSEx_GetConfigAutonomousMode()
(++) HAL_SMBUSEx_ClearConfigAutonomousMode()
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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;
}
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup SMBUSEx_Exported_Functions_Group4 Autonomous Mode Functions
* @brief Autonomous Mode Functions
*
@verbatim
===============================================================================
##### Autonomous Mode functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure Autonomous Mode
@endverbatim
* @{
*/
/**
* @brief Set Autonomous Mode configuration
* @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains
* the configuration information for the specified SMBUSx peripheral.
* @param sConfig Pointer to a SMBUS_AutonomousModeConfTypeDef structure that contains
* the configuration information of the autonomous mode for the specified SMBUSx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SMBUSEx_SetConfigAutonomousMode(SMBUS_HandleTypeDef *hsmbus,
SMBUS_AutonomousModeConfTypeDef *sConfig)
{
if (hsmbus->State == HAL_SMBUS_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hsmbus);
hsmbus->State = HAL_SMBUS_STATE_BUSY;
/* Check the parameters */
assert_param(IS_SMBUS_TRIG_SOURCE(hsmbus->Instance, sConfig->TriggerSelection));
assert_param(IS_SMBUS_AUTO_MODE_TRG_POL(sConfig->TriggerPolarity));
/* Disable the selected SMBUS peripheral to be able to configure AUTOCR */
__HAL_SMBUS_DISABLE(hsmbus);
/* SMBUSx AUTOCR Configuration */
WRITE_REG(hsmbus->Instance->AUTOCR,
(sConfig->TriggerState | \
((sConfig->TriggerSelection) & I2C_AUTOCR_TRIGSEL_Msk) | \
sConfig->TriggerPolarity));
/* Enable the selected SMBUS peripheral */
__HAL_SMBUS_ENABLE(hsmbus);
hsmbus->State = HAL_SMBUS_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hsmbus);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Get Autonomous Mode configuration
* @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains
* the configuration information for the specified SMBUSx peripheral.
* @param sConfig Pointer to a SMBUS_AutonomousModeConfTypeDef structure that contains
* the configuration information of the autonomous mode for the specified SMBUSx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SMBUSEx_GetConfigAutonomousMode(SMBUS_HandleTypeDef *hsmbus, \
SMBUS_AutonomousModeConfTypeDef *sConfig)
{
uint32_t autocr_tmp;
autocr_tmp = hsmbus->Instance->AUTOCR;
sConfig->TriggerState = (autocr_tmp & I2C_AUTOCR_TRIGEN);
if (IS_SMBUS_GRP2_INSTANCE(hsmbus->Instance))
{
sConfig->TriggerSelection = ((autocr_tmp & I2C_AUTOCR_TRIGSEL) | SMBUS_TRIG_GRP2);
}
else
{
sConfig->TriggerSelection = ((autocr_tmp & I2C_AUTOCR_TRIGSEL) | SMBUS_TRIG_GRP1);
}
sConfig->TriggerPolarity = (autocr_tmp & I2C_AUTOCR_TRIGPOL);
return HAL_OK;
}
/**
* @brief Clear Autonomous Mode configuration
* @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains
* the configuration information for the specified SMBUS peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SMBUSEx_ClearConfigAutonomousMode(SMBUS_HandleTypeDef *hsmbus)
{
if (hsmbus->State == HAL_SMBUS_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hsmbus);
hsmbus->State = HAL_SMBUS_STATE_BUSY;
/* Disable the selected SMBUS peripheral to be able to clear AUTOCR */
__HAL_SMBUS_DISABLE(hsmbus);
CLEAR_REG(hsmbus->Instance->AUTOCR);
/* Enable the selected SMBUS peripheral */
__HAL_SMBUS_ENABLE(hsmbus);
hsmbus->State = HAL_SMBUS_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hsmbus);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_SMBUS_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_smbus_ex.c
|
C
|
apache-2.0
| 10,956
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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
(+) 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
(+) 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.
[..]
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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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(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(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));
/* 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 */
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 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_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_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, 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 = (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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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) = *((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) = *((uint32_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint32_t);
hspi->TxXferCount -= (uint16_t)2UL;
}
else
{
#if defined (__GNUC__)
*ptxdr_16bits = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((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) = *((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 = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((uint16_t *)hspi->pTxBuffPtr);
#endif /* __GNUC__ */
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= (uint16_t)2UL;
}
else
{
*((__IO uint8_t *)&hspi->Instance->TXDR) = *((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, tickstart, Timeout) != 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));
if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES))
{
hspi->State = HAL_SPI_STATE_BUSY_RX;
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout);
}
/* 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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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, tickstart, Timeout) != 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, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size,
uint32_t Timeout)
{
HAL_SPI_StateTypeDef tmp_state;
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;
uint32_t tmp_mode;
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;
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))))
{
errorcode = HAL_BUSY;
__HAL_UNLOCK(hspi);
return errorcode;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL))
{
errorcode = HAL_ERROR;
__HAL_UNLOCK(hspi);
return errorcode;
}
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if (hspi->State != HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Set the transaction information */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pRxBuffPtr = (uint8_t *)pRxData;
hspi->RxXferCount = Size;
hspi->RxXferSize = Size;
hspi->pTxBuffPtr = (uint8_t *)pTxData;
hspi->TxXferCount = Size;
hspi->TxXferSize = Size;
/*Init field not used in handle to zero */
hspi->RxISR = NULL;
hspi->TxISR = NULL;
/* Set the number of data at current transfer */
MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size);
__HAL_SPI_ENABLE(hspi);
if (((hspi->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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) = *((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 = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((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) = *((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, tickstart, Timeout) != 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, 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 = (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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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));
if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
{
hspi->State = HAL_SPI_STATE_BUSY_RX;
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size);
}
/* 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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
{
HAL_SPI_StateTypeDef tmp_state;
HAL_StatusTypeDef errorcode = HAL_OK;
uint32_t max_fifo_length = 0UL;
uint32_t tmp_TxXferCount;
#if defined (__GNUC__)
__IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR));
#endif /* __GNUC__ */
uint32_t tmp_mode;
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Lock the process */
__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))))
{
errorcode = HAL_BUSY;
__HAL_UNLOCK(hspi);
return errorcode;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL))
{
errorcode = HAL_ERROR;
__HAL_UNLOCK(hspi);
return errorcode;
}
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if (hspi->State != HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Set the transaction information */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pTxBuffPtr = (uint8_t *)pTxData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
hspi->pRxBuffPtr = (uint8_t *)pRxData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
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 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))
{
if (max_fifo_length < MAX_FIFO_LENGTH)
{
/* Transmit data in 32 Bit mode */
if (hspi->Init.DataSize > SPI_DATASIZE_16BIT)
{
*((__IO uint32_t *)&hspi->Instance->TXDR) = *((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 ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA))
{
*((__IO uint32_t *)&hspi->Instance->TXDR) = *((uint32_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint32_t);
hspi->TxXferCount -= (uint16_t)2UL;
tmp_TxXferCount = hspi->TxXferCount;
}
else
{
#if defined (__GNUC__)
*ptxdr_16bits = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((uint16_t *)hspi->pTxBuffPtr);
#endif /* __GNUC__ */
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
tmp_TxXferCount = hspi->TxXferCount;
}
}
/* Transmit data in 8 Bit mode */
else
{
if ((hspi->TxXferCount > 3UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_03DATA))
{
*((__IO uint32_t *)&hspi->Instance->TXDR) = *((uint32_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint32_t);
hspi->TxXferCount -= (uint16_t)4UL;
tmp_TxXferCount = hspi->TxXferCount;
}
else if ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA))
{
#if defined (__GNUC__)
*ptxdr_16bits = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((uint16_t *)hspi->pTxBuffPtr);
#endif /* __GNUC__ */
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= (uint16_t)2UL;
tmp_TxXferCount = hspi->TxXferCount;
}
else
{
*((__IO uint8_t *)&hspi->Instance->TXDR) = *((uint8_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint8_t);
hspi->TxXferCount--;
tmp_TxXferCount = hspi->TxXferCount;
}
}
max_fifo_length++;
}
else
{
errorcode = HAL_BUSY;
__HAL_UNLOCK(hspi);
return errorcode;
}
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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, 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 = (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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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));
if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
{
hspi->State = HAL_SPI_STATE_BUSY_RX;
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size);
}
/* 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);
}
/* 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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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, uint8_t *pTxData, uint8_t *pRxData,
uint16_t Size)
{
HAL_SPI_StateTypeDef tmp_state;
HAL_StatusTypeDef errorcode;
uint32_t tmp_mode;
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Lock the process */
__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))))
{
errorcode = HAL_BUSY;
__HAL_UNLOCK(hspi);
return errorcode;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL))
{
errorcode = HAL_ERROR;
__HAL_UNLOCK(hspi);
return errorcode;
}
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if (hspi->State != HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Set the transaction information */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pTxBuffPtr = (uint8_t *)pTxData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
hspi->pRxBuffPtr = (uint8_t *)pRxData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
/* Init field not used in handle to zero */
hspi->RxISR = NULL;
hspi->TxISR = NULL;
/* 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 */
}
/* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */
if (hspi->State == HAL_SPI_STATE_BUSY_RX)
{
/* Set the SPI Rx DMA Half transfer complete callback */
hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt;
hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt;
}
else
{
/* 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->XferErrorCallback = NULL;
hspi->hdmatx->XferAbortCallback = NULL;
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->Instance->AUTOCR & SPI_AUTOCR_TRIGEN) == 0U) && (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))
{
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));
}
/* 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 (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))
{
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));
}
/* 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 (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 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;
}
if (HAL_IS_BIT_SET(itflag, SPI_FLAG_SUSP) && HAL_IS_BIT_SET(itsource, SPI_FLAG_EOT))
{
/* Abort on going, clear SUSP flag to avoid infinite looping */
__HAL_SPI_CLEAR_SUSPFLAG(hspi);
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)
{
/* 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)
{
/* 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)
{
/* 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)
{
/* 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)
{
/* 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)
{
/* 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)
{
/* 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)
{
/* 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.
*/
}
/**
* @}
*/
/** @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(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(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)
{
SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#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)
{
SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#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)
{
SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#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 = *((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 = *((uint16_t *)hspi->pTxBuffPtr);
#else
*((__IO uint16_t *)&hspi->Instance->TXDR) = *((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) = *((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(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status,
uint32_t Tickstart, uint32_t Timeout)
{
/* 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(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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_spi.c
|
C
|
apache-2.0
| 118,027
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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(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;
}
/**
* @brief Set Autonomous Mode configuration
* @param hspi Pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPIx peripheral.
* @param sConfig Pointer to a SPI_HandleTypeDef structure that contains
* the configuration information of the autonomous mode for the specified SPIx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPIEx_SetConfigAutonomousMode(SPI_HandleTypeDef *hspi, SPI_AutonomousModeConfTypeDef *sConfig)
{
if (hspi->State == HAL_SPI_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hspi);
hspi->State = HAL_SPI_STATE_BUSY;
/* Check the parameters */
assert_param(IS_SPI_TRIG_SOURCE(hspi->Instance, sConfig->TriggerSelection));
assert_param(IS_SPI_AUTO_MODE_TRG_POL(sConfig->TriggerPolarity));
/* Disable the selected SPI peripheral to be able to configure AUTOCR */
__HAL_SPI_DISABLE(hspi);
/* SPIx AUTOCR Configuration */
WRITE_REG(hspi->Instance->AUTOCR, (sConfig->TriggerState | ((sConfig->TriggerSelection) & SPI_AUTOCR_TRIGSEL_Msk) |
sConfig->TriggerPolarity));
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Get Autonomous Mode configuration
* @param hspi Pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPIx peripheral.
* @param sConfig Pointer to a SPI_HandleTypeDef structure that contains
* the configuration information of the autonomous mode for the specified SPIx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPIEx_GetConfigAutonomousMode(SPI_HandleTypeDef *hspi, SPI_AutonomousModeConfTypeDef *sConfig)
{
uint32_t autocr_tmp;
autocr_tmp = hspi->Instance->AUTOCR;
sConfig->TriggerState = (autocr_tmp & SPI_AUTOCR_TRIGEN);
if (IS_SPI_GRP2_INSTANCE(hspi->Instance))
{
sConfig->TriggerSelection = ((autocr_tmp & SPI_AUTOCR_TRIGSEL) | SPI_TRIG_GRP2);
}
else
{
sConfig->TriggerSelection = ((autocr_tmp & SPI_AUTOCR_TRIGSEL) | SPI_TRIG_GRP1);
}
sConfig->TriggerPolarity = (autocr_tmp & SPI_AUTOCR_TRIGPOL);
return HAL_OK;
}
/**
* @brief Clear Autonomous Mode configuration
* @param hspi Pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPIx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPIEx_ClearConfigAutonomousMode(SPI_HandleTypeDef *hspi)
{
if (hspi->State == HAL_SPI_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hspi);
hspi->State = HAL_SPI_STATE_BUSY;
/* Disable the selected SPI peripheral to be able to clear AUTOCR */
__HAL_SPI_DISABLE(hspi);
CLEAR_REG(hspi->Instance->AUTOCR);
/* Enable the selected SPI peripheral */
__HAL_SPI_ENABLE(hspi);
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_SPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_spi_ex.c
|
C
|
apache-2.0
| 9,675
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 (surcharged) 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 (surcharged) functions.
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 -----------------------------------------------*/
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 instead of the weak (surcharged) 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;
}
/* Process locked */
__HAL_LOCK(hsram);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsram);
return status;
}
/**
* @brief Unregister a User SRAM Callback
* SRAM Callback is redirected to the weak (surcharged) 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;
/* Process locked */
__HAL_LOCK(hsram);
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;
}
/* Release Lock */
__HAL_UNLOCK(hsram);
return status;
}
/**
* @brief Register a User SRAM Callback for DMA transfers
* To be used instead of the weak (surcharged) 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(SRAM_HandleTypeDef *hsram)
{
return hsram->State;
}
/**
* @}
*/
/**
* @}
*/
/**
* @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 */
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_sram.c
|
C
|
apache-2.0
| 37,276
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup TIM TIM
* @brief TIM HAL module driver
* @{
*/
#ifdef HAL_TIM_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup TIM_Private_Constants
* @{
*/
#define TIMx_AF2_OCRSEL TIM1_AF2_OCRSEL
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup TIM_Private_Functions
* @{
*/
static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
uint32_t TIM_ICFilter);
static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
uint32_t TIM_ICFilter);
static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
uint32_t TIM_ICFilter);
static void TIM_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,
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, 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_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);
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_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 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, uint32_t *pData, uint16_t Length)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(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_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 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_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);
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_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 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, uint32_t *pData, uint16_t Length)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(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_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 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_INSTANCE(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_INSTANCE(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_INSTANCE(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_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 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_INSTANCE(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_INSTANCE(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, 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)
{
/* Capture compare 1 event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET)
{
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
/* Input capture event */
if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
/* Input capture event */
if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
/* Input capture event */
if ((htim->Instance->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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
/* Input capture event */
if ((htim->Instance->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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK2) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET)
{
__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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET)
{
__HAL_TIM_CLEAR_IT(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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_IDX) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_IDX) != RESET)
{
__HAL_TIM_CLEAR_IT(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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_DIR) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_DIR) != RESET)
{
__HAL_TIM_CLEAR_IT(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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_IERR) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_IERR) != RESET)
{
__HAL_TIM_CLEAR_IT(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 (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TERR) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TERR) != RESET)
{
__HAL_TIM_CLEAR_IT(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,
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, 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,
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
* @arg TIM_DMABASE_OR1
* @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, uint32_t *BurstBuffer, uint32_t BurstLength)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t BlockDataLength = 0;
uint32_t data_width;
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
* @arg TIM_DMABASE_OR1
* @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, 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
* @arg TIM_DMABASE_OR1
* @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;
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
* @arg TIM_DMABASE_OR1
* @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,
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_OCCS | TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP));
break;
}
case TIM_CLEARINPUTSOURCE_COMP1:
case TIM_CLEARINPUTSOURCE_COMP2:
{
/* Clear the OCREF clear selection bit */
CLEAR_BIT(htim->Instance->SMCR, TIM_SMCR_OCCS);
/* Clear TIM1_AF2_OCRSEL (reset value) */
MODIFY_REG(htim->Instance->AF2, TIMx_AF2_OCRSEL, sClearInputConfig->ClearInputSource);
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);
/* Set the OCREF clear selection bit */
SET_BIT(htim->Instance->SMCR, TIM_SMCR_OCCS);
/* Clear TIMx_AF2_OCRSEL (reset value) */
CLEAR_BIT(htim->Instance->AF2, TIMx_AF2_OCRSEL);
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, 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_ITR11:
{
/* 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, 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,
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(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;
}
/* Process locked */
__HAL_LOCK(htim);
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;
}
/* Release Lock */
__HAL_UNLOCK(htim);
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;
/* Process locked */
__HAL_LOCK(htim);
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;
}
/* Release Lock */
__HAL_UNLOCK(htim);
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(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(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(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(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(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(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(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(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(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, 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;
}
/**
* @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, TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the Channel 1: Reset the CC1E Bit */
TIMx->CCER &= ~TIM_CCER_CC1E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->CCMR1;
/* Reset the Output Compare Mode Bits */
tmpccmrx &= ~TIM_CCMR1_OC1M;
tmpccmrx &= ~TIM_CCMR1_CC1S;
/* Select the Output Compare Mode */
tmpccmrx |= OC_Config->OCMode;
/* Reset the Output Polarity level */
tmpccer &= ~TIM_CCER_CC1P;
/* Set the Output Compare Polarity */
tmpccer |= OC_Config->OCPolarity;
if (IS_TIM_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, TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the Channel 2: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC2E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->CCMR1;
/* Reset the Output Compare mode and Capture/Compare selection Bits */
tmpccmrx &= ~TIM_CCMR1_OC2M;
tmpccmrx &= ~TIM_CCMR1_CC2S;
/* Select the Output Compare Mode */
tmpccmrx |= (OC_Config->OCMode << 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, TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the Channel 3: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC3E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR2 register value */
tmpccmrx = TIMx->CCMR2;
/* Reset the Output Compare mode and Capture/Compare selection Bits */
tmpccmrx &= ~TIM_CCMR2_OC3M;
tmpccmrx &= ~TIM_CCMR2_CC3S;
/* Select the Output Compare Mode */
tmpccmrx |= OC_Config->OCMode;
/* Reset the Output Polarity level */
tmpccer &= ~TIM_CCER_CC3P;
/* Set the Output Compare Polarity */
tmpccer |= (OC_Config->OCPolarity << 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, TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the Channel 4: Reset the CC4E Bit */
TIMx->CCER &= ~TIM_CCER_CC4E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR2 register value */
tmpccmrx = TIMx->CCMR2;
/* Reset the Output Compare mode and Capture/Compare selection Bits */
tmpccmrx &= ~TIM_CCMR2_OC4M;
tmpccmrx &= ~TIM_CCMR2_CC4S;
/* Select the Output Compare Mode */
tmpccmrx |= (OC_Config->OCMode << 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,
TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the output: Reset the CCxE Bit */
TIMx->CCER &= ~TIM_CCER_CC5E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->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,
TIM_OC_InitTypeDef *OC_Config)
{
uint32_t tmpccmrx;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Disable the output: Reset the CCxE Bit */
TIMx->CCER &= ~TIM_CCER_CC6E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->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,
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_ITR11:
{
/* 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 */
TIMx->CCER &= ~TIM_CCER_CC1E;
tmpccmr1 = TIMx->CCMR1;
tmpccer = TIMx->CCER;
/* Select the Input */
if (IS_TIM_CC2_INSTANCE(TIMx) != RESET)
{
tmpccmr1 &= ~TIM_CCMR1_CC1S;
tmpccmr1 |= TIM_ICSelection;
}
else
{
tmpccmr1 |= TIM_CCMR1_CC1S_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 */
TIMx->CCER &= ~TIM_CCER_CC2E;
tmpccmr1 = TIMx->CCMR1;
tmpccer = TIMx->CCER;
/* 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 */
TIMx->CCER &= ~TIM_CCER_CC2E;
tmpccmr1 = TIMx->CCMR1;
tmpccer = TIMx->CCER;
/* 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 */
TIMx->CCER &= ~TIM_CCER_CC3E;
tmpccmr2 = TIMx->CCMR2;
tmpccer = TIMx->CCER;
/* Select the Input */
tmpccmr2 &= ~TIM_CCMR2_CC3S;
tmpccmr2 |= TIM_ICSelection;
/* Set the filter */
tmpccmr2 &= ~TIM_CCMR2_IC3F;
tmpccmr2 |= ((TIM_ICFilter << 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 */
TIMx->CCER &= ~TIM_CCER_CC4E;
tmpccmr2 = TIMx->CCMR2;
tmpccer = TIMx->CCER;
/* 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_TS_ITR3: Internal Trigger 3
* @arg TIM_TS_TI1F_ED: TI1 Edge Detector
* @arg TIM_TS_TI1FP1: Filtered Timer Input 1
* @arg TIM_TS_TI2FP2: Filtered Timer Input 2
* @arg TIM_TS_ETRF: External Trigger input
* @arg TIM_TS_ITR4: Internal Trigger 4
* @arg TIM_TS_ITR5: Internal Trigger 5
* @arg TIM_TS_ITR6: Internal Trigger 6
* @arg TIM_TS_ITR7: Internal Trigger 7
* @arg TIM_TS_ITR8: Internal Trigger 8
* @arg TIM_TS_ITR11: Internal Trigger 11
* @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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_tim.c
|
C
|
apache-2.0
| 263,136
|
/**
******************************************************************************
* @file stm32u5xx_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)
* + Time OCRef clear configuration
* + Timer remapping capabilities configuration
* + Timer encoder index configuration
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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, 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_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_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE | TIM_CCER_CC4NE)) == (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, 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.
(+) Start the Complementary Input Capture measurement.
(+) Stop the Complementary Input Capture.
(+) Start the Complementary Input Capture and enable interrupts.
(+) Stop the Complementary Input Capture and disable interrupts.
(+) Start the Complementary Input Capture and enable DMA transfers.
(+) Stop the Complementary Input Capture and disable DMA transfers.
(+) Start the Complementary One Pulse generation.
(+) Stop the Complementary One Pulse.
(+) Start the Complementary One Pulse and enable interrupts.
(+) Stop the Complementary One Pulse and disable interrupts.
@endverbatim
* @{
*/
/**
* @brief Starts the PWM signal generation on the complementary output.
* @param htim TIM handle
* @param Channel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @arg TIM_CHANNEL_4: TIM Channel 4 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
{
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_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE | TIM_CCER_CC4NE)) == (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, 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_ITR11: Internal trigger 11 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 ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) ||
(InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) ||
(InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) ||
(InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11))
{
/* 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_ITR11: Internal trigger 11 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 ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) ||
(InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) ||
(InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) ||
(InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11))
{
/* 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_ITR11: Internal trigger 11 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 ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) ||
(InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) ||
(InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) ||
(InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11))
{
/* 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,
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,
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));
/* 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));
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);
}
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));
/* 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);
}
}
/* 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,
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));
if (sBreakInputConfig->Source != TIM_BREAKINPUTSOURCE_MDF1)
{
assert_param(IS_TIM_BREAKINPUTSOURCE_POLARITY(sBreakInputConfig->Polarity));
}
/* Check input state */
__HAL_LOCK(htim);
switch (sBreakInputConfig->Source)
{
case TIM_BREAKINPUTSOURCE_BKIN:
{
bkin_enable_mask = TIM1_AF1_BKINE;
bkin_enable_bitpos = TIM1_AF1_BKINE_Pos;
bkin_polarity_mask = TIM1_AF1_BKINP;
bkin_polarity_bitpos = TIM1_AF1_BKINP_Pos;
break;
}
case TIM_BREAKINPUTSOURCE_COMP1:
{
bkin_enable_mask = TIM1_AF1_BKCMP1E;
bkin_enable_bitpos = TIM1_AF1_BKCMP1E_Pos;
bkin_polarity_mask = TIM1_AF1_BKCMP1P;
bkin_polarity_bitpos = TIM1_AF1_BKCMP1P_Pos;
break;
}
case TIM_BREAKINPUTSOURCE_COMP2:
{
bkin_enable_mask = TIM1_AF1_BKCMP2E;
bkin_enable_bitpos = TIM1_AF1_BKCMP2E_Pos;
bkin_polarity_mask = TIM1_AF1_BKCMP2P;
bkin_polarity_bitpos = TIM1_AF1_BKCMP2P_Pos;
break;
}
case TIM_BREAKINPUTSOURCE_MDF1:
{
bkin_enable_mask = TIM1_AF1_BKDF1BK0E;
bkin_enable_bitpos = TIM1_AF1_BKDF1BK0E_Pos;
/* No polarity bit for MDF. Variable bkin_polarity_mask keeps its default value 0 */
bkin_polarity_mask = 0U;
bkin_polarity_bitpos = 0U;
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_COMP1 TIM1 ETR is connected to COMP1 output
* @arg TIM_TIM1_ETR_COMP2 TIM1 ETR is connected to COMP2 output
* @arg TIM_TIM1_ETR_HSI TIM1 ETR is connected to HSI
* @arg TIM_TIM1_ETR_MSIS TIM1_ETR is connected to MSIS
* @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 (*)
* @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_ADC4_AWD1 TIM1 ETR is connected to ADC4 AWD1
* @arg TIM_TIM1_ETR_ADC4_AWD2 TIM1 ETR is connected to ADC4 AWD2
* @arg TIM_TIM1_ETR_ADC4_AWD3 TIM1 ETR is connected to ADC4 AWD3
* @arg TIM_TIM1_ETR_ADC2_AWD1 TIM1_ETR is connected to ADC2 AWD1 (*)
*
* 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_COMP1 TIM2 ETR is connected to COMP1 output
* @arg TIM_TIM2_ETR_COMP2 TIM2 ETR is connected to COMP2 output
* @arg TIM_TIM2_ETR_MSIK TIM2 ETR is connected to MSIK
* @arg TIM_TIM2_ETR_HSI TIM2 ETR is connected to HSI
* @arg TIM_TIM2_ETR_MSIS TIM2_ETR is connected to MSIS
* @arg TIM_TIM2_ETR_DCMI_VSYNC TIM2_ETR is connected to DCMI VSYNC (*)
* @arg TIM_TIM2_ETR_LTDC_VSYNC TIM2_ETR is connected to LTDC_VSYNC (*)
* @arg TIM_TIM2_ETR_TIM3_ETR TIM2 ETR is connected to TIM3 ETR pin
* @arg TIM_TIM2_ETR_TIM4_ETR TIM2 ETR is connected to TIM4 ETR pin
* @arg TIM_TIM2_ETR_TIM5_ETR TIM2 ETR is connected to TIM5 ETR pin
* @arg TIM_TIM2_ETR_LSE TIM2 ETR is connected to LSE
* @arg TIM_TIM2_ETR_DSI_TE TIM2_ETR is connected to DSI_TE (*)
* @arg TIM_TIM2_ETR_DCMI_HSYNC TIM2_ETR is connected to DCMI HSYNC (*)
* @arg TIM_TIM2_ETR_LTDC_HSYNC TIM2_ETR is connected to LTDC HSYNC (*)
*
* For TIM3, the parameter can take one of the following values:
* @arg TIM_TIM3_ETR_GPIO TIM3 ETR is connected to GPIO
* @arg TIM_TIM3_ETR_COMP1 TIM3 ETR is connected to COMP1 output
* @arg TIM_TIM3_ETR_COMP2 TIM3 ETR is connected to COMP2 output
* @arg TIM_TIM3_ETR_MSIK TIM3 ETR is connected to MSIK
* @arg TIM_TIM3_ETR_HSI TIM3 ETR is connected to HSI
* @arg TIM_TIM3_ETR_MSIS TIM3_ETR is connected to MSIS
* @arg TIM_TIM3_ETR_DCMI_VSYNC TIM3_ETR is connected to DCMI 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 pin
* @arg TIM_TIM3_ETR_TIM4_ETR TIM3 ETR is connected to TIM4 ETR pin
* @arg TIM_TIM3_ETR_DSI_TE TIM2_ETR is connected to DSI_TE (*)
* @arg TIM_TIM3_ETR_ADC1_AWD1 TIM3 ETR is connected to ADC1 AWD1
* @arg TIM_TIM3_ETR_ADC1_AWD2 TIM3 ETR is connected to ADC1 AWD2
* @arg TIM_TIM3_ETR_ADC1_AWD3 TIM3 ETR is connected to ADC1 AWD3
* @arg TIM_TIM3_ETR_DCMI_HSYNC TIM3_ETR is connected to DCMI HSYNC (*)
* @arg TIM_TIM3_ETR_LTDC_HSYNC TIM3_ETR is connected to LTDC HSYNC (*)
*
* 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_COMP1 TIM4 ETR is connected to COMP1 output
* @arg TIM_TIM4_ETR_COMP2 TIM4 ETR is connected to COMP2 output
* @arg TIM_TIM4_ETR_MSIK TIM4 ETR is connected to MSIK
* @arg TIM_TIM4_ETR_HSI TIM4 ETR is connected to HSI
* @arg TIM_TIM4_ETR_MSIS TIM4_ETR is connected to MSIS
* @arg TIM_TIM4_ETR_DCMI_VSYNC TIM4_ETR is connected to DCMI VSYNC (*)
* @arg TIM_TIM4_ETR_LTDC_VSYNC TIM4_ETR is connected to LTDC_VSYNC (*)
* @arg TIM_TIM4_ETR_TIM3_ETR TIM4 ETR is connected to TIM3 ETR pin
* @arg TIM_TIM4_ETR_TIM5_ETR TIM4 ETR is connected to TIM5 ETR pin
* @arg TIM_TIM4_ETR_DSI_TE TIM2_ETR is connected to DSI_TE (*)
* @arg TIM_TIM4_ETR_ADC2_AWD1 TIM4_ETR is connected to ADC2 AWD1 (*)
* @arg TIM_TIM4_ETR_ADC2_AWD2 TIM4_ETR is connected to ADC2 AWD2 (*)
* @arg TIM_TIM4_ETR_ADC2_AWD3 TIM4_ETR is connected to ADC2 AWD3 (*)
* @arg TIM_TIM4_ETR_DCMI_HSYNC TIM4_ETR is connected to DCMI HSYNC (*)
* @arg TIM_TIM4_ETR_LTDC_HSYNC TIM4_ETR is connected to LTDC HSYNC (*)
*
* 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_COMP1 TIM5 ETR is connected to COMP1 output
* @arg TIM_TIM5_ETR_COMP2 TIM5 ETR is connected to COMP2 output
* @arg TIM_TIM5_ETR_MSIK TIM5 ETR is connected to MSIK
* @arg TIM_TIM5_ETR_HSI TIM5 ETR is connected to HSI
* @arg TIM_TIM5_ETR_MSIS TIM5_ETR is connected to MSIS
* @arg TIM_TIM5_ETR_DCMI_VSYNC TIM5_ETR is connected to DCMI 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 pin
* @arg TIM_TIM5_ETR_TIM3_ETR TIM5 ETR is connected to TIM3 ETR pin
* @arg TIM_TIM5_ETR_DSI_TE TIM5_ETR is connected to DSI_TE (*)
* @arg TIM_TIM5_ETR_DCMI_HSYNC TIM5_ETR is connected to DCMI HSYNC (*)
* @arg TIM_TIM5_ETR_LTDC_HSYNC TIM5_ETR is connected to LTDC HSYNC (*)
*
* For TIM8, the parameter can take one of the following values:
* @arg TIM_TIM8_ETR_GPIO TIM8 ETR is connected to GPIO
* @arg TIM_TIM8_ETR_COMP1 TIM8 ETR is connected to COMP1 output
* @arg TIM_TIM8_ETR_COMP2 TIM8 ETR is connected to COMP2 output
* @arg TIM_TIM8_ETR_MSIK TIM8 ETR is connected to MSIK
* @arg TIM_TIM8_ETR_HSI TIM8 ETR is connected to HSI
* @arg TIM_TIM8_ETR_MSIS TIM8_ETR is connected to MSIS
* @arg TIM_TIM8_ETR_ADC2_AWD2 TIM8_ETR is connected to ADC2 AWD2 (*)
* @arg TIM_TIM8_ETR_ADC2_AWD3 TIM8_ETR is connected to ADC2 AWD3 (*)
* @arg TIM_TIM8_ETR_ADC1_AWD1 TIM8 ETR is connected to ADC1 AWD1
* @arg TIM_TIM8_ETR_ADC1_AWD2 TIM8 ETR is connected to ADC1 AWD2
* @arg TIM_TIM8_ETR_ADC1_AWD3 TIM8 ETR is connected to ADC1 AWD3
* @arg TIM_TIM8_ETR_ADC4_AWD1 TIM8 ETR is connected to ADC4 AWD1
* @arg TIM_TIM8_ETR_ADC4_AWD2 TIM8 ETR is connected to ADC4 AWD2
* @arg TIM_TIM8_ETR_ADC4_AWD3 TIM8 ETR is connected to ADC4 AWD3
* @arg TIM_TIM8_ETR_ADC2_AWD1 TIM8_ETR is connected to ADC2 AWD1 (*)
*
* (*) Value not defined in all devices.
*
* @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(Remap));
__HAL_LOCK(htim);
MODIFY_REG(htim->Instance->AF1, TIM1_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
* @arg TIM_CHANNEL_4: TIM Channel 4
* @param TISelection parameter of the TIM_TISelectionStruct structure is detailed as follows:
* For TIM1, the parameter is one of the following values:
* @arg TIM_TIM1_TI1_GPIO: TIM1 TI1 is connected to GPIO
* @arg TIM_TIM1_TI1_COMP1: TIM1 TI1 is connected to COMP1 output
* @arg TIM_TIM1_TI1_COMP2: TIM1 TI1 is connected to COMP2 output
*
* 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_COMP1: TIM2 TI1 is connected to COMP1 output
* @arg TIM_TIM2_TI1_COMP2: TIM2 TI1 is connected to COMP1 output
* @arg TIM_TIM2_TI2_GPIO: TIM2 TI2 is connected to GPIO
* @arg TIM_TIM2_TI2_COMP1: TIM2 TI2 is connected to COMP1 output
* @arg TIM_TIM2_TI2_COMP2: TIM2 TI2 is connected to COMP1 output
* @arg TIM_TIM2_TI4_GPIO: TIM2 TI4 is connected to GPIO
* @arg TIM_TIM2_TI4_COMP1: TIM2 TI4 is connected to COMP1 output
* @arg TIM_TIM2_TI4_COMP2: TIM2 TI4 is connected to COMP2 output
*
* 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_COMP1: TIM3 TI1 is connected to COMP1 output
* @arg TIM_TIM3_TI1_COMP2: TIM3 TI1 is connected to COMP2 output
* @arg TIM_TIM3_TI2_GPIO: TIM3 TI2 is connected to GPIO
* @arg TIM_TIM3_TI2_COMP1: TIM3 TI2 is connected to COMP1 output
* @arg TIM_TIM3_TI2_COMP2: TIM3 TI2 is connected to COMP1 output
*
* For TIM4, the parameter is one of the following values:
* @arg TIM_TIM4_TI1_GPIO: TIM4 TI1 is connected to GPIO
* @arg TIM_TIM4_TI1_COMP1: TIM4 TI1 is connected to COMP1 output
* @arg TIM_TIM4_TI1_COMP2: TIM4 TI1 is connected to COMP2 output
* @arg TIM_TIM4_TI2_GPIO: TIM4 TI2 is connected to GPIO
* @arg TIM_TIM4_TI2_COMP1: TIM4 TI2 is connected to COMP1 output
* @arg TIM_TIM4_TI2_COMP2: TIM4 TI2 is connected to COMP2 output
*
* For TIM5, the parameter is one of the following values:
* @arg TIM_TIM5_TI1_GPIO: TIM5 TI1 is connected to GPIO
* @arg TIM_TIM5_TI1_LSI: TIM5 TI1 is connected to LSI
* @arg TIM_TIM5_TI1_LSE: TIM5 TI1 is connected to LSE
* @arg TIM_TIM5_TI1_RTC_WKUP: TIM5 TI1 is connected to RTC wakeup interrupt
* @arg TIM_TIM5_TI1_COMP1: TIM5 TI1 is connected to COMP1 output
* @arg TIM_TIM5_TI1_COMP2: TIM5 TI1 is connected to COMP2 output
* @arg TIM_TIM5_TI2_GPIO: TIM5 TI2 is connected to GPIO
* @arg TIM_TIM5_TI2_COMP1: TIM5 TI2 is connected to COMP1 output
* @arg TIM_TIM5_TI2_COMP2: TIM5 TI2 is connected to COMP2 output
*
* For TIM8, the parameter is one of the following values:
* @arg TIM_TIM8_TI1_GPIO: TIM8 TI1 is connected to GPIO
* @arg TIM_TIM8_TI1_COMP1: TIM8 TI1 is connected to COMP1 output
* @arg TIM_TIM8_TI1_COMP2: TIM8 TI1 is connected to COMP2 output
*
* 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_LSE: TIM15 TI1 is connected to LSE
* @arg TIM_TIM15_TI1_COMP1: TIM8 TI1 is connected to COMP1 output
* @arg TIM_TIM15_TI1_COMP2: TIM8 TI1 is connected to COMP2 output
* @arg TIM_TIM15_TI2_GPIO: TIM15 TI2 is connected to GPIO
* @arg TIM_TIM15_TI2_TIM2: TIM15 TI2 is connected to TIM2 CH2
* @arg TIM_TIM15_TI2_TIM3: TIM15 TI2 is connected to TIM3 CH2
* @arg TIM_TIM15_TI2_COMP2: TIM8 TI1 is connected to COMP2 output
*
* For TIM16, the parameter can have the following values:
* @arg TIM_TIM16_TI1_GPIO: TIM16 TI1 is connected to GPIO
* @arg TIM_TIM16_TI1_MCO: TIM16 TI1 is connected to MCO
* @arg TIM_TIM16_TI1_LSI: TIM16 TI1 is connected to LSI
* @arg TIM_TIM16_TI1_LSE: TIM16 TI1 is connected to LSE
* @arg TIM_TIM16_TI1_RTC_WKUP: TIM16 TI1 is connected to RTC wakeup interrupt
* @arg TIM_TIM16_TI1_HSE_DIV32: TIM16 TI1 is connected to HSE/32
* @arg TIM_TIM16_TI1_MSIS_1024: TIM16 TI1 is connected to MSIS/1024
* @arg TIM_TIM16_TI1_MSIS_4: TIM16 TI1 is connected to MSIS/4
* @arg TIM_TIM16_TI1_HSI_256: TIM16 TI1 is connected to HSI/256
*
* For TIM17, the parameter can have the following values:
* @arg TIM_TIM17_TI1_GPIO: TIM17 TI1 is connected to GPIO
* @arg TIM_TIM17_TI1_MCO: TIM17 TI1 is connected to MCO
* @arg TIM_TIM17_TI1_LSI: TIM17 TI1 is connected to LSI
* @arg TIM_TIM17_TI1_LSE: TIM17 TI1 is connected to LSE
* @arg TIM_TIM17_TI1_RTC_WKUP: TIM17 TI1 is connected to RTC wakeup interrupt
* @arg TIM_TIM17_TI1_HSE_DIV32: TIM17 TI1 is connected to HSE/32
* @arg TIM_TIM17_TI1_MSIS_1024: TIM17 TI1 is connected to MSIS/024
* @arg TIM_TIM17_TI1_MSIS_4: TIM17 TI1 is connected to MSIS/4
* @arg TIM_TIM17_TI1_HSI_256: TIM17 TI1 is connected to HSI/256
*
* (*) Value not defined in all devices. \n
* @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_INSTANCE(htim->Instance));
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;
case TIM_CHANNEL_4:
MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI4SEL, 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_ADVANCED_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(TIM_HandleTypeDef *htim, uint32_t BreakInput)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tickstart;
/* Check the parameters */
assert_param(IS_TIM_ADVANCED_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 */
#if defined (STM32U575xx) || defined (STM32U585xx)
if (HAL_GetREVID() >= REV_ID_B) /* supported in cut2 */
{
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));
}
else
{
MODIFY_REG(htim->Instance->ECR,
TIM_ECR_IDIR_Msk | TIM_ECR_FIDX_Msk | TIM_ECR_IPOS_Msk,
(sEncoderIndexConfig->Direction |
((sEncoderIndexConfig->FirstIndexEnable == ENABLE) ? (0x1U << TIM_ECR_FIDX_Pos) : 0U) |
sEncoderIndexConfig->Position |
TIM_ECR_IE));
}
#else
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));
#endif /* STM32U575xx || STM32U585xx */
__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 Hall commutation changed 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 Hall commutation changed 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 Hall 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 Hall 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(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(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
{
/* 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 & 0x1FU); /* 0x1FU = 31 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 */
}
/**
* @brief Enable HSE/32 .
* @note This function should be called to enable the HSE/32 when it is selected as TIM17_TI1 or TIM16_TI1 input
* source.
* @param htim TIM handle.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_TIMEx_EnableHSE32(TIM_HandleTypeDef *htim)
{
/* Check the parameters */
assert_param(IS_TIM_HSE32_INSTANCE(htim->Instance));
#if defined (STM32U575xx) || defined (STM32U585xx)
/* The Cut1.x contains a limitation when using HSE/32 as input capture for TIM16
Bug ID 56: On TIM16, the HSE/32 input capture requires the set of HSE32EN bit of TIM17 Option Register */
if (HAL_GetREVID() < REV_ID_B) /* Cut1.x */
{
__HAL_RCC_TIM17_CLK_ENABLE();
SET_BIT(TIM17->OR1, TIM_OR1_HSE32EN);
}
else
{
SET_BIT(htim->Instance->OR1, TIM_OR1_HSE32EN);
}
#else
SET_BIT(htim->Instance->OR1, TIM_OR1_HSE32EN);
#endif /* STM32U575xx || STM32U585xx */
return HAL_OK;
}
/**
* @brief Disable HSE/32 .
* @note This function should be called to Disable the HSE/32 .
* @param htim TIM handle.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_TIMEx_DisableHSE32(TIM_HandleTypeDef *htim)
{
/* Check the parameters */
assert_param(IS_TIM_HSE32_INSTANCE(htim->Instance));
#if defined (STM32U575xx) || defined (STM32U585xx)
if (HAL_GetREVID() < REV_ID_B) /* Cut1.x */
{
__HAL_RCC_TIM17_CLK_ENABLE();
CLEAR_BIT(TIM17->OR1, TIM_OR1_HSE32EN);
}
else
{
CLEAR_BIT(htim->Instance->OR1, TIM_OR1_HSE32EN);
}
#else
CLEAR_BIT(htim->Instance->OR1, TIM_OR1_HSE32EN);
#endif /* STM32U575xx || STM32U585xx */
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_TIM_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_tim_ex.c
|
C
|
apache-2.0
| 128,377
|
/**
******************************************************************************
* @file stm32u5xx_hal_timebase_rtc_alarm_template.c
* @author MCD Application Team
* @brief HAL time base based on the hardware RTC_ALARM Template.
*
* This file overrides the native HAL time base functions (defined as weak)
* to use the RTC ALARM for time base generation:
* + Initializes the RTC peripheral to increment the seconds registers each 1ms
* + The alarm is configured to assert an interrupt when the RTC reaches 1ms
* + HAL_IncTick is called at each Alarm event
* + HSE (default), LSE or LSI can be selected as RTC clock source
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 file must be copied to the application folder and modified as follows:
(#) Rename it to 'stm32u5xx_hal_timebase_rtc_alarm.c'
(#) Add this file and the RTC HAL drivers to your project and uncomment
HAL_RTC_MODULE_ENABLED define in stm32u5xx_hal_conf.h
[..]
(@) HAL RTC alarm and HAL RTC wakeup drivers can not be used with low power modes:
The wake up capability of the RTC may be intrusive in case of prior low power mode
configuration requiring different wake up sources.
Application/Example behavior is no more guaranteed
(@) The stm32u5xx_hal_timebase_tim use is recommended for the Applications/Examples
requiring low power modes
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup HAL_TimeBase_RTC_Alarm_Template HAL TimeBase RTC Alarm Template
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Uncomment the line below to select the appropriate RTC Clock source for your application:
+ RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
+ RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
precision.
+ RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
precision.
*/
/* #define RTC_CLOCK_SOURCE_HSE */
/* #define RTC_CLOCK_SOURCE_LSE */
#define RTC_CLOCK_SOURCE_LSI
/* The time base should be 1ms
Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
*/
#if defined (RTC_CLOCK_SOURCE_HSE)
#define RTC_ASYNCH_PREDIV 99U
#define RTC_SYNCH_PREDIV 4U
#elif defined (RTC_CLOCK_SOURCE_LSE)
#define RTC_ASYNCH_PREDIV 0U
#define RTC_SYNCH_PREDIV 32U
#elif defined (RTC_CLOCK_SOURCE_LSI)
#define RTC_ASYNCH_PREDIV 0U
#define RTC_SYNCH_PREDIV 31U
#else
#error Please select the RTC Clock source
#endif /* RTC_CLOCK_SOURCE_LSE */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static RTC_HandleTypeDef hRTC_Handle;
/* Private function prototypes -----------------------------------------------*/
void RTC_IRQHandler(void);
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
void TimeBase_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Private functions ---------------------------------------------------------*/
/**
* @brief This function configures the RTC_ALARMA as a time base source.
* The time source is configured to have 1ms time base with a dedicated
* Tick interrupt priority.
* @note This function is called automatically at the beginning of program after
* reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
* @param TickPriority Tick interrupt priority.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
HAL_StatusTypeDef Status;
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;
/* Disable bkup domain protection */
__HAL_RCC_PWR_CLK_ENABLE();
HAL_PWR_EnableBkUpAccess();
/* Force and Release the Backup domain reset */
__HAL_RCC_BACKUPRESET_FORCE();
__HAL_RCC_BACKUPRESET_RELEASE();
/* Enable RTC Clock */
__HAL_RCC_RTC_ENABLE();
__HAL_RCC_RTCAPB_CLK_ENABLE();
#if defined (RTC_CLOCK_SOURCE_LSE)
/* Configure LSE as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.LSEState = RCC_LSE_ON_RTC_ONLY;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
#elif defined (RTC_CLOCK_SOURCE_LSI)
/* Configure LSI as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.LSIDiv = RCC_LSI_DIV1;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
#elif defined (RTC_CLOCK_SOURCE_HSE)
/* Configure HSE as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
#else
#error Please select the RTC Clock source
#endif /* RTC_CLOCK_SOURCE_LSE */
Status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
if (Status == HAL_OK)
{
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
Status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
}
if (Status == HAL_OK)
{
hRTC_Handle.Instance = RTC;
hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
hRTC_Handle.Init.BinMode = RTC_BINARY_NONE;
Status = HAL_RTC_Init(&hRTC_Handle);
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
HAL_RTC_RegisterCallback(&hRTC_Handle, HAL_RTC_ALARM_A_EVENT_CB_ID, TimeBase_RTC_AlarmAEventCallback);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
if (Status == HAL_OK)
{
/* RTC variables */
RTC_AlarmTypeDef RTC_AlarmStructure;
/* RTC Alarm Generation */
RTC_AlarmStructure.Alarm = RTC_ALARM_A;
RTC_AlarmStructure.AlarmDateWeekDay = RTC_WEEKDAY_MONDAY;
RTC_AlarmStructure.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
/* Mask all and keep only subsecond, to have one match in each time base 1ms(uwTickFreq) */
RTC_AlarmStructure.AlarmMask = RTC_ALARMMASK_ALL;
RTC_AlarmStructure.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_NONE;
RTC_AlarmStructure.AlarmTime.TimeFormat = RTC_HOURFORMAT_24;
RTC_AlarmStructure.AlarmTime.Hours = 0;
RTC_AlarmStructure.AlarmTime.Minutes = 0;
RTC_AlarmStructure.AlarmTime.Seconds = 0;
RTC_AlarmStructure.AlarmTime.SubSeconds = 0;
/* Set the specified RTC Alarm with Interrupt */
Status = HAL_RTC_SetAlarm_IT(&hRTC_Handle, &RTC_AlarmStructure, RTC_FORMAT_BCD);
}
if (TickPriority < (1UL << __NVIC_PRIO_BITS))
{
/* Enable the RTC global Interrupt */
HAL_NVIC_SetPriority(RTC_IRQn, TickPriority, 0);
uwTickPrio = TickPriority;
}
else
{
Status = HAL_ERROR;
}
HAL_NVIC_EnableIRQ(RTC_IRQn);
return Status;
}
/**
* @brief Suspend Tick increment.
* @note Disable the tick increment by disabling RTC ALARM interrupt.
* @retval None
*/
void HAL_SuspendTick(void)
{
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
/* Disable RTC ALARM update Interrupt */
__HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}
/**
* @brief Resume Tick increment.
* @note Enable the tick increment by Enabling RTC ALARM interrupt.
* @retval None
*/
void HAL_ResumeTick(void)
{
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
/* Enable RTC ALARM Update interrupt */
__HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}
/**
* @brief ALARM A Event Callback in non blocking mode
* @note This function is called when RTC_ALARM interrupt took place, inside
* RTC_ALARM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
* a global variable "uwTick" used as application time base.
* @param hrtc RTC handle
* @retval None
*/
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
void TimeBase_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
#else
void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
HAL_IncTick();
}
/**
* @brief This function handles RTC ALARM interrupt request.
* @retval None
*/
void RTC_IRQHandler(void)
{
HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
}
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_timebase_rtc_alarm_template.c
|
C
|
apache-2.0
| 10,241
|
/**
******************************************************************************
* @file stm32u5xx_hal_timebase_rtc_wakeup_template.c
* @author MCD Application Team
* @brief HAL time base based on the hardware RTC_WAKEUP Template.
*
* This file overrides the native HAL time base functions (defined as weak)
* to use the RTC WAKEUP for the time base generation:
* + Initializes the RTC peripheral and configures the wakeup timer to be
* incremented each 1ms
* + The wakeup feature is configured to assert an interrupt each 1ms
* + HAL_IncTick is called inside the HAL_RTCEx_WakeUpTimerEventCallback
* + HSE (default), LSE or LSI can be selected as RTC clock source
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 file must be copied to the application folder and modified as follows:
(#) Rename it to 'stm32u5xx_hal_timebase_rtc_wakeup.c'
(#) Add this file and the RTC HAL drivers to your project and uncomment
HAL_RTC_MODULE_ENABLED define in stm32u5xx_hal_conf.h
[..]
(@) HAL RTC alarm and HAL RTC wakeup drivers can not be used with low power modes:
The wake up capability of the RTC may be intrusive in case of prior low power mode
configuration requiring different wake up sources.
Application/Example behavior is no more guaranteed
(@) The stm32u5xx_hal_timebase_tim use is recommended for the Applications/Examples
requiring low power modes
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup HAL_TimeBase_RTC_Alarm_Template HAL TimeBase RTC Alarm Template
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Uncomment the line below to select the appropriate RTC Clock source for your application:
+ RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
+ RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
precision.
+ RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
precision.
*/
/* #define RTC_CLOCK_SOURCE_HSE */
/* #define RTC_CLOCK_SOURCE_LSE */
#define RTC_CLOCK_SOURCE_LSI
/* The time base should be 1ms
Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
*/
#if defined (RTC_CLOCK_SOURCE_HSE)
#define RTC_ASYNCH_PREDIV 99U
#define RTC_SYNCH_PREDIV 4U
#elif defined (RTC_CLOCK_SOURCE_LSE)
#define RTC_ASYNCH_PREDIV 0U
#define RTC_SYNCH_PREDIV 32U
#elif defined (RTC_CLOCK_SOURCE_LSI)
#define RTC_ASYNCH_PREDIV 0U
#define RTC_SYNCH_PREDIV 31U
#else
#error Please select the RTC Clock source
#endif /* RTC_CLOCK_SOURCE_LSE */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static RTC_HandleTypeDef hRTC_Handle;
/* Private function prototypes -----------------------------------------------*/
void RTC_IRQHandler(void);
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
void TimeBase_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* Private functions ---------------------------------------------------------*/
/**
* @brief This function configures the RTC_ALARMA as a time base source.
* The time source is configured to have 1ms time base with a dedicated
* Tick interrupt priority.
* @note This function is called automatically at the beginning of program after
* reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
* @param TickPriority Tick interrupt priority.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
HAL_StatusTypeDef Status;
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;
/* Disable bkup domain protection */
__HAL_RCC_PWR_CLK_ENABLE();
HAL_PWR_EnableBkUpAccess();
/* Force and Release the Backup domain reset */
__HAL_RCC_BACKUPRESET_FORCE();
__HAL_RCC_BACKUPRESET_RELEASE();
/* Enable RTC Clock */
__HAL_RCC_RTC_ENABLE();
__HAL_RCC_RTCAPB_CLK_ENABLE();
#if defined (RTC_CLOCK_SOURCE_LSE)
/* Configure LSE as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.LSEState = RCC_LSE_RTC_ONLY;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
#elif defined (RTC_CLOCK_SOURCE_LSI)
/* Configure LSI as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.LSIDiv = RCC_LSI_DIV1;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
#elif defined (RTC_CLOCK_SOURCE_HSE)
/* Configure HSE as RTC clock source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
#else
#error Please select the RTC Clock source
#endif /* RTC_CLOCK_SOURCE_LSE */
Status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
if (Status == HAL_OK)
{
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
Status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
}
if (Status == HAL_OK)
{
hRTC_Handle.Instance = RTC;
hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
hRTC_Handle.Init.BinMode = RTC_BINARY_NONE;
Status = HAL_RTC_Init(&hRTC_Handle);
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
HAL_RTC_RegisterCallback(&hRTC_Handle, HAL_RTC_WAKEUPTIMER_EVENT_CB_ID, TimeBase_RTCEx_WakeUpTimerEventCallback);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
if (Status == HAL_OK)
{
Status = HAL_RTCEx_SetWakeUpTimer_IT(&hRTC_Handle, 0, RTC_WAKEUPCLOCK_CK_SPRE_16BITS, 0);
}
if (TickPriority < (1UL << __NVIC_PRIO_BITS))
{
/* Enable the RTC global Interrupt */
HAL_NVIC_SetPriority(RTC_IRQn, TickPriority, 0U);
uwTickPrio = TickPriority;
}
else
{
Status = HAL_ERROR;
}
HAL_NVIC_EnableIRQ(RTC_IRQn);
return Status;
}
/**
* @brief Suspend Tick increment.
* @note Disable the tick increment by disabling RTC_WKUP interrupt.
* @retval None
*/
void HAL_SuspendTick(void)
{
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
/* Disable WAKE UP TIMER Interrupt */
__HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}
/**
* @brief Resume Tick increment.
* @note Enable the tick increment by Enabling RTC_WKUP interrupt.
* @retval None
*/
void HAL_ResumeTick(void)
{
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
/* Enable WAKE UP TIMER interrupt */
__HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}
/**
* @brief Wake Up Timer Event Callback in non blocking mode
* @note This function is called when RTC_WKUP interrupt took place, inside
* RTC_WKUP_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
* a global variable "uwTick" used as application time base.
* @param hrtc RTC handle
* @retval None
*/
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
void TimeBase_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
#else
void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
HAL_IncTick();
}
/**
* @brief This function handles WAKE UP TIMER interrupt request.
* @retval None
*/
void RTC_IRQHandler(void)
{
HAL_RTCEx_WakeUpTimerIRQHandler(&hRTC_Handle);
}
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_timebase_rtc_wakeup_template.c
|
C
|
apache-2.0
| 9,511
|
/**
******************************************************************************
* @file stm32u5xx_hal_timebase_tim_template.c
* @author MCD Application Team
* @brief HAL time base based on the hardware TIM.
*
* This file overrides the native HAL time base functions (defined as weak)
* the TIM time base:
* + Initializes the TIM peripheral to generate a Period elapsed Event each 1ms
* + HAL_IncTick is called inside HAL_TIM_PeriodElapsedCallback ie each 1ms
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 file must be copied to the application folder and modified as follows:
(#) Rename it to 'stm32u5xx_hal_timebase_tim.c'
(#) Add this file and the TIM HAL drivers to your project and uncomment
HAL_TIM_MODULE_ENABLED define in stm32u5xx_hal_conf.h
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @addtogroup HAL_TimeBase
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static TIM_HandleTypeDef TimHandle;
/* Private function prototypes -----------------------------------------------*/
void TIM6_IRQHandler(void);
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1U)
void TimeBase_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
/* Private functions ---------------------------------------------------------*/
/**
* @brief This function configures the TIM6 as a time base source.
* The time source is configured to have 1ms time base with a dedicated
* Tick interrupt priority.
* @note This function is called automatically at the beginning of program after
* reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
* @param TickPriority Tick interrupt priority.
* @retval HAL Status
*/
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
RCC_ClkInitTypeDef clkconfig;
uint32_t uwTimclock;
uint32_t uwAPB1Prescaler;
uint32_t uwPrescalerValue;
uint32_t pFLatency;
HAL_StatusTypeDef Status;
/* Enable TIM6 clock */
__HAL_RCC_TIM6_CLK_ENABLE();
/* Get clock configuration */
HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);
/* Get APB1 prescaler */
uwAPB1Prescaler = clkconfig.APB1CLKDivider;
/* Compute TIM6 clock */
if (uwAPB1Prescaler == RCC_HCLK_DIV1)
{
uwTimclock = HAL_RCC_GetPCLK1Freq();
}
else
{
uwTimclock = 2UL * HAL_RCC_GetPCLK1Freq();
}
/* Compute the prescaler value to have TIM6 counter clock equal to 100KHz */
uwPrescalerValue = (uint32_t)((uwTimclock / 100000U) - 1U);
/* Initialize TIM6 */
TimHandle.Instance = TIM6;
/* Initialize TIMx peripheral as follow:
+ Period = [(TIM6CLK/1000) - 1]. to have a (1/1000) s time base.
+ Prescaler = (uwTimclock/100000 - 1) to have a 100KHz counter clock.
+ ClockDivision = 0
+ Counter direction = Up
*/
TimHandle.Init.Period = (1000000U / 1000U) - 1U;
TimHandle.Init.Prescaler = uwPrescalerValue;
TimHandle.Init.ClockDivision = 0;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
Status = HAL_TIM_Base_Init(&TimHandle);
if (Status == HAL_OK)
{
/* Start the TIM time Base generation in interrupt mode */
Status = HAL_TIM_Base_Start_IT(&TimHandle);
if (Status == HAL_OK)
{
if (TickPriority < (1UL << __NVIC_PRIO_BITS))
{
/* Enable the TIM6 global Interrupt */
HAL_NVIC_SetPriority(TIM6_IRQn, TickPriority, 0);
uwTickPrio = TickPriority;
}
else
{
Status = HAL_ERROR;
}
}
}
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1U)
HAL_TIM_RegisterCallback(&TimHandle, HAL_TIM_PERIOD_ELAPSED_CB_ID, TimeBase_TIM_PeriodElapsedCallback);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
HAL_NVIC_EnableIRQ(TIM6_IRQn);
/* Return function Status */
return Status;
}
/**
* @brief Suspend Tick increment.
* @note Disable the tick increment by disabling TIM6 update interrupt.
* @param None
* @retval None
*/
void HAL_SuspendTick(void)
{
/* Disable TIM6 update Interrupt */
__HAL_TIM_DISABLE_IT(&TimHandle, TIM_IT_UPDATE);
}
/**
* @brief Resume Tick increment.
* @note Enable the tick increment by Enabling TIM6 update interrupt.
* @param None
* @retval None
*/
void HAL_ResumeTick(void)
{
/* Enable TIM6 Update interrupt */
__HAL_TIM_ENABLE_IT(&TimHandle, TIM_IT_UPDATE);
}
/**
* @brief Period elapsed callback in non blocking mode
* @note This function is called when TIM6 interrupt took place, inside
* HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
* a global variable "uwTick" used as application time base.
* @param htim TIM handle
* @retval None
*/
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1U)
void TimeBase_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
#else
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
HAL_IncTick();
}
/**
* @brief This function handles TIM interrupt request.
* @param None
* @retval None
*/
void TIM6_IRQHandler(void)
{
HAL_TIM_IRQHandler(&TimHandle);
}
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_timebase_tim_template.c
|
C
|
apache-2.0
| 6,407
|
/**
******************************************************************************
* @file stm32u5xx_hal_tsc.c
* @author MCD Application Team
* @brief This file provides firmware functions to manage the following
* functionalities of the Touch Sensing Controller (TSC) peripheral:
* + Initialization and De-initialization
* + Channel IOs, Shield IOs and Sampling IOs configuration
* + Start and Stop an acquisition
* + Read acquisition result
* + Interrupts and flags management
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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
================================================================================
##### TSC specific features #####
================================================================================
[..]
(#) Proven and robust surface charge transfer acquisition principle
(#) Supports up to 3 capacitive sensing channels per group
(#) Capacitive sensing channels can be acquired in parallel offering a very good
response time
(#) Spread spectrum feature to improve system robustness in noisy environments
(#) Full hardware management of the charge transfer acquisition sequence
(#) Programmable charge transfer frequency
(#) Programmable sampling capacitor I/O pin
(#) Programmable channel I/O pin
(#) Programmable max count value to avoid long acquisition when a channel is faulty
(#) Dedicated end of acquisition and max count error flags with interrupt capability
(#) One sampling capacitor for up to 3 capacitive sensing channels to reduce the system
components
(#) Compatible with proximity, touchkey, linear and rotary touch sensor implementation
##### How to use this driver #####
================================================================================
[..]
(#) Enable the TSC interface clock using __HAL_RCC_TSC_CLK_ENABLE() macro.
(#) GPIO pins configuration
(++) Enable the clock for the TSC GPIOs using __HAL_RCC_GPIOx_CLK_ENABLE() macro.
(++) Configure the TSC pins used as sampling IOs in alternate function output Open-Drain mode,
and TSC pins used as channel/shield IOs in alternate function output Push-Pull mode
using HAL_GPIO_Init() function.
(#) Interrupts configuration
(++) Configure the NVIC (if the interrupt model is used) using HAL_NVIC_SetPriority()
and HAL_NVIC_EnableIRQ() and function.
(#) TSC configuration
(++) Configure all TSC parameters and used TSC IOs using HAL_TSC_Init() function.
[..] TSC peripheral alternate functions are mapped on AF9.
*** Acquisition sequence ***
===================================
[..]
(+) Discharge all IOs using HAL_TSC_IODischarge() function.
(+) Wait a certain time allowing a good discharge of all capacitors. This delay depends
of the sampling capacitor and electrodes design.
(+) Select the channel IOs to be acquired using HAL_TSC_IOConfig() function.
(+) Launch the acquisition using either HAL_TSC_Start() or HAL_TSC_Start_IT() function.
If the synchronized mode is selected, the acquisition will start as soon as the signal
is received on the synchro pin.
(+) Wait the end of acquisition using either HAL_TSC_PollForAcquisition() or
HAL_TSC_GetState() function or using WFI instruction for example.
(+) Check the group acquisition status using HAL_TSC_GroupGetStatus() function.
(+) Read the acquisition value using HAL_TSC_GroupGetValue() function.
*** Callback registration ***
=============================================
[..]
The compilation flag USE_HAL_TSC_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions @ref HAL_TSC_RegisterCallback() to register an interrupt callback.
[..]
Function @ref HAL_TSC_RegisterCallback() allows to register following callbacks:
(+) ConvCpltCallback : callback for conversion complete process.
(+) 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 @ref HAL_TSC_UnRegisterCallback to reset a callback to the default
weak function.
@ref HAL_TSC_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
[..]
This function allows to reset following callbacks:
(+) ConvCpltCallback : callback for conversion complete process.
(+) ErrorCallback : callback for error detection.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
[..]
By default, after the @ref HAL_TSC_Init() and when the state is @ref HAL_TSC_STATE_RESET
all callbacks are set to the corresponding weak functions:
examples @ref HAL_TSC_ConvCpltCallback(), @ref HAL_TSC_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the @ref HAL_TSC_Init()/ @ref HAL_TSC_DeInit() only when
these callbacks are null (not registered beforehand).
If MspInit or MspDeInit are not null, the @ref HAL_TSC_Init()/ @ref HAL_TSC_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in @ref HAL_TSC_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in @ref HAL_TSC_STATE_READY or @ref HAL_TSC_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_TSC_RegisterCallback() before calling @ref HAL_TSC_DeInit()
or @ref HAL_TSC_Init() function.
[..]
When the compilation flag USE_HAL_TSC_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
******************************************************************************
Table 1. IOs for the STM32U5xx devices
+--------------------------------+
| IOs | TSC functions |
|--------------|-----------------|
| PB12 (AF9) | TSC_G1_IO1 |
| PB13 (AF9) | TSC_G1_IO2 |
| PB14 (AF9) | TSC_G1_IO3 |
| PC3 (AF9) | TSC_G1_IO4 |
|--------------|-----------------|
| PB4 (AF9) | TSC_G2_IO1 |
| PB5 (AF9) | TSC_G2_IO2 |
| PB6 (AF9) | TSC_G2_IO3 |
| PB7 (AF9) | TSC_G2_IO4 |
|--------------|-----------------|
| PC2 (AF9) | TSC_G3_IO1 |
| PC10 (AF9) | TSC_G3_IO2 |
| PC11 (AF9) | TSC_G3_IO3 |
| PC12 (AF9) | TSC_G3_IO4 |
|--------------|-----------------|
| PC6 (AF9) | TSC_G4_IO1 |
| PC7 (AF9) | TSC_G4_IO2 |
| PC8 (AF9) | TSC_G4_IO3 |
| PC9 (AF9) | TSC_G4_IO4 |
|--------------|-----------------|
| PE10 (AF9) | TSC_G5_IO1 |
| PE11 (AF9) | TSC_G5_IO2 |
| PE12 (AF9) | TSC_G5_IO3 |
| PE13 (AF9) | TSC_G5_IO4 |
|--------------|-----------------|
| PD10 (AF9) | TSC_G6_IO1 |
| PD11 (AF9) | TSC_G6_IO2 |
| PD12 (AF9) | TSC_G6_IO3 |
| PD13 (AF9) | TSC_G6_IO4 |
|--------------|-----------------|
| PE2 (AF9) | TSC_G7_IO1 |
| PE3 (AF9) | TSC_G7_IO2 |
| PE4 (AF9) | TSC_G7_IO3 |
| PE5 (AF9) | TSC_G7_IO4 |
|--------------|-----------------|
| PF14 (AF9) | TSC_G8_IO1 |
| PF15 (AF9) | TSC_G8_IO2 |
| PG0 (AF9) | TSC_G8_IO3 |
| PG1 (AF9) | TSC_G8_IO4 |
|--------------|-----------------|
| PB10 (AF9) | TSC_SYNC |
| PD2 (AF9) | |
+--------------------------------+
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup TSC TSC
* @brief HAL TSC module driver
* @{
*/
#ifdef HAL_TSC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static uint32_t TSC_extract_groups(uint32_t iomask);
/* Exported functions --------------------------------------------------------*/
/** @defgroup TSC_Exported_Functions TSC Exported Functions
* @{
*/
/** @defgroup TSC_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 TSC.
(+) De-initialize the TSC.
@endverbatim
* @{
*/
/**
* @brief Initialize the TSC peripheral according to the specified parameters
* in the TSC_InitTypeDef structure and initialize the associated handle.
* @param htsc TSC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef *htsc)
{
/* Check TSC handle allocation */
if (htsc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_CTPH(htsc->Init.CTPulseHighLength));
assert_param(IS_TSC_CTPL(htsc->Init.CTPulseLowLength));
assert_param(IS_TSC_SS(htsc->Init.SpreadSpectrum));
assert_param(IS_TSC_SSD(htsc->Init.SpreadSpectrumDeviation));
assert_param(IS_TSC_SS_PRESC(htsc->Init.SpreadSpectrumPrescaler));
assert_param(IS_TSC_PG_PRESC(htsc->Init.PulseGeneratorPrescaler));
assert_param(IS_TSC_PG_PRESC_VS_CTPL(htsc->Init.PulseGeneratorPrescaler, htsc->Init.CTPulseLowLength));
assert_param(IS_TSC_MCV(htsc->Init.MaxCountValue));
assert_param(IS_TSC_IODEF(htsc->Init.IODefaultMode));
assert_param(IS_TSC_SYNC_POL(htsc->Init.SynchroPinPolarity));
assert_param(IS_TSC_ACQ_MODE(htsc->Init.AcquisitionMode));
assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt));
assert_param(IS_TSC_GROUP(htsc->Init.ChannelIOs));
assert_param(IS_TSC_GROUP(htsc->Init.ShieldIOs));
assert_param(IS_TSC_GROUP(htsc->Init.SamplingIOs));
if (htsc->State == HAL_TSC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
htsc->Lock = HAL_UNLOCKED;
#if (USE_HAL_TSC_REGISTER_CALLBACKS == 1)
/* Init the TSC Callback settings */
htsc->ConvCpltCallback = HAL_TSC_ConvCpltCallback; /* Legacy weak ConvCpltCallback */
htsc->ErrorCallback = HAL_TSC_ErrorCallback; /* Legacy weak ErrorCallback */
if (htsc->MspInitCallback == NULL)
{
htsc->MspInitCallback = HAL_TSC_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
htsc->MspInitCallback(htsc);
#else
/* Init the low level hardware : GPIO, CLOCK, CORTEX */
HAL_TSC_MspInit(htsc);
#endif /* USE_HAL_TSC_REGISTER_CALLBACKS */
}
/* Initialize the TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/*--------------------------------------------------------------------------*/
/* Set TSC parameters */
/* Enable TSC */
htsc->Instance->CR = TSC_CR_TSCE;
/* Set all functions */
htsc->Instance->CR |= (htsc->Init.CTPulseHighLength |
htsc->Init.CTPulseLowLength |
(htsc->Init.SpreadSpectrumDeviation << TSC_CR_SSD_Pos) |
htsc->Init.SpreadSpectrumPrescaler |
htsc->Init.PulseGeneratorPrescaler |
htsc->Init.MaxCountValue |
htsc->Init.SynchroPinPolarity |
htsc->Init.AcquisitionMode);
/* Spread spectrum */
if (htsc->Init.SpreadSpectrum == ENABLE)
{
htsc->Instance->CR |= TSC_CR_SSE;
}
/* Disable Schmitt trigger hysteresis on all used TSC IOs */
htsc->Instance->IOHCR = (~(htsc->Init.ChannelIOs | htsc->Init.ShieldIOs | htsc->Init.SamplingIOs));
/* Set channel and shield IOs */
htsc->Instance->IOCCR = (htsc->Init.ChannelIOs | htsc->Init.ShieldIOs);
/* Set sampling IOs */
htsc->Instance->IOSCR = htsc->Init.SamplingIOs;
/* Set the groups to be acquired */
htsc->Instance->IOGCSR = TSC_extract_groups(htsc->Init.ChannelIOs);
/* Disable interrupts */
htsc->Instance->IER &= (~(TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
htsc->Instance->ICR = (TSC_FLAG_EOA | TSC_FLAG_MCE);
/*--------------------------------------------------------------------------*/
/* Initialize the TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Deinitialize the TSC peripheral registers to their default reset values.
* @param htsc TSC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef *htsc)
{
/* Check TSC handle allocation */
if (htsc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
#if (USE_HAL_TSC_REGISTER_CALLBACKS == 1)
if (htsc->MspDeInitCallback == NULL)
{
htsc->MspDeInitCallback = HAL_TSC_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: GPIO, CLOCK, NVIC */
htsc->MspDeInitCallback(htsc);
#else
/* DeInit the low level hardware */
HAL_TSC_MspDeInit(htsc);
#endif /* USE_HAL_TSC_REGISTER_CALLBACKS */
/* Change TSC state */
htsc->State = HAL_TSC_STATE_RESET;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initialize the TSC MSP.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_MspInit(TSC_HandleTypeDef *htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_MspInit could be implemented in the user file.
*/
}
/**
* @brief DeInitialize the TSC MSP.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_MspDeInit(TSC_HandleTypeDef *htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_MspDeInit could be implemented in the user file.
*/
}
#if (USE_HAL_TSC_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User TSC Callback
* To be used instead of the weak predefined callback
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_TSC_CONV_COMPLETE_CB_ID Conversion completed callback ID
* @arg @ref HAL_TSC_ERROR_CB_ID Error callback ID
* @arg @ref HAL_TSC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_TSC_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_RegisterCallback(TSC_HandleTypeDef *htsc, HAL_TSC_CallbackIDTypeDef CallbackID,
pTSC_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(htsc);
if (HAL_TSC_STATE_READY == htsc->State)
{
switch (CallbackID)
{
case HAL_TSC_CONV_COMPLETE_CB_ID :
htsc->ConvCpltCallback = pCallback;
break;
case HAL_TSC_ERROR_CB_ID :
htsc->ErrorCallback = pCallback;
break;
case HAL_TSC_MSPINIT_CB_ID :
htsc->MspInitCallback = pCallback;
break;
case HAL_TSC_MSPDEINIT_CB_ID :
htsc->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_TSC_STATE_RESET == htsc->State)
{
switch (CallbackID)
{
case HAL_TSC_MSPINIT_CB_ID :
htsc->MspInitCallback = pCallback;
break;
case HAL_TSC_MSPDEINIT_CB_ID :
htsc->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(htsc);
return status;
}
/**
* @brief Unregister an TSC Callback
* TSC callback is redirected to the weak predefined callback
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @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_TSC_CONV_COMPLETE_CB_ID Conversion completed callback ID
* @arg @ref HAL_TSC_ERROR_CB_ID Error callback ID
* @arg @ref HAL_TSC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_TSC_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_UnRegisterCallback(TSC_HandleTypeDef *htsc, HAL_TSC_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(htsc);
if (HAL_TSC_STATE_READY == htsc->State)
{
switch (CallbackID)
{
case HAL_TSC_CONV_COMPLETE_CB_ID :
htsc->ConvCpltCallback = HAL_TSC_ConvCpltCallback; /* Legacy weak ConvCpltCallback */
break;
case HAL_TSC_ERROR_CB_ID :
htsc->ErrorCallback = HAL_TSC_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_TSC_MSPINIT_CB_ID :
htsc->MspInitCallback = HAL_TSC_MspInit; /* Legacy weak MspInit */
break;
case HAL_TSC_MSPDEINIT_CB_ID :
htsc->MspDeInitCallback = HAL_TSC_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_TSC_STATE_RESET == htsc->State)
{
switch (CallbackID)
{
case HAL_TSC_MSPINIT_CB_ID :
htsc->MspInitCallback = HAL_TSC_MspInit; /* Legacy weak MspInit */
break;
case HAL_TSC_MSPDEINIT_CB_ID :
htsc->MspDeInitCallback = HAL_TSC_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
htsc->ErrorCode |= HAL_TSC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(htsc);
return status;
}
#endif /* USE_HAL_TSC_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group2 Input and Output operation functions
* @brief Input and Output operation functions
*
@verbatim
===============================================================================
##### IO Operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Start acquisition in polling mode.
(+) Start acquisition in interrupt mode.
(+) Stop conversion in polling mode.
(+) Stop conversion in interrupt mode.
(+) Poll for acquisition completed.
(+) Get group acquisition status.
(+) Get group acquisition value.
@endverbatim
* @{
*/
/**
* @brief Start the acquisition.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* Clear interrupts */
__HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Set touch sensing IOs not acquired to the specified IODefaultMode */
if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Launch the acquisition */
__HAL_TSC_START_ACQ(htsc);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the acquisition in interrupt mode.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt));
/* Process locked */
__HAL_LOCK(htsc);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* Enable end of acquisition interrupt */
__HAL_TSC_ENABLE_IT(htsc, TSC_IT_EOA);
/* Enable max count error interrupt (optional) */
if (htsc->Init.MaxCountInterrupt == ENABLE)
{
__HAL_TSC_ENABLE_IT(htsc, TSC_IT_MCE);
}
else
{
__HAL_TSC_DISABLE_IT(htsc, TSC_IT_MCE);
}
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Set touch sensing IOs not acquired to the specified IODefaultMode */
if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Launch the acquisition */
__HAL_TSC_START_ACQ(htsc);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the acquisition previously launched in polling mode.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop the acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Set touch sensing IOs in low power mode (output push-pull) */
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the acquisition previously launched in interrupt mode.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop the acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Set touch sensing IOs in low power mode (output push-pull) */
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
/* Disable interrupts */
__HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Start acquisition and wait until completion.
* @note There is no need of a timeout parameter as the max count error is already
* managed by the TSC peripheral.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL state
*/
HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Check end of acquisition */
while (HAL_TSC_GetState(htsc) == HAL_TSC_STATE_BUSY)
{
/* The timeout (max count error) is managed by the TSC peripheral itself. */
}
/* Process unlocked */
__HAL_UNLOCK(htsc);
return HAL_OK;
}
/**
* @brief Get the acquisition status for a group.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param gx_index Index of the group
* @retval Group status
*/
TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef *htsc, uint32_t gx_index)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_GROUP_INDEX(gx_index));
/* Return the group status */
return (__HAL_TSC_GET_GROUP_STATUS(htsc, gx_index));
}
/**
* @brief Get the acquisition measure for a group.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param gx_index Index of the group
* @retval Acquisition measure
*/
uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef *htsc, uint32_t gx_index)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_GROUP_INDEX(gx_index));
/* Return the group acquisition counter */
return htsc->Instance->IOGXCR[gx_index];
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure TSC IOs
(+) Discharge TSC IOs
@endverbatim
* @{
*/
/**
* @brief Configure TSC IOs.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param config Pointer to the configuration structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef *htsc, TSC_IOConfigTypeDef *config)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_GROUP(config->ChannelIOs));
assert_param(IS_TSC_GROUP(config->ShieldIOs));
assert_param(IS_TSC_GROUP(config->SamplingIOs));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Disable Schmitt trigger hysteresis on all used TSC IOs */
htsc->Instance->IOHCR = (~(config->ChannelIOs | config->ShieldIOs | config->SamplingIOs));
/* Set channel and shield IOs */
htsc->Instance->IOCCR = (config->ChannelIOs | config->ShieldIOs);
/* Set sampling IOs */
htsc->Instance->IOSCR = config->SamplingIOs;
/* Set groups to be acquired */
htsc->Instance->IOGCSR = TSC_extract_groups(config->ChannelIOs);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Discharge TSC IOs.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param choice This parameter can be set to ENABLE or DISABLE.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef *htsc, FunctionalState choice)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
if (choice == ENABLE)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return the group acquisition counter */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group4 Peripheral State and Errors functions
* @brief Peripheral State and Errors functions
*
@verbatim
===============================================================================
##### State and Errors functions #####
===============================================================================
[..]
This subsection provides functions allowing to
(+) Get TSC state.
@endverbatim
* @{
*/
/**
* @brief Return the TSC handle state.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL state
*/
HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
if (htsc->State == HAL_TSC_STATE_BUSY)
{
/* Check end of acquisition flag */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET)
{
/* Check max count error flag */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET)
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_ERROR;
}
else
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
}
}
}
/* Return TSC state */
return htsc->State;
}
/**
* @}
*/
/** @defgroup TSC_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks
* @{
*/
/**
* @brief Handle TSC interrupt request.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
void HAL_TSC_IRQHandler(TSC_HandleTypeDef *htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Check if the end of acquisition occurred */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET)
{
/* Clear EOA flag */
__HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_EOA);
}
/* Check if max count error occurred */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET)
{
/* Clear MCE flag */
__HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_MCE);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_ERROR;
#if (USE_HAL_TSC_REGISTER_CALLBACKS == 1)
htsc->ErrorCallback(htsc);
#else
/* Conversion completed callback */
HAL_TSC_ErrorCallback(htsc);
#endif /* USE_HAL_TSC_REGISTER_CALLBACKS */
}
else
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
#if (USE_HAL_TSC_REGISTER_CALLBACKS == 1)
htsc->ConvCpltCallback(htsc);
#else
/* Conversion completed callback */
HAL_TSC_ConvCpltCallback(htsc);
#endif /* USE_HAL_TSC_REGISTER_CALLBACKS */
}
}
/**
* @brief Acquisition completed callback in non-blocking mode.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef *htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_ConvCpltCallback could be implemented in the user file.
*/
}
/**
* @brief Error callback in non-blocking mode.
* @param htsc Pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_ErrorCallback(TSC_HandleTypeDef *htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_ErrorCallback could be implemented in the user file.
*/
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup TSC_Private_Functions TSC Private Functions
* @{
*/
/**
* @brief Utility function used to set the acquired groups mask.
* @param iomask Channels IOs mask
* @retval Acquired groups mask
*/
static uint32_t TSC_extract_groups(uint32_t iomask)
{
uint32_t groups = 0UL;
uint32_t idx;
for (idx = 0UL; idx < (uint32_t)TSC_NB_OF_GROUPS; idx++)
{
if ((iomask & (0x0FUL << (idx * 4UL))) != 0UL)
{
groups |= (1UL << idx);
}
}
return groups;
}
/**
* @}
*/
#endif /* HAL_TSC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_tsc.c
|
C
|
apache-2.0
| 34,806
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 (surcharged) 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 (surcharged) functions:
examples HAL_UART_TxCpltCallback(), HAL_UART_RxHalfCpltCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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_EndTxTransfer(UART_HandleTypeDef *huart);
static void UART_EndRxTransfer(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);
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);
/* Set the UART Communication parameters */
if (UART_SetConfig(huart) == HAL_ERROR)
{
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
/* In asynchronous mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL and IREN bits in the USART_CR3 register.*/
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);
/* Set the UART Communication parameters */
if (UART_SetConfig(huart) == HAL_ERROR)
{
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
/* In half-duplex mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN and IREN bits in the USART_CR3 register.*/
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);
/* Set the UART Communication parameters */
if (UART_SetConfig(huart) == HAL_ERROR)
{
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
/* In LIN mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN and IREN bits in the USART_CR3 register.*/
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);
/* Set the UART Communication parameters */
if (UART_SetConfig(huart) == HAL_ERROR)
{
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
/* 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;
__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 instead of the weak predefined callback
* @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;
}
__HAL_LOCK(huart);
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_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;
}
__HAL_UNLOCK(huart);
return status;
}
/**
* @brief Unregister an UART Callback
* UART callaback is redirected to the weak predefined callback
* @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;
__HAL_LOCK(huart);
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_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;
}
__HAL_UNLOCK(huart);
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;
}
/* Process locked */
__HAL_LOCK(huart);
if (huart->gState == HAL_UART_STATE_READY)
{
huart->RxEventCallback = pCallback;
}
else
{
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(huart);
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;
/* Process locked */
__HAL_LOCK(huart);
if (huart->gState == 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;
}
/* Release Lock */
__HAL_UNLOCK(huart);
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;
}
__HAL_LOCK(huart);
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
}
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;
}
__HAL_UNLOCK(huart);
while (huart->TxXferCount > 0U)
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
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)
{
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;
}
__HAL_LOCK(huart);
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
}
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;
}
__HAL_UNLOCK(huart);
/* as long as data have to be received */
while (huart->RxXferCount > 0U)
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
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;
}
__HAL_LOCK(huart);
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
}
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;
}
__HAL_UNLOCK(huart);
/* 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;
}
__HAL_UNLOCK(huart);
/* 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;
}
__HAL_LOCK(huart);
/* Set Reception type to Standard reception */
huart->ReceptionType = HAL_UART_RECEPTION_STANDARD;
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
}
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;
}
}
/**
* @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;
}
__HAL_LOCK(huart);
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;
__HAL_UNLOCK(huart);
/* 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);
__HAL_UNLOCK(huart);
/* 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;
}
__HAL_LOCK(huart);
/* 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;
__HAL_LOCK(huart);
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;
}
}
}
}
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Resume the DMA Transfer.
* @param huart UART handle.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart)
{
__HAL_LOCK(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;
}
}
}
__HAL_UNLOCK(huart);
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;
}
/**
* @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));
}
/* Abort the UART DMA Tx channel if enabled */
if (HAL_IS_BIT_SET(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))
{
/* 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;
}
}
}
}
/* 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);
/* Abort the UART DMA Tx channel if enabled */
if (HAL_IS_BIT_SET(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;
}
}
}
}
/* 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));
}
/* Abort the UART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(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;
}
}
}
}
/* 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 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))
{
/* 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))
{
/* 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;
}
}
}
/* 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);
/* Abort the UART DMA Tx channel if enabled */
if (HAL_IS_BIT_SET(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
{
/* 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));
}
/* Abort the UART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(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
{
/* 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);
/* Abort the UART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(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
{
/* 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);
/* 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);
/* 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);
}
#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
{
/* 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);
#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;
}
}
/* 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(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(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->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;
uint32_t 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 */
pclk = HAL_RCCEx_GetPeriphCLKFreq(clocksource);
/* 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)
{
pclk = HAL_RCCEx_GetPeriphCLKFreq(clocksource);
/* 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
{
pclk = HAL_RCCEx_GetPeriphCLKFreq(clocksource);
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 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/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 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 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);
}
/* 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)
{
/* 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)
{
/* 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;
__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))
{
/* 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_RXFNEIE | USART_CR1_PEIE |
USART_CR1_TXEIE_TXFNFIE));
ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
__HAL_UNLOCK(huart);
return HAL_TIMEOUT;
}
if (READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U)
{
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RTOF) == SET)
{
/* Clear Receiver Timeout flag*/
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF);
/* 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_RXFNEIE | USART_CR1_PEIE |
USART_CR1_TXEIE_TXFNFIE));
ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
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;
}
__HAL_UNLOCK(huart);
/* 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;
}
__HAL_UNLOCK(huart);
/* 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;
}
/**
* @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;
__HAL_UNLOCK(huart);
/* Restore huart->RxState to ready */
huart->RxState = HAL_UART_STATE_READY;
return HAL_ERROR;
}
}
__HAL_UNLOCK(huart);
/* 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;
}
/**
* @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;
}
/**
* @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;
/* 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);
/* 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);
}
}
/* 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);
/* 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 */
}
/**
* @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;
/* 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;
/* 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;
/* 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;
/* 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_uart.c
|
C
|
apache-2.0
| 156,091
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 8U
/* UART TX FIFO depth */
#define TX_FIFO_DEPTH 8U
/**
* @}
*/
/* 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);
/* Set the UART Communication parameters */
if (UART_SetConfig(huart) == HAL_ERROR)
{
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
/* 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.
(#) TX/RX Fifos Callbacks:
(+) HAL_UARTEx_RxFifoFullCallback()
(+) HAL_UARTEx_TxFifoEmptyCallback()
@endverbatim
* @{
*/
/**
* @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_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);
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;
}
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->RxState = HAL_UART_STATE_BUSY_RX;
huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE;
/* 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;
}
__HAL_UNLOCK(huart);
/* 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->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;
/* Check that a Rx process is not already ongoing */
if (huart->RxState == HAL_UART_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
__HAL_LOCK(huart);
/* Set Reception type to reception till IDLE Event*/
huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE;
status = UART_Start_Receive_IT(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;
}
}
/**
* @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;
}
__HAL_LOCK(huart);
/* Set Reception type to reception till IDLE Event*/
huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE;
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;
}
}
/**
* @brief Set autonomous mode Configuration.
* @param huart UART handle.
* @param sConfig Autonomous mode structure parameters.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UARTEx_SetConfigAutonomousMode(UART_HandleTypeDef *huart, UART_AutonomousModeConfTypeDef *sConfig)
{
uint32_t tmpreg;
if (huart->gState == HAL_UART_STATE_READY)
{
/* Check the parameters */
assert_param(IS_UART_TRIGGER_POLARITY(sConfig->TriggerPolarity));
assert_param(IS_UART_IDLE_FRAME_TRANSMIT(sConfig->IdleFrame));
assert_param(IS_UART_TX_DATA_SIZE(sConfig->DataSize));
if (IS_LPUART_INSTANCE(huart->Instance))
{
assert_param(IS_LPUART_TRIGGER_SELECTION(sConfig->TriggerSelection));
}
else
{
assert_param(IS_UART_TRIGGER_SELECTION(sConfig->TriggerSelection));
}
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/* Disable UART */
__HAL_UART_DISABLE(huart);
/* Disable Transmitter */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_TE);
/* Clear AUTOCR register */
CLEAR_REG(huart->Instance->AUTOCR);
/* UART AUTOCR Configuration */
tmpreg = ((sConfig->DataSize << USART_AUTOCR_TDN_Pos) | (sConfig->TriggerPolarity) | \
(sConfig->AutonomousModeState) | (sConfig->IdleFrame) | \
(sConfig->TriggerSelection << USART_AUTOCR_TRIGSEL_Pos));
WRITE_REG(huart->Instance->AUTOCR, tmpreg);
/* Enable UART */
__HAL_UART_ENABLE(huart);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Get autonomous mode Configuration.
* @param huart UART handle.
* @param sConfig Autonomous mode structure parameters.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UARTEx_GetConfigAutonomousMode(UART_HandleTypeDef *huart, UART_AutonomousModeConfTypeDef *sConfig)
{
uint32_t tmpreg;
/* Read AUTOCR register */
tmpreg = READ_REG(huart->Instance->AUTOCR);
/* Fill Autonomous structure parameter */
sConfig->AutonomousModeState = (tmpreg & USART_AUTOCR_TRIGEN);
sConfig->TriggerSelection = ((tmpreg & USART_AUTOCR_TRIGSEL) >> USART_AUTOCR_TRIGSEL_Pos);
sConfig->TriggerPolarity = (tmpreg & USART_AUTOCR_TRIGPOL);
sConfig->IdleFrame = (tmpreg & USART_AUTOCR_IDLEDIS);
sConfig->DataSize = (tmpreg & USART_AUTOCR_TDN);
return HAL_OK;
}
/**
* @brief Clear autonomous mode Configuration.
* @param huart UART handle.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UARTEx_ClearConfigAutonomousMode(UART_HandleTypeDef *huart)
{
if (huart->gState == HAL_UART_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/* Disable UART */
__HAL_UART_DISABLE(huart);
/* Clear AUTOCR register */
CLEAR_REG(huart->Instance->AUTOCR);
/* Enable UART */
__HAL_UART_ENABLE(huart);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @}
*/
/**
* @}
*/
/** @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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_uart_ex.c
|
C
|
apache-2.0
| 36,859
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 (surcharged) 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 (surcharged) functions:
examples HAL_USART_TxCpltCallback(), HAL_USART_RxHalfCpltCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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);
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);
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 instead of the weak predefined callback
* @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;
}
/* Process locked */
__HAL_LOCK(husart);
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;
}
/* Release Lock */
__HAL_UNLOCK(husart);
return status;
}
/**
* @brief Unregister an USART Callback
* USART callaback is redirected to the weak predefined callback
* @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;
/* Process locked */
__HAL_LOCK(husart);
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;
}
/* Release Lock */
__HAL_UNLOCK(husart);
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);
/* Disable the USART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
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);
/* Disable the USART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
}
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);
/* Disable the USART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
/* Disable the USART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
}
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);
/* Disable the USART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
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);
/* Disable the USART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
}
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);
/* Disable the USART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
/* Disable the USART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
}
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;
}
}
/**
* @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;
}
/**
* @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));
/* Abort the USART DMA Tx channel if enabled */
if (HAL_IS_BIT_SET(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))
{
/* 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;
}
}
}
}
/* 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 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))
{
/* 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))
{
/* 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;
}
}
}
/* 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);
/* Abort the USART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, 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
{
/* 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(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(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;
}
/**
* @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)
{
/* 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);
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 */
}
/**
* @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_HSI:
usartdiv = (uint32_t)(USART_DIV_SAMPLING8(HSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler));
break;
case USART_CLOCKSOURCE_SYSCLK:
pclk = HAL_RCC_GetSysClockFreq();
usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_usart.c
|
C
|
apache-2.0
| 133,469
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 8U
/* USART TX FIFO depth */
#define TX_FIFO_DEPTH 8U
/**
* @}
*/
/* 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;
}
/**
* @brief Set autonomous mode Configuration.
* @param husart USART handle.
* @param sConfig Autonomous mode structure parameters.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USARTEx_SetConfigAutonomousMode(USART_HandleTypeDef *husart,
USART_AutonomousModeConfTypeDef *sConfig)
{
uint32_t tmpreg;
if (husart->State == HAL_USART_STATE_READY)
{
/* Check the parameters */
assert_param(IS_USART_TRIGGER_POLARITY(sConfig->TriggerPolarity));
assert_param(IS_USART_IDLE_FRAME_TRANSMIT(sConfig->IdleFrame));
assert_param(IS_USART_TX_DATA_SIZE(sConfig->DataSize));
assert_param(IS_USART_TRIGGER_SELECTION(sConfig->TriggerSelection));
/* Process Locked */
__HAL_LOCK(husart);
husart->State = HAL_USART_STATE_BUSY;
/* Disable USART */
__HAL_USART_DISABLE(husart);
/* Disable Transmitter */
CLEAR_BIT(husart->Instance->CR1, USART_CR1_TE);
/* Clear AUTOCR register */
CLEAR_REG(husart->Instance->AUTOCR);
/* USART AUTOCR Configuration */
tmpreg = ((sConfig->DataSize << USART_AUTOCR_TDN_Pos) | (sConfig->TriggerPolarity) |
(sConfig->AutonomousModeState) | (sConfig->IdleFrame) |
(sConfig->TriggerSelection << USART_AUTOCR_TRIGSEL_Pos));
WRITE_REG(husart->Instance->AUTOCR, tmpreg);
/* Enable USART */
__HAL_USART_ENABLE(husart);
husart->State = HAL_USART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(husart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Get autonomous mode Configuration.
* @param husart USART handle.
* @param sConfig Autonomous mode structure parameters.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USARTEx_GetConfigAutonomousMode(USART_HandleTypeDef *husart,
USART_AutonomousModeConfTypeDef *sConfig)
{
uint32_t tmpreg;
/* Read AUTOCR register */
tmpreg = READ_REG(husart->Instance->AUTOCR);
/* Fill Autonomous structure parameter */
sConfig->AutonomousModeState = (tmpreg & USART_AUTOCR_TRIGEN);
sConfig->TriggerSelection = ((tmpreg & USART_AUTOCR_TRIGSEL) >> USART_AUTOCR_TRIGSEL_Pos);
sConfig->TriggerPolarity = (tmpreg & USART_AUTOCR_TRIGPOL);
sConfig->IdleFrame = (tmpreg & USART_AUTOCR_IDLEDIS);
sConfig->DataSize = (tmpreg & USART_AUTOCR_TDN);
return HAL_OK;
}
/**
* @brief Clear autonomous mode Configuration.
* @param husart USART handle.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USARTEx_ClearConfigAutonomousMode(USART_HandleTypeDef *husart)
{
if (husart->State == HAL_USART_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(husart);
husart->State = HAL_USART_STATE_BUSY;
/* Disable USART */
__HAL_USART_DISABLE(husart);
/* Clear AUTOCR register */
CLEAR_REG(husart->Instance->AUTOCR);
/* Enable USART */
__HAL_USART_ENABLE(husart);
husart->State = HAL_USART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(husart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @}
*/
/**
* @}
*/
/** @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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_usart_ex.c
|
C
|
apache-2.0
| 18,917
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 56MHz (PCLK1) with zero prescaler:
max timeout before reset: approximately 73.14us
(++) Counter max (T[5;0] = 0x3F) at 56MHz (PCLK1) with prescaler
dividing by 128:
max timeout before reset: approximately 599.18ms
##### 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_wwdg.c
|
C
|
apache-2.0
| 15,307
|
/**
******************************************************************************
* @file stm32u5xx_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
+ Delay block 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 unsing 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
(+) Sending Instruction Only Once (SIOO) 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_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.
*** Delay Block functions ***
==========================================
[..]
The delay block (DLYB) is used to generate an output clock that is dephased from the input clock.
(+) The delay line length can be Configure to one period of the Input clock with HAL_XSPI_DLYB_GetClockPeriod().
(+) The phase of the output clock can be programmed directly with HAL_XSPI_DLYB_SetConfig().
(+) The phase of the output clock can be got with HAL_XSPI_DLYB_GetConfig().
[..]
*** 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 HSPI 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 (surcharged) 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 (surcharged) functions.
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) 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 (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
#if defined(HSPI) || defined(HSPI1) || defined(HSPI2)|| defined(OCTOSPI) || defined(OCTOSPI1)|| defined(OCTOSPI2)
/** @addtogroup STM32U5xx_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 OSPI_NB_INSTANCE 2U
#define OSPI_IOM_NB_PORTS 2U
#define OSPI_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));
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_OCTOSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte));
}
if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_HSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte));
}
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_XSPI_DLYB_BYPASS(hxspi->Init.DelayBlockBypass));
}
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_XSPI_MAXTRAN(hxspi->Init.MaxTran));
}
/* 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 delay block bypass */
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
MODIFY_REG(hxspi->Instance->DCR1, OCTOSPI_DCR1_DLYBYP, hxspi->Init.DelayBlockBypass);
}
/* 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 */
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
MODIFY_REG(hxspi->Instance->DCR3, OCTOSPI_DCR3_MAXTRAN, (hxspi->Init.MaxTran << OCTOSPI_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_HSPI_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 */
MODIFY_REG(hxspi->Instance->CR, XSPI_CR_DMM, hxspi->Init.MemoryMode);
/* 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)
{
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_OCTOSPI_IO_SELECT(pCmd->IOSelect));
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_HSPI_IO_SELECT(pCmd->IOSelect));
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
}
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));
}
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_OCTOSPI_DATA_MODE(pCmd->DataMode));
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_HSPI_DATA_MODE(pCmd->DataMode));
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
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));
assert_param(IS_XSPI_SIOO_MODE(pCmd->SIOOMode));
/* 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_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 (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM)
{
assert_param(IS_OCTOSPI_IO_SELECT(pCmd->IOSelect));
}
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM)
{
assert_param(IS_HSPI_IO_SELECT(pCmd->IOSelect));
}
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
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));
}
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_OCTOSPI_DATA_MODE(pCmd->DataMode));
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_HSPI_DATA_MODE(pCmd->DataMode));
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
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));
assert_param(IS_XSPI_SIOO_MODE(pCmd->SIOOMode));
/* 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_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));
/* 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 lines */
WRITE_REG(hxspi->Instance->CCR, (pCmd->DQSMode | XSPI_CCR_DDTR | XSPI_CCR_DMODE_2 |
pCmd->AddressWidth | XSPI_CCR_ADDTR | XSPI_CCR_ADMODE_2));
WRITE_REG(hxspi->Instance->WCCR, (pCmd->DQSMode | XSPI_WCCR_DDTR | XSPI_WCCR_DMODE_2 |
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_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, uint8_t *const 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 = 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, uint8_t *const 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 = 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, uint8_t *const 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 = 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_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 instead of the weak (surcharged) 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 (surcharged) 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 transmission.
* @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)
{
hxspi->State = HAL_XSPI_STATE_READY;
}
}
}
else
{
hxspi->State = HAL_XSPI_STATE_READY;
}
}
else
{
status = HAL_ERROR;
hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE;
}
return status;
}
/**
* @brief Abort the current transmission (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);
}
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
{
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;
if (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_OCTOSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte));
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
assert_param(IS_HSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte));
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* 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(XSPI_HandleTypeDef *hxspi)
{
return ((READ_BIT(hxspi->Instance->CR, XSPI_CR_FTHRES) >> XSPI_CR_FTHRES_Pos) + 1U);
}
/** @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(XSPI_HandleTypeDef *hxspi)
{
return hxspi->ErrorCode;
}
/**
* @brief Return the XSPI handle state.
* @param hxspi : XSPI handle
* @retval HAL state
*/
uint32_t HAL_XSPI_GetState(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 *hxspi, XSPIM_CfgTypeDef *const pCfg, uint32_t Timeout)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t instance;
uint8_t index;
uint8_t xspi_enabled = 0U;
uint8_t other_instance;
XSPIM_CfgTypeDef IOM_cfg[OSPI_NB_INSTANCE];
/* Prevent unused argument(s) compilation warning */
UNUSED(Timeout);
/* Check the parameters of the XSPI IO Manager configuration structure */
assert_param(IS_XSPIM_PORT(pCfg->ClkPort));
assert_param(IS_XSPIM_DQS_PORT(pCfg->DQSPort));
assert_param(IS_XSPIM_PORT(pCfg->NCSPort));
assert_param(IS_XSPIM_IO_PORT(pCfg->IOLowPort));
assert_param(IS_XSPIM_IO_PORT(pCfg->IOHighPort));
assert_param(IS_XSPIM_REQ2ACKTIME(pCfg->Req2AckTime));
if (hxspi->Instance == OCTOSPI1)
{
instance = 0U;
other_instance = 1U;
}
else if (hxspi->Instance == OCTOSPI2)
{
instance = 1U;
other_instance = 0U;
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/**************** Get current configuration of the instances ****************/
for (index = 0U; index < OSPI_NB_INSTANCE; index++)
{
XSPIM_GetConfig(index + 1U, &(IOM_cfg[index]));
}
if (status == HAL_OK)
{
/********** Disable both XSPI to configure XSPI IO Manager **********/
if ((OCTOSPI1->CR & XSPI_CR_EN) != 0U)
{
CLEAR_BIT(OCTOSPI1->CR, XSPI_CR_EN);
xspi_enabled |= 0x1U;
}
if ((OCTOSPI2->CR & XSPI_CR_EN) != 0U)
{
CLEAR_BIT(OCTOSPI2->CR, XSPI_CR_EN);
xspi_enabled |= 0x2U;
}
/***************** Deactivation of previous configuration *****************/
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[instance].NCSPort - 1U)], OCTOSPIM_PCR_NCSEN);
if ((OCTOSPIM->CR & OCTOSPIM_CR_MUXEN) != 0U)
{
/* De-multiplexing should be performed */
CLEAR_BIT(OCTOSPIM->CR, OCTOSPIM_CR_MUXEN);
if (other_instance == 1U)
{
SET_BIT(OCTOSPIM->PCR[(IOM_cfg[other_instance].ClkPort - 1U)], OCTOSPIM_PCR_CLKSRC);
if (IOM_cfg[other_instance].DQSPort != 0U)
{
SET_BIT(OCTOSPIM->PCR[(IOM_cfg[other_instance].DQSPort - 1U)], OCTOSPIM_PCR_DQSSRC);
}
if (IOM_cfg[other_instance].IOLowPort != HAL_XSPIM_IOPORT_NONE)
{
SET_BIT(OCTOSPIM->PCR[((IOM_cfg[other_instance].IOLowPort - 1U)& OSPI_IOM_PORT_MASK)],
OCTOSPIM_PCR_IOLSRC_1);
}
if (IOM_cfg[other_instance].IOHighPort != HAL_XSPIM_IOPORT_NONE)
{
SET_BIT(OCTOSPIM->PCR[((IOM_cfg[other_instance].IOHighPort - 1U)& OSPI_IOM_PORT_MASK)],
OCTOSPIM_PCR_IOHSRC_1);
}
}
}
else
{
if (IOM_cfg[instance].ClkPort != 0U)
{
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[instance].ClkPort - 1U)], OCTOSPIM_PCR_CLKEN);
if (IOM_cfg[instance].DQSPort != 0U)
{
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[instance].DQSPort - 1U)], OCTOSPIM_PCR_DQSEN);
}
if (IOM_cfg[instance].IOLowPort != HAL_XSPIM_IOPORT_NONE)
{
CLEAR_BIT(OCTOSPIM->PCR[((IOM_cfg[instance].IOLowPort - 1U)& OSPI_IOM_PORT_MASK)], OCTOSPIM_PCR_IOLEN);
}
if (IOM_cfg[instance].IOHighPort != HAL_XSPIM_IOPORT_NONE)
{
CLEAR_BIT(OCTOSPIM->PCR[((IOM_cfg[instance].IOHighPort - 1U)& OSPI_IOM_PORT_MASK)], OCTOSPIM_PCR_IOHEN);
}
}
}
/********************* Deactivation of other instance *********************/
if ((pCfg->ClkPort == IOM_cfg[other_instance].ClkPort) || (pCfg->DQSPort == IOM_cfg[other_instance].DQSPort) ||
(pCfg->NCSPort == IOM_cfg[other_instance].NCSPort) || (pCfg->IOLowPort == IOM_cfg[other_instance].IOLowPort) ||
(pCfg->IOHighPort == IOM_cfg[other_instance].IOHighPort))
{
if ((pCfg->ClkPort == IOM_cfg[other_instance].ClkPort) &&
(pCfg->DQSPort == IOM_cfg[other_instance].DQSPort) &&
(pCfg->IOLowPort == IOM_cfg[other_instance].IOLowPort) &&
(pCfg->IOHighPort == IOM_cfg[other_instance].IOHighPort))
{
/* Multiplexing should be performed */
SET_BIT(OCTOSPIM->CR, OCTOSPIM_CR_MUXEN);
}
else
{
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[other_instance].ClkPort - 1U)], OCTOSPIM_PCR_CLKEN);
if (IOM_cfg[other_instance].DQSPort != 0U)
{
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[other_instance].DQSPort - 1U)], OCTOSPIM_PCR_DQSEN);
}
CLEAR_BIT(OCTOSPIM->PCR[(IOM_cfg[other_instance].NCSPort - 1U)], OCTOSPIM_PCR_NCSEN);
if (IOM_cfg[other_instance].IOLowPort != HAL_XSPIM_IOPORT_NONE)
{
CLEAR_BIT(OCTOSPIM->PCR[((IOM_cfg[other_instance].IOLowPort - 1U)& OSPI_IOM_PORT_MASK)], OCTOSPIM_PCR_IOLEN);
}
if (IOM_cfg[other_instance].IOHighPort != HAL_XSPIM_IOPORT_NONE)
{
CLEAR_BIT(OCTOSPIM->PCR[((IOM_cfg[other_instance].IOHighPort - 1U)& OSPI_IOM_PORT_MASK)], OCTOSPIM_PCR_IOHEN);
}
}
}
/******************** Activation of new configuration *********************/
MODIFY_REG(OCTOSPIM->PCR[(pCfg->NCSPort - 1U)], (OCTOSPIM_PCR_NCSEN | OCTOSPIM_PCR_NCSSRC),
(OCTOSPIM_PCR_NCSEN | (instance << OCTOSPIM_PCR_NCSSRC_Pos)));
if ((pCfg->Req2AckTime - 1U) > ((OCTOSPIM->CR & OCTOSPIM_CR_REQ2ACK_TIME) >> OCTOSPIM_CR_REQ2ACK_TIME_Pos))
{
MODIFY_REG(OCTOSPIM->CR, OCTOSPIM_CR_REQ2ACK_TIME, ((pCfg->Req2AckTime - 1U) << OCTOSPIM_CR_REQ2ACK_TIME_Pos));
}
if ((OCTOSPIM->CR & OCTOSPIM_CR_MUXEN) != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[(pCfg->ClkPort - 1U)], (OCTOSPIM_PCR_CLKEN | OCTOSPIM_PCR_CLKSRC), OCTOSPIM_PCR_CLKEN);
if (pCfg->DQSPort != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[(pCfg->DQSPort - 1U)], (OCTOSPIM_PCR_DQSEN | OCTOSPIM_PCR_DQSSRC), OCTOSPIM_PCR_DQSEN);
}
if ((pCfg->IOLowPort & OCTOSPIM_PCR_IOLEN) != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOLowPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC), OCTOSPIM_PCR_IOLEN);
}
else if (pCfg->IOLowPort != HAL_XSPIM_IOPORT_NONE)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOLowPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC), OCTOSPIM_PCR_IOHEN);
}
else
{
/* Nothing to do */
}
if ((pCfg->IOHighPort & OCTOSPIM_PCR_IOLEN) != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOHighPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC), (OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC_0));
}
else if (pCfg->IOHighPort != HAL_XSPIM_IOPORT_NONE)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOHighPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC), (OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC_0));
}
else
{
/* Nothing to do */
}
}
else
{
MODIFY_REG(OCTOSPIM->PCR[(pCfg->ClkPort - 1U)], (OCTOSPIM_PCR_CLKEN | OCTOSPIM_PCR_CLKSRC),
(OCTOSPIM_PCR_CLKEN | (instance << OCTOSPIM_PCR_CLKSRC_Pos)));
if (pCfg->DQSPort != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[(pCfg->DQSPort - 1U)], (OCTOSPIM_PCR_DQSEN | OCTOSPIM_PCR_DQSSRC),
(OCTOSPIM_PCR_DQSEN | (instance << OCTOSPIM_PCR_DQSSRC_Pos)));
}
if ((pCfg->IOLowPort & OCTOSPIM_PCR_IOLEN) != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOLowPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC),
(OCTOSPIM_PCR_IOLEN | (instance << (OCTOSPIM_PCR_IOLSRC_Pos + 1U))));
}
else if (pCfg->IOLowPort != HAL_XSPIM_IOPORT_NONE)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOLowPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC),
(OCTOSPIM_PCR_IOHEN | (instance << (OCTOSPIM_PCR_IOHSRC_Pos + 1U))));
}
else
{
/* Nothing to do */
}
if ((pCfg->IOHighPort & OCTOSPIM_PCR_IOLEN) != 0U)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOHighPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC),
(OCTOSPIM_PCR_IOLEN | OCTOSPIM_PCR_IOLSRC_0 | (instance << (OCTOSPIM_PCR_IOLSRC_Pos + 1U))));
}
else if (pCfg->IOHighPort != HAL_XSPIM_IOPORT_NONE)
{
MODIFY_REG(OCTOSPIM->PCR[((pCfg->IOHighPort - 1U)& OSPI_IOM_PORT_MASK)],
(OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC),
(OCTOSPIM_PCR_IOHEN | OCTOSPIM_PCR_IOHSRC_0 | (instance << (OCTOSPIM_PCR_IOHSRC_Pos + 1U))));
}
else
{
/* Nothing to do */
}
}
/******* Re-enable both XSPI after configure XSPI IO Manager ********/
if ((xspi_enabled & 0x1U) != 0U)
{
SET_BIT(OCTOSPI1->CR, XSPI_CR_EN);
}
if ((xspi_enabled & 0x2U) != 0U)
{
SET_BIT(OCTOSPI2->CR, XSPI_CR_EN);
}
}
return status;
}
/**
* @}
*/
/** @defgroup XSPI_Exported_Functions_Group5 Delay Block function
* @brief Delay block function
*
@verbatim
===============================================================================
##### Delay Block function #####
===============================================================================
[..]
This subsection provides a set of functions allowing to :
(+) Configure the delay block.
@endverbatim
* @{
*/
/**
* @brief Set the Delay Block configuration.
* @param hxspi : XSPI handle.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_XSPI_DLYB_SetConfig(XSPI_HandleTypeDef *hxspi, HAL_XSPI_DLYB_CfgTypeDef *const pdlyb_cfg)
{
HAL_StatusTypeDef status = HAL_ERROR;
/* Enable XSPI Free Running Clock (mandatory) */
SET_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK);
/* Update XSPI state */
hxspi->State = HAL_XSPI_STATE_BUSY_CMD;
if (hxspi->Instance == OCTOSPI1)
{
/* Enable the DelayBlock */
LL_DLYB_Enable(DLYB_OCTOSPI1);
/* Set the Delay Block configuration */
LL_DLYB_SetDelay(DLYB_OCTOSPI1, pdlyb_cfg);
status = HAL_OK;
}
else if (hxspi->Instance == OCTOSPI2)
{
/* Enable the DelayBlock */
LL_DLYB_Enable(DLYB_OCTOSPI2);
/* Set the Delay Block configuration */
LL_DLYB_SetDelay(DLYB_OCTOSPI2, pdlyb_cfg);
status = HAL_OK;
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
}
/* Abort the current XSPI operation if exist */
(void)HAL_XSPI_Abort(hxspi);
/* Disable Free Running Clock */
CLEAR_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK);
return status;
}
/**
* @brief Get the Delay Block configuration.
* @param hxspi : XSPI handle.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_XSPI_DLYB_GetConfig(XSPI_HandleTypeDef *hxspi, HAL_XSPI_DLYB_CfgTypeDef *const pdlyb_cfg)
{
HAL_StatusTypeDef status = HAL_ERROR;
if (hxspi->Instance == OCTOSPI1)
{
LL_DLYB_GetDelay(DLYB_OCTOSPI1, pdlyb_cfg);
status = HAL_OK;
}
else if (hxspi->Instance == OCTOSPI2)
{
LL_DLYB_GetDelay(DLYB_OCTOSPI2, pdlyb_cfg);
status = HAL_OK;
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
}
return status;
}
/**
* @brief Get the Delay line length value.
* @param hxspi : XSPI handle.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_XSPI_DLYB_GetClockPeriod(XSPI_HandleTypeDef *hxspi, HAL_XSPI_DLYB_CfgTypeDef *const pdlyb_cfg)
{
HAL_StatusTypeDef status = HAL_ERROR;
/* Enable XSPI Free Running Clock (mandatory) */
SET_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK);
/* Update XSPI state */
hxspi->State = HAL_XSPI_STATE_BUSY_CMD;
if (hxspi->Instance == OCTOSPI1)
{
/* Enable the DelayBlock */
LL_DLYB_Enable(DLYB_OCTOSPI1);
/* try to detect Period */
if (LL_DLYB_GetClockPeriod(DLYB_OCTOSPI1, pdlyb_cfg) == (uint32_t)SUCCESS)
{
status = HAL_OK;
}
/* Disable the DelayBlock */
LL_DLYB_Disable(DLYB_OCTOSPI1);
}
else if (hxspi->Instance == OCTOSPI2)
{
/* Enable the DelayBlock */
LL_DLYB_Enable(DLYB_OCTOSPI2);
/* try to detect Period */
if (LL_DLYB_GetClockPeriod(DLYB_OCTOSPI2, pdlyb_cfg) == (uint32_t)SUCCESS)
{
status = HAL_OK;
}
/* Disable the DelayBlock */
LL_DLYB_Disable(DLYB_OCTOSPI2);
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
}
/* Abort the current XSPI operation if exist */
(void)HAL_XSPI_Abort(hxspi);
/* Disable Free Running Clock */
CLEAR_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK);
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_HSPI_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 & HSPI_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 & HSPI_CALFCR_FINE);
pCfg->CoarseCalibrationUnit = ((reg & HSPI_CALFCR_COARSE) >> HSPI_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_HSPI_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, (HSPI_CALMR_COARSE | HSPI_CALMR_FINE),
(pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << HSPI_CALMR_COARSE_Pos)));
break;
case HAL_XSPI_CAL_DATA_OUTPUT_DELAY:
MODIFY_REG(hxspi->Instance->CALSOR, (HSPI_CALSOR_COARSE | HSPI_CALSOR_FINE),
(pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << HSPI_CALSOR_COARSE_Pos)));
break;
case HAL_XSPI_CAL_DQS_INPUT_DELAY:
MODIFY_REG(hxspi->Instance->CALSIR, (HSPI_CALSIR_COARSE | HSPI_CALSIR_FINE),
(pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << HSPI_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);
/* Disable the DMA channel */
__HAL_DMA_DISABLE(hdma);
/* 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_ERROR;
}
}
}
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 (IS_OSPI_ALL_INSTANCE(hxspi->Instance))
{
if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM)
{
assert_param(IS_OCTOSPI_IO_SELECT(pCmd->IOSelect));
MODIFY_REG(hxspi->Instance->CR, OCTOSPI_CR_MSEL, pCmd->IOSelect);
}
}
else if (IS_HSPI_ALL_INSTANCE(hxspi->Instance))
{
if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM)
{
assert_param(IS_HSPI_IO_SELECT(pCmd->IOSelect));
MODIFY_REG(hxspi->Instance->CR, HSPI_CR_MSEL, pCmd->IOSelect);
}
}
else
{
hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
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 | pCmd->SIOOMode);
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 reg;
uint32_t value = 0U;
uint32_t index;
/* Initialize the structure */
pCfg->ClkPort = 0U;
pCfg->DQSPort = 0U;
pCfg->NCSPort = 0U;
pCfg->IOLowPort = 0U;
pCfg->IOHighPort = 0U;
if (instance_nb == 2U)
{
if ((OCTOSPIM->CR & OCTOSPIM_CR_MUXEN) == 0U)
{
value = (OCTOSPIM_PCR_CLKSRC | OCTOSPIM_PCR_DQSSRC | OCTOSPIM_PCR_NCSSRC |
OCTOSPIM_PCR_IOLSRC_1 | OCTOSPIM_PCR_IOHSRC_1);
}
else
{
value = OCTOSPIM_PCR_NCSSRC;
}
}
/* Get the information about the instance */
for (index = 0U; index < OSPI_IOM_NB_PORTS; index ++)
{
reg = OCTOSPIM->PCR[index];
if ((reg & OCTOSPIM_PCR_CLKEN) != 0U)
{
/* The clock is enabled on this port */
if ((reg & OCTOSPIM_PCR_CLKSRC) == (value & OCTOSPIM_PCR_CLKSRC))
{
/* The clock correspond to the instance passed as parameter */
pCfg->ClkPort = index + 1U;
}
}
if ((reg & OCTOSPIM_PCR_DQSEN) != 0U)
{
/* The DQS is enabled on this port */
if ((reg & OCTOSPIM_PCR_DQSSRC) == (value & OCTOSPIM_PCR_DQSSRC))
{
/* The DQS correspond to the instance passed as parameter */
pCfg->DQSPort = index + 1U;
}
}
if ((reg & OCTOSPIM_PCR_NCSEN) != 0U)
{
/* The nCS is enabled on this port */
if ((reg & OCTOSPIM_PCR_NCSSRC) == (value & OCTOSPIM_PCR_NCSSRC))
{
/* The nCS correspond to the instance passed as parameter */
pCfg->NCSPort = index + 1U;
}
}
if ((reg & OCTOSPIM_PCR_IOLEN) != 0U)
{
/* The IO Low is enabled on this port */
if ((reg & OCTOSPIM_PCR_IOLSRC_1) == (value & OCTOSPIM_PCR_IOLSRC_1))
{
/* The IO Low correspond to the instance passed as parameter */
if ((reg & OCTOSPIM_PCR_IOLSRC_0) == 0U)
{
pCfg->IOLowPort = (OCTOSPIM_PCR_IOLEN | (index + 1U));
}
else
{
pCfg->IOLowPort = (OCTOSPIM_PCR_IOHEN | (index + 1U));
}
}
}
if ((reg & OCTOSPIM_PCR_IOHEN) != 0U)
{
/* The IO High is enabled on this port */
if ((reg & OCTOSPIM_PCR_IOHSRC_1) == (value & OCTOSPIM_PCR_IOHSRC_1))
{
/* The IO High correspond to the instance passed as parameter */
if ((reg & OCTOSPIM_PCR_IOHSRC_0) == 0U)
{
pCfg->IOHighPort = (OCTOSPIM_PCR_IOLEN | (index + 1U));
}
else
{
pCfg->IOHighPort = (OCTOSPIM_PCR_IOHEN | (index + 1U));
}
}
}
}
}
/**
@endcond
*/
/**
* @}
*/
#endif /* HAL_XSPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
#endif /* HSPI || HSPI1 || HSPI2 || OCTOSPI || OCTOSPI1 || OCTOSPI2 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_hal_xspi.c
|
C
|
apache-2.0
| 126,706
|
/**
******************************************************************************
* @file stm32u5xx_ll_adc.c
* @author MCD Application Team
* @brief ADC LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_adc.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (ADC1) || defined (ADC2) || defined (ADC4)
/** @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, */
/* APB prescaler 16, ADC prescaler 4. */
/* - ADC clock from asynchronous clock (PLL) with prescaler 1, */
/* with highest ratio CPU clock frequency vs HSI clock frequency */
/* Unit: CPU cycles. */
#define ADC_CLOCK_RATIO_VS_CPU_HIGHEST (512UL * 16UL * 4UL)
#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: */
/* applicable for the twoinstances. */
#define IS_LL_ADC_CLOCK(__CLOCK__) \
( ((__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_14B) \
|| ((__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_LEFT_BIT_SHIFT(__LEFT_BIT_SHIFT__) \
( ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_NONE) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_1) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_2) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_3) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_4) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_5) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_6) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_7) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_8) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_9) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_10) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_11) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_12) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_13) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_14) \
|| ((__LEFT_BIT_SHIFT__) == LL_ADC_LEFT_BIT_SHIFT_15) \
)
#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_TIM8_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO2) \
|| ((__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_EXTI_LINE15) \
|| ((__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) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM4_OUT) \
)
#define IS_LL_ADC4_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \
( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH4_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM15_TRGO_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM1_CH1_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM3_CH2_ADC4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE15_ADC4) \
)
#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_DATA_TRANSFER_MODE(__REG_DATA_TRANSFER_MODE__) \
( ((__REG_DATA_TRANSFER_MODE__) == LL_ADC_REG_DR_TRANSFER) \
|| ((__REG_DATA_TRANSFER_MODE__) == LL_ADC_REG_DMA_TRANSFER_LIMITED) \
|| ((__REG_DATA_TRANSFER_MODE__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \
|| ((__REG_DATA_TRANSFER_MODE__) == LL_ADC_REG_MDF_TRANSFER) \
)
#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \
( ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE_ADC4) \
|| ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_LIMITED_ADC4) \
|| ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED_ADC4) \
)
#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_MODE(__REG_SEQ_MODE__) \
( ((__REG_SEQ_MODE__) == LL_ADC_REG_SEQ_FIXED) \
|| ((__REG_SEQ_MODE__) == LL_ADC_REG_SEQ_CONFIGURABLE) \
)
#define IS_LL_ADC4_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \
( ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_DISABLE) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_2RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_3RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_4RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_5RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_6RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_7RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC4_REG_SEQ_SCAN_ENABLE_8RANKS) \
)
#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_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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_TRGO2) \
|| ((__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_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) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM4_OUT) \
)
#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) \
)
/**
* @}
*/
/* 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 pADCxyCOMMON 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(ADC_Common_TypeDef *pADCxyCOMMON)
{
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(pADCxyCOMMON));
if (pADCxyCOMMON == ADC12_COMMON)
{
/* Force reset of ADC clock (core clock) */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_ADC12);
/* Release reset of ADC clock (core clock) */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_ADC12);
}
else /*if ( pADCxyCOMMON == ADC4_COMMON)*/
{
/* Force reset of ADC clock (core clock) */
LL_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_ADC4);
/* Release reset of ADC clock (core clock) */
LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_ADC4);
}
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 pADCxyCOMMON ADC common instance
* (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() )
* @param pADC_CommonInit 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 *pADCxyCOMMON, LL_ADC_CommonInitTypeDef *pADC_CommonInit)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(pADCxyCOMMON));
assert_param(IS_LL_ADC_CLOCK(pADC_CommonInit->CommonClock));
/* 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(pADCxyCOMMON) == 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) */
LL_ADC_SetCommonClock(pADCxyCOMMON, pADC_CommonInit->CommonClock);
}
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_CommonInit 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_CommonInit)
{
/* Set pADC_CommonInit fields to default values */
/* Set fields of ADC common */
/* (all ADC instances belonging to the same ADC common instance) */
pADC_CommonInit->CommonClock = LL_ADC_CLOCK_ASYNC_DIV2;
}
/**
* @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().
* @param pADCx 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 *pADCx)
{
ErrorStatus status = SUCCESS;
__IO uint32_t timeout_cpu_cycles = 0UL;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(pADCx));
/* Disable ADC instance if not already disabled. */
if (LL_ADC_IsEnabled(pADCx) == 1UL)
{
/* Set ADC group regular trigger source to SW start to ensure to not */
/* have an external trigger event occurring during the conversion stop */
/* ADC disable process. */
LL_ADC_REG_SetTriggerSource(pADCx, LL_ADC_REG_TRIG_SOFTWARE);
/* Stop potential ADC conversion on going on ADC group regular. */
if (LL_ADC_REG_IsConversionOngoing(pADCx) != 0UL)
{
if (LL_ADC_REG_IsStopConversionOngoing(pADCx) == 0UL)
{
LL_ADC_REG_StopConversion(pADCx);
}
}
/* Wait for ADC conversions are effectively stopped */
timeout_cpu_cycles = ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES;
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
while ((LL_ADC_REG_IsStopConversionOngoing(pADCx)
| LL_ADC_INJ_IsStopConversionOngoing(pADCx)) == 1UL)
{
timeout_cpu_cycles--;
if (timeout_cpu_cycles == 0UL)
{
/* Time-out error */
status = ERROR;
break;
}
}
}
else
{
while (LL_ADC_REG_IsStopConversionOngoing(pADCx) == 1UL)
{
timeout_cpu_cycles--;
if (timeout_cpu_cycles == 0UL)
{
/* Time-out error */
status = ERROR;
}
}
}
/* Disable the ADC instance */
LL_ADC_Disable(pADCx);
/* Wait for ADC instance is effectively disabled */
timeout_cpu_cycles = ADC_TIMEOUT_DISABLE_CPU_CYCLES;
while (LL_ADC_IsDisableOngoing(pADCx) == 1UL)
{
timeout_cpu_cycles--;
if (timeout_cpu_cycles == 0UL)
{
/* Time-out error */
status = ERROR;
}
}
}
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
CLEAR_BIT(pADCx->IER,
(LL_ADC_IT_AWD3
| LL_ADC_IT_AWD2
| LL_ADC_IT_AWD1
| LL_ADC_IT_OVR
| LL_ADC_IT_JEOS
| LL_ADC_IT_JEOC
| LL_ADC_IT_EOS
| LL_ADC_IT_EOC
| LL_ADC_IT_EOSMP
| LL_ADC_IT_ADRDY
)
);
/* Reset register ISR */
SET_BIT(pADCx->ISR,
(LL_ADC_FLAG_AWD3
| LL_ADC_FLAG_AWD2
| LL_ADC_FLAG_AWD1
| LL_ADC_FLAG_OVR
| LL_ADC_FLAG_JEOS
| LL_ADC_FLAG_JEOC
| LL_ADC_FLAG_EOS
| LL_ADC_FLAG_EOC
| LL_ADC_FLAG_EOSMP
| LL_ADC_FLAG_ADRDY
)
);
/* Reset register CR */
/* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode */
/* "read-set": no direct reset applicable. */
CLEAR_BIT(pADCx->CR, ADC_CR_ADVREGEN);
SET_BIT(pADCx->CR, ADC_CR_DEEPPWD);
/* Reset register CFGR */
CLEAR_BIT(pADCx->CFGR1, ADC_CFGR1_AWD1CH | ADC_CFGR1_JAUTO | ADC_CFGR1_JAWD1EN |
ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL | ADC_CFGR1_JDISCEN |
ADC_CFGR1_DISCNUM | ADC_CFGR1_DISCEN | ADC_CFGR1_AUTDLY |
ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD |
ADC_CFGR1_EXTEN | ADC_CFGR1_EXTSEL |
ADC_CFGR1_RES | ADC_CFGR1_DMNGT);
/* Reset register CFGR2 */
CLEAR_BIT(pADCx->CFGR2, ADC_CFGR2_ROVSM | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS |
ADC_CFGR2_OVSR | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE);
/* Reset register SMPR1 */
CLEAR_BIT(pADCx->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(pADCx->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 LTR1 and HTR1 */
CLEAR_BIT(pADCx->LTR1, ADC_LTR_LT);
SET_BIT(pADCx->HTR1, ADC_HTR_HT);
/* Reset register LTR2 and HTR2*/
CLEAR_BIT(pADCx->LTR2, ADC_LTR_LT);
SET_BIT(pADCx->HTR2, ADC_HTR_HT);
/* Reset register LTR3 and HTR3 */
CLEAR_BIT(pADCx->LTR3, ADC_LTR_LT);
SET_BIT(pADCx->HTR3, ADC_HTR_HT);
/* Reset register SQR1 */
CLEAR_BIT(pADCx->SQR1, ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 | ADC_SQR1_SQ1 | ADC_SQR1_L);
/* Reset register SQR2 */
CLEAR_BIT(pADCx->SQR2, ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 | ADC_SQR2_SQ6 | ADC_SQR2_SQ5);
/* Reset register SQR3 */
CLEAR_BIT(pADCx->SQR3, ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 | ADC_SQR3_SQ11 | ADC_SQR3_SQ10);
/* Reset register SQR4 */
CLEAR_BIT(pADCx->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15);
/* Reset register JSQR */
CLEAR_BIT(pADCx->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 */
/* bits in access mode read only, no direct reset applicable*/
/* Reset register OFR1 */
CLEAR_BIT(pADCx->OFR1, ADC_OFR1_SSAT | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1);
/* Reset register OFR2 */
CLEAR_BIT(pADCx->OFR2, ADC_OFR2_SSAT | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2);
/* Reset register OFR3 */
CLEAR_BIT(pADCx->OFR3, ADC_OFR3_SSAT | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3);
/* Reset register OFR4 */
CLEAR_BIT(pADCx->OFR4, ADC_OFR4_SSAT | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4);
/* Reset register GCOMP */
CLEAR_BIT(pADCx->GCOMP, ADC_GCOMP_GCOMP | ADC_GCOMP_GCOMPCOEFF);
/* Reset registers JDR1, JDR2, JDR3, JDR4 */
/* bits in access mode read only, no direct reset applicable*/
/* Reset register AWD2CR */
CLEAR_BIT(pADCx->AWD2CR, ADC_AWD2CR_AWD2CH);
/* Reset register AWD3CR */
CLEAR_BIT(pADCx->AWD3CR, ADC_AWD3CR_AWD3CH);
/* Reset register DIFSEL */
CLEAR_BIT(pADCx->DIFSEL, ADC_DIFSEL_DIFSEL);
/* Reset register PCSEL */
CLEAR_BIT(pADCx->PCSEL, ADC_PCSEL_PCSEL);
/* Reset register CALFACT */
CLEAR_BIT(pADCx->CALFACT, ADC_CALFACT_CAPTURE_COEF | ADC_CALFACT_LATCH_COEF);
}
else
{
/* Check whether ADC state is compliant with expected state */
if (READ_BIT(pADCx->CR, (ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN)) == 0UL)
{
/* ========== Reset ADC registers ========== */
/* Reset register IER */
CLEAR_BIT(pADCx->IER,
(LL_ADC_IT_ADRDY
| LL_ADC_IT_EOC
| LL_ADC_IT_EOS
| LL_ADC_IT_OVR
| LL_ADC_IT_EOSMP
| LL_ADC_IT_AWD1
| LL_ADC_IT_AWD2
| LL_ADC_IT_AWD3
| LL_ADC_IT_EOCAL
| LL_ADC_IT_LDORDY
)
);
/* Reset register ISR */
SET_BIT(pADCx->ISR,
(LL_ADC_FLAG_ADRDY
| LL_ADC_FLAG_EOC
| LL_ADC_FLAG_EOS
| LL_ADC_FLAG_OVR
| LL_ADC_FLAG_EOSMP
| LL_ADC_FLAG_AWD1
| LL_ADC_FLAG_AWD2
| LL_ADC_FLAG_AWD3
| LL_ADC_FLAG_EOCAL
| LL_ADC_FLAG_LDORDY
)
);
/* Reset register CR */
/* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode */
/* "read-set": no direct reset applicable. */
CLEAR_BIT(pADCx->CR, ADC_CR_ADVREGEN);
/* Reset register CFGR1 */
CLEAR_BIT(pADCx->CFGR1,
(ADC_CFGR1_AWD1CH | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL | ADC_CFGR1_DISCEN
| ADC4_CFGR1_WAIT | ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD
| ADC_CFGR1_EXTEN | ADC_CFGR1_EXTSEL | ADC4_CFGR1_ALIGN | ADC_CFGR1_RES
| ADC4_CFGR1_SCANDIR | ADC4_CFGR1_DMACFG | ADC4_CFGR1_DMAEN)
);
/* Reset register CFGR2 */
/* Note: Update of ADC clock mode is conditioned to ADC state disabled: */
/* already done above. */
CLEAR_BIT(pADCx->CFGR2,
(ADC_CFGR2_TROVS | ADC_CFGR2_OVSS | ADC4_CFGR2_OVSR
| ADC_CFGR2_ROVSE | ADC4_CFGR2_LFTRIG)
);
/* Reset register SMPR */
CLEAR_BIT(pADCx->SMPR1, ADC4_SMPR_SMP1 | ADC4_SMPR_SMP2 | ADC4_SMPR_SMPSEL);
/* Reset register TR1 */
MODIFY_REG(pADCx->AWD1TR, ADC_AWD1TR_HT1 | ADC_AWD1TR_LT1, ADC_AWD1TR_HT1);
/* Reset register TR2 */
MODIFY_REG(pADCx->AWD2TR, ADC_AWD2TR_HT2 | ADC_AWD2TR_LT2, ADC_AWD2TR_HT2);
/* Reset register TR3 */
MODIFY_REG(pADCx->AWD3TR, ADC_AWD3TR_HT3 | ADC_AWD3TR_LT3, ADC_AWD3TR_HT3);
/* Reset register CHSELR */
CLEAR_BIT(pADCx->CHSELR,
(ADC_CHSELR_CHSEL23 | ADC_CHSELR_CHSEL22 | ADC_CHSELR_CHSEL21 | ADC_CHSELR_CHSEL20
| ADC_CHSELR_CHSEL19 | ADC_CHSELR_CHSEL18 | ADC_CHSELR_CHSEL17 | ADC_CHSELR_CHSEL16
| ADC_CHSELR_CHSEL15 | ADC_CHSELR_CHSEL14 | ADC_CHSELR_CHSEL13 | ADC_CHSELR_CHSEL12
| ADC_CHSELR_CHSEL11 | ADC_CHSELR_CHSEL10 | ADC_CHSELR_CHSEL9 | ADC_CHSELR_CHSEL8
| ADC_CHSELR_CHSEL7 | ADC_CHSELR_CHSEL6 | ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL4
| ADC_CHSELR_CHSEL3 | ADC_CHSELR_CHSEL2 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL0)
);
/* Reset register DR */
/* bits in access mode read only, no direct reset applicable */
/* Reset register CALFACT */
CLEAR_BIT(pADCx->CALFACT, ADC4_CALFACT_CALFACT);
/* Reset register CCR */
CLEAR_BIT(ADC4_COMMON->CCR, ADC_CCR_VBATEN | ADC_CCR_VSENSEEN | ADC_CCR_VREFEN | ADC_CCR_PRESC);
}
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. */
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 families).
* 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 families. 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 pADCx 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 *pADCx, LL_ADC_InitTypeDef *pADC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(pADCx));
assert_param(IS_LL_ADC_RESOLUTION(pADC_InitStruct->Resolution));
assert_param(IS_LL_ADC_LOW_POWER(pADC_InitStruct->LowPowerMode));
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
assert_param(IS_LL_ADC_LEFT_BIT_SHIFT(pADC_InitStruct->LeftBitShift));
}
else
{
assert_param(IS_LL_ADC_DATA_ALIGN(pADC_InitStruct->DataAlignment));
}
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if (LL_ADC_IsEnabled(pADCx) == 0UL)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC instance */
/* - Set ADC data resolution */
/* - Set ADC conversion data alignment */
/* - Set ADC low power mode */
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_RES | ADC4_CFGR1_WAIT, pADC_InitStruct->Resolution | pADC_InitStruct->LowPowerMode);
MODIFY_REG(pADCx->CFGR2, ADC_CFGR2_LSHIFT, pADC_InitStruct->LeftBitShift);
}
else
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_RES | ADC4_CFGR1_ALIGN | ADC4_CFGR1_WAIT,
__LL_ADC_RESOLUTION_ADC1_TO_ADC4(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 pADCx ADC instance
* @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(ADC_TypeDef *pADCx, LL_ADC_InitTypeDef *pADC_InitStruct)
{
/* Set pADC_InitStruct fields to default values */
/* Set fields of ADC instance */
pADC_InitStruct->LowPowerMode = LL_ADC_LP_MODE_NONE;
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
pADC_InitStruct->Resolution = LL_ADC_RESOLUTION_14B;
pADC_InitStruct->LeftBitShift = LL_ADC_LEFT_BIT_SHIFT_NONE;
}
else
{
pADC_InitStruct->Resolution = LL_ADC_RESOLUTION_12B;
pADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT;
}
}
/**
* @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 families. 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 pADCx 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 *pADCx, LL_ADC_REG_InitTypeDef *pADC_RegInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(pADCx));
if (pADCx == ADC1)
{
assert_param(IS_LL_ADC_REG_TRIG_SOURCE(pADC_RegInitStruct->TriggerSource));
assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(pADC_RegInitStruct->SequencerLength));
assert_param(IS_LL_ADC_REG_DATA_TRANSFER_MODE(pADC_RegInitStruct->DataTransferMode));
}
else
{
assert_param(IS_LL_ADC4_REG_TRIG_SOURCE(pADC_RegInitStruct->TriggerSource));
assert_param(IS_LL_ADC4_REG_SEQ_SCAN_LENGTH(pADC_RegInitStruct->SequencerLength));
assert_param(IS_LL_ADC_REG_DMA_TRANSFER(pADC_RegInitStruct->DMATransfer));
if ((LL_ADC_REG_GetSequencerConfigurable(pADCx) == LL_ADC_REG_SEQ_FIXED)
|| (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));
}
}
if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(pADC_RegInitStruct->SequencerDiscont));
}
assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(pADC_RegInitStruct->ContinuousMode));
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(pADCx) == 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 when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_EXTSEL
| ADC_CFGR1_EXTEN
| ADC_CFGR1_DISCEN
| ADC_CFGR1_DISCNUM
| ADC_CFGR1_CONT
| ADC_CFGR1_DMNGT
| ADC_CFGR1_OVRMOD
,
pADC_RegInitStruct->TriggerSource
| pADC_RegInitStruct->SequencerDiscont
| pADC_RegInitStruct->ContinuousMode
| pADC_RegInitStruct->DataTransferMode
| pADC_RegInitStruct->Overrun
);
}
else
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_EXTSEL
| ADC_CFGR1_EXTEN
| ADC_CFGR1_DISCEN
| ADC_CFGR1_DISCNUM
| ADC_CFGR1_CONT
| ADC_CFGR1_DMNGT
| ADC_CFGR1_OVRMOD
,
pADC_RegInitStruct->TriggerSource
| LL_ADC_REG_SEQ_DISCONT_DISABLE
| pADC_RegInitStruct->ContinuousMode
| pADC_RegInitStruct->DataTransferMode
| pADC_RegInitStruct->Overrun
);
}
}
else
{
if ((LL_ADC_REG_GetSequencerConfigurable(pADCx) == LL_ADC_REG_SEQ_FIXED)
|| (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
)
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_EXTSEL
| ADC_CFGR1_EXTEN
| ADC_CFGR1_DISCEN
| ADC_CFGR1_CONT
| ADC4_CFGR1_DMAEN
| ADC4_CFGR1_DMACFG
| ADC_CFGR1_OVRMOD
,
pADC_RegInitStruct->TriggerSource
| pADC_RegInitStruct->SequencerDiscont
| pADC_RegInitStruct->ContinuousMode
| pADC_RegInitStruct->DMATransfer
| pADC_RegInitStruct->Overrun
);
}
else
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_EXTSEL
| ADC_CFGR1_EXTEN
| ADC_CFGR1_DISCEN
| ADC_CFGR1_CONT
| ADC4_CFGR1_DMAEN
| ADC4_CFGR1_DMACFG
| ADC_CFGR1_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 */
if (pADCx == ADC4)
{
if (LL_ADC_REG_GetSequencerConfigurable(pADCx) != LL_ADC_REG_SEQ_FIXED)
{
LL_ADC_REG_SetSequencerLength(pADCx, pADC_RegInitStruct->SequencerLength);
}
}
else
{
LL_ADC_REG_SetSequencerLength(pADCx, 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 pADCx ADC instance
* @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(ADC_TypeDef *pADCx, 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 when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */
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->Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN;
if (pADCx != ADC4) /* ADC1 or ADC2 */
{
pADC_RegInitStruct->DataTransferMode = LL_ADC_REG_DR_TRANSFER;
}
else
{
pADC_RegInitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE_ADC4;
}
}
/**
* @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 families. 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();
* @param pADCx 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 *pADCx, LL_ADC_INJ_InitTypeDef *pADC_InjInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(pADCx));
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(pADCx) == 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 when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_INJ_StartConversionExtTrig(). */
if (pADC_InjInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_JDISCEN | ADC_CFGR1_JAUTO,
pADC_InjInitStruct->SequencerDiscont | pADC_InjInitStruct->TrigAuto
);
}
else
{
MODIFY_REG(pADCx->CFGR1,
ADC_CFGR1_JDISCEN | ADC_CFGR1_JAUTO,
LL_ADC_REG_SEQ_DISCONT_DISABLE | pADC_InjInitStruct->TrigAuto
);
}
MODIFY_REG(pADCx->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 || ADC4 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_adc.c
|
C
|
apache-2.0
| 52,298
|
/**
******************************************************************************
* @file stm32u5xx_ll_comp.c
* @author MCD Application Team
* @brief COMP LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_comp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (COMP1) || defined (COMP2)
/** @addtogroup COMP_LL COMP
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup COMP_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of COMP hierarchical scope: */
/* COMP instance. */
#define IS_LL_COMP_POWER_MODE(__POWER_MODE__) \
(((__POWER_MODE__) == LL_COMP_POWERMODE_HIGHSPEED) \
|| ((__POWER_MODE__) == LL_COMP_POWERMODE_MEDIUMSPEED) \
|| ((__POWER_MODE__) == LL_COMP_POWERMODE_ULTRALOWPOWER) \
)
/* 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. */
#define IS_LL_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) \
(((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO1) \
|| ((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO2) \
|| ((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO3) \
)
/* 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. */
#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_DAC1_CH1) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) \
)
#define IS_LL_COMP_INPUT_HYSTERESIS(__INPUT_HYSTERESIS__) \
(((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_NONE) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_LOW) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_MEDIUM) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_HIGH) \
)
#define IS_LL_COMP_OUTPUT_POLARITY(__POLARITY__) \
(((__POLARITY__) == LL_COMP_OUTPUTPOL_NONINVERTED) \
|| ((__POLARITY__) == LL_COMP_OUTPUTPOL_INVERTED) \
)
#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__OUTPUT_BLANKING_SOURCE__) \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup COMP_LL_Exported_Functions
* @{
*/
/** @addtogroup COMP_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected COMP instance
* to their default reset values.
* @note If comparator is locked, de-initialization by software is
* not possible.
* The only way to unlock the comparator is a device hardware reset.
* @param COMPx COMP instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: COMP registers are de-initialized
* - ERROR: COMP registers are not de-initialized
*/
ErrorStatus LL_COMP_DeInit(COMP_TypeDef *COMPx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(COMPx));
/* Note: Hardware constraint (refer to description of this function): */
/* COMP instance must not be locked. */
if (LL_COMP_IsLocked(COMPx) == 0UL)
{
LL_COMP_WriteReg(COMPx, CSR, 0x00000000UL);
}
else
{
/* Comparator instance is locked: de-initialization by software is */
/* not possible. */
/* The only way to unlock the comparator is a device hardware reset. */
status = ERROR;
}
return status;
}
/**
* @brief Initialize some features of COMP instance.
* @note This function configures features of the selected COMP instance.
* Some features are also available at scope COMP common instance
* (common to several COMP instances).
* Refer to functions having argument "COMPxy_COMMON" as parameter.
* @param COMPx COMP instance
* @param COMP_InitStruct Pointer to a @ref LL_COMP_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: COMP registers are initialized
* - ERROR: COMP registers are not initialized
*/
ErrorStatus LL_COMP_Init(COMP_TypeDef *COMPx, LL_COMP_InitTypeDef *COMP_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(COMPx));
assert_param(IS_LL_COMP_POWER_MODE(COMP_InitStruct->PowerMode));
assert_param(IS_LL_COMP_INPUT_PLUS(COMPx, COMP_InitStruct->InputPlus));
assert_param(IS_LL_COMP_INPUT_MINUS(COMPx, COMP_InitStruct->InputMinus));
assert_param(IS_LL_COMP_INPUT_HYSTERESIS(COMP_InitStruct->InputHysteresis));
assert_param(IS_LL_COMP_OUTPUT_POLARITY(COMP_InitStruct->OutputPolarity));
assert_param(IS_LL_COMP_OUTPUT_BLANKING_SOURCE(COMP_InitStruct->OutputBlankingSource));
/* Note: Hardware constraint (refer to description of this function) */
/* COMP instance must not be locked. */
if (LL_COMP_IsLocked(COMPx) == 0UL)
{
/* Configuration of comparator instance : */
/* - PowerMode */
/* - InputPlus */
/* - InputMinus */
/* - InputHysteresis */
/* - OutputPolarity */
/* - OutputBlankingSource */
MODIFY_REG(COMPx->CSR,
COMP_CSR_PWRMODE
| COMP_CSR_INPSEL
| COMP_CSR_INMSEL
| COMP_CSR_HYST
| COMP_CSR_POLARITY
| COMP_CSR_BLANKSEL
,
COMP_InitStruct->PowerMode
| COMP_InitStruct->InputPlus
| COMP_InitStruct->InputMinus
| COMP_InitStruct->InputHysteresis
| COMP_InitStruct->OutputPolarity
| COMP_InitStruct->OutputBlankingSource
);
}
else
{
/* Initialization error: COMP instance is locked. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_COMP_InitTypeDef field to default value.
* @param COMP_InitStruct Pointer to a @ref LL_COMP_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_COMP_StructInit(LL_COMP_InitTypeDef *COMP_InitStruct)
{
/* Set COMP_InitStruct fields to default values */
COMP_InitStruct->PowerMode = LL_COMP_POWERMODE_ULTRALOWPOWER;
COMP_InitStruct->InputPlus = LL_COMP_INPUT_PLUS_IO1;
COMP_InitStruct->InputMinus = LL_COMP_INPUT_MINUS_VREFINT;
COMP_InitStruct->InputHysteresis = LL_COMP_HYSTERESIS_NONE;
COMP_InitStruct->OutputPolarity = LL_COMP_OUTPUTPOL_NONINVERTED;
COMP_InitStruct->OutputBlankingSource = LL_COMP_BLANKINGSRC_NONE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* COMP1 || COMP2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_comp.c
|
C
|
apache-2.0
| 10,069
|
/**
******************************************************************************
* @file stm32u5xx_ll_cordic.c
* @author MCD Application Team
* @brief CORDIC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_cordic.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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(CORDIC_TypeDef *CORDICx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_CORDIC_ALL_INSTANCE(CORDICx));
if (CORDICx == CORDIC)
{
/* Force CORDIC reset */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_CORDIC);
/* Release CORDIC reset */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_CORDIC);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(CORDIC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_cordic.c
|
C
|
apache-2.0
| 2,525
|
/**
******************************************************************************
* @file stm32u5xx_ll_crc.c
* @author MCD Application Team
* @brief CRC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_crc.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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(CRC_TypeDef *CRCx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_CRC_ALL_INSTANCE(CRCx));
if (CRCx == CRC)
{
/* Force CRC reset */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_CRC);
/* Release CRC reset */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_CRC);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (CRC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_crc.c
|
C
|
apache-2.0
| 2,460
|
/**
******************************************************************************
* @file stm32u5xx_ll_crs.h
* @author MCD Application Team
* @brief CRS LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_crs.h"
#include "stm32u5xx_ll_bus.h"
/** @addtogroup STM32U5xx_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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_crs.c
|
C
|
apache-2.0
| 2,043
|
/**
******************************************************************************
* @file stm32u5xx_ll_dac.c
* @author MCD Application Team
* @brief DAC LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_dac.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined(DAC1)
/** @addtogroup DAC_LL DAC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DAC_LL_Private_Macros
* @{
*/
#define IS_LL_DAC_CHANNEL(__DAC_CHANNEL__) \
( ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
|| ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \
)
#define IS_LL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM5_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_LPTIM1_CH1) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_LPTIM3_CH1) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \
( ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_MODE__, __WAVE_AUTO_GENERATION_CONFIG__) \
( (((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \
&& ( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BIT0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS11_0)) \
) \
||(((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \
&& ( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_3) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_7) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_15) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_31) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_63) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_127) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_255) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_511) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1023) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_2047) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_4095)) \
) \
)
#define IS_LL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \
( ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_ENABLE) \
|| ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_DISABLE) \
)
#define IS_LL_DAC_OUTPUT_CONNECTION(__OUTPUT_CONNECTION__) \
( ((__OUTPUT_CONNECTION__) == LL_DAC_OUTPUT_CONNECT_GPIO) \
|| ((__OUTPUT_CONNECTION__) == LL_DAC_OUTPUT_CONNECT_INTERNAL) \
)
#define IS_LL_DAC_OUTPUT_MODE(__OUTPUT_MODE__) \
( ((__OUTPUT_MODE__) == LL_DAC_OUTPUT_MODE_NORMAL) \
|| ((__OUTPUT_MODE__) == LL_DAC_OUTPUT_MODE_SAMPLE_AND_HOLD) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DAC_LL_Exported_Functions
* @{
*/
/** @addtogroup DAC_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected DAC instance
* to their default reset values.
* @param DACx DAC instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_DAC_DeInit(DAC_TypeDef *DACx)
{
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
#ifdef DAC1
/* Force reset of DAC clock */
LL_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_DAC1);
/* Release reset of DAC clock */
LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_DAC1);
#endif /* DAC1 */
return SUCCESS;
}
/**
* @brief Initialize some features of DAC channel.
* @note @ref LL_DAC_Init() aims to ease basic configuration of a DAC channel.
* Leaving it ready to be enabled and output:
* a level by calling one of
* @ref LL_DAC_ConvertData12RightAligned
* @ref LL_DAC_ConvertData12LeftAligned
* @ref LL_DAC_ConvertData8RightAligned
* or one of the supported autogenerated wave.
* @note This function allows configuration of:
* - Output mode
* - Trigger
* - Wave generation
* @note The setting of these parameters by function @ref LL_DAC_Init()
* is conditioned to DAC state:
* DAC channel must be disabled.
* @param DACx DAC instance
* @param DAC_Channel This parameter can be one of the following values:
* @arg @ref LL_DAC_CHANNEL_1
* @arg @ref LL_DAC_CHANNEL_2
* @param DAC_InitStruct Pointer to a @ref LL_DAC_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are initialized
* - ERROR: DAC registers are not initialized
*/
ErrorStatus LL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef *DAC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
assert_param(IS_LL_DAC_CHANNEL(DAC_Channel));
assert_param(IS_LL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource));
assert_param(IS_LL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer));
assert_param(IS_LL_DAC_OUTPUT_CONNECTION(DAC_InitStruct->OutputConnection));
assert_param(IS_LL_DAC_OUTPUT_MODE(DAC_InitStruct->OutputMode));
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration));
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGeneration,
DAC_InitStruct->WaveAutoGenerationConfig));
}
/* Note: Hardware constraint (refer to description of this function) */
/* DAC instance must be disabled. */
if (LL_DAC_IsEnabled(DACx, DAC_Channel) == 0UL)
{
/* Configuration of DAC channel: */
/* - TriggerSource */
/* - WaveAutoGeneration */
/* - OutputBuffer */
/* - OutputConnection */
/* - OutputMode */
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
MODIFY_REG(DACx->CR,
(DAC_CR_TSEL1
| DAC_CR_WAVE1
| DAC_CR_MAMP1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
(DAC_InitStruct->TriggerSource
| DAC_InitStruct->WaveAutoGeneration
| DAC_InitStruct->WaveAutoGenerationConfig
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
else
{
MODIFY_REG(DACx->CR,
(DAC_CR_TSEL1
| DAC_CR_WAVE1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
(DAC_InitStruct->TriggerSource
| LL_DAC_WAVE_AUTO_GENERATION_NONE
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
MODIFY_REG(DACx->MCR,
(DAC_MCR_MODE1_1
| DAC_MCR_MODE1_0
| DAC_MCR_MODE1_2
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
(DAC_InitStruct->OutputBuffer
| DAC_InitStruct->OutputConnection
| DAC_InitStruct->OutputMode
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
else
{
/* Initialization error: DAC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_DAC_InitTypeDef field to default value.
* @param DAC_InitStruct pointer to a @ref LL_DAC_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_DAC_StructInit(LL_DAC_InitTypeDef *DAC_InitStruct)
{
/* Set DAC_InitStruct fields to default values */
DAC_InitStruct->TriggerSource = LL_DAC_TRIG_SOFTWARE;
DAC_InitStruct->WaveAutoGeneration = LL_DAC_WAVE_AUTO_GENERATION_NONE;
/* Note: Parameter discarded if wave auto generation is disabled, */
/* set anyway to its default value. */
DAC_InitStruct->WaveAutoGenerationConfig = LL_DAC_NOISE_LFSR_UNMASK_BIT0;
DAC_InitStruct->OutputBuffer = LL_DAC_OUTPUT_BUFFER_ENABLE;
DAC_InitStruct->OutputConnection = LL_DAC_OUTPUT_CONNECT_GPIO;
DAC_InitStruct->OutputMode = LL_DAC_OUTPUT_MODE_NORMAL;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* DAC1 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_dac.c
|
C
|
apache-2.0
| 13,141
|
/**
******************************************************************************
* @file stm32u5xx_ll_dlyb.c
* @author MCD Application Team
* @brief DelayBlock Low Layer HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the DelayBlock peripheral:
* + input clock frequency
* + up to 12 oversampling phases
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 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
==============================================================================
##### DelayBlock peripheral features #####
==============================================================================
[..] The DelayBlock is used to generate an Output clock which is de-phased from the Input
clock. The phase of the Output clock is programmed by FW. The Output clock is then used
to clock the receive data in i.e. a SDMMC, OSPI or QSPI interface.
The delay is Voltage and Temperature dependent, which may require FW to do re-tuning
and recenter the Output clock phase to the receive data.
[..] The DelayBlock features include the following:
(+) Input clock frequency.
(+) Up to 12 oversampling phases.
##### How to use this driver #####
==============================================================================
[..]
This driver is a considered as a driver of service for external devices drivers
that interfaces with the DELAY peripheral.
The LL_DLYB_SetDelay() function, configure the Delay value configured on SEL and UNIT.
The LL_DLYB_GetDelay() function, return the Delay value configured on SEL and UNIT.
The LL_DLYB_GetClockPeriod()function, get the clock period.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
/** @defgroup DLYB_LL DLYB
* @brief DLYB LL module driver.
* @{
*/
#if defined(HAL_SD_MODULE_ENABLED) || defined(HAL_OSPI_MODULE_ENABLED) || defined(HAL_XSPI_MODULE_ENABLED)
/**
@cond 0
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define DLYB_TIMEOUT 0xFFU
#define DLYB_LNG_10_0_MASK 0x07FF0000U
#define DLYB_LNG_11_10_MASK 0x0C000000U
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/**
@endcond
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DLYB_LL_Exported_Functions
* @brief Configuration and control functions
*
@verbatim
===============================================================================
##### Control functions #####
===============================================================================
[..] This section provides functions allowing to
(+) Control the DLYB.
@endverbatim
* @{
*/
/** @addtogroup DLYB_Control_Functions DLYB Control functions
* @{
*/
/**
* @brief Set the Delay value configured on SEL and UNIT.
* @param DLYBx: Pointer to DLYB instance.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: the Delay value is set.
* - ERROR: the Delay value is not set.
*/
void LL_DLYB_SetDelay(DLYB_TypeDef *DLYBx, LL_DLYB_CfgTypeDef *pdlyb_cfg)
{
/* Check the DelayBlock instance */
assert_param(IS_DLYB_ALL_INSTANCE(DLYBx));
/* Enable the length sampling */
SET_BIT(DLYBx->CR, DLYB_CR_SEN);
/* Update the UNIT and SEL field */
DLYBx->CFGR = (pdlyb_cfg->PhaseSel) | ((pdlyb_cfg->Units) << DLYB_CFGR_UNIT_Pos);
/* Disable the length sampling */
CLEAR_BIT(DLYBx->CR, DLYB_CR_SEN);
}
/**
* @brief Get the Delay value configured on SEL and UNIT.
* @param DLYBx: Pointer to DLYB instance.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: the Delay value is received.
* - ERROR: the Delay value is not received.
*/
void LL_DLYB_GetDelay(DLYB_TypeDef *DLYBx, LL_DLYB_CfgTypeDef *pdlyb_cfg)
{
/* Check the DelayBlock instance */
assert_param(IS_DLYB_ALL_INSTANCE(DLYBx));
/* Fill the DelayBlock configuration structure with SEL and UNIT value */
pdlyb_cfg->Units = ((DLYBx->CFGR & DLYB_CFGR_UNIT) >> DLYB_CFGR_UNIT_Pos);
pdlyb_cfg->PhaseSel = (DLYBx->CFGR & DLYB_CFGR_SEL);
}
/**
* @brief Get the clock period.
* @param DLYBx: Pointer to DLYB instance.
* @param pdlyb_cfg: Pointer to DLYB configuration structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: there is a valid period detected and stored in pdlyb_cfg.
* - ERROR: there is no valid period detected.
*/
uint32_t LL_DLYB_GetClockPeriod(DLYB_TypeDef *DLYBx, LL_DLYB_CfgTypeDef *pdlyb_cfg)
{
uint32_t i = 0U;
uint32_t nb ;
uint32_t lng ;
uint32_t tickstart;
/* Check the DelayBlock instance */
assert_param(IS_DLYB_ALL_INSTANCE(DLYBx));
/* Enable the length sampling */
SET_BIT(DLYBx->CR, DLYB_CR_SEN);
/* Delay line length detection */
while (i < DLYB_MAX_UNIT)
{
/* Set the Delay of the UNIT(s)*/
DLYBx->CFGR = DLYB_MAX_SELECT | (i << DLYB_CFGR_UNIT_Pos);
/* Waiting for a LNG valid value */
tickstart = HAL_GetTick();
while ((DLYBx->CFGR & DLYB_CFGR_LNGF) == 0U)
{
if ((HAL_GetTick() - tickstart) >= DLYB_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
if ((DLYBx->CFGR & DLYB_CFGR_LNGF) == 0U)
{
return (uint32_t) HAL_TIMEOUT;
}
}
}
if ((DLYBx->CFGR & DLYB_LNG_10_0_MASK) != 0U)
{
if ((DLYBx->CFGR & (DLYB_CFGR_LNG_11 | DLYB_CFGR_LNG_10)) != DLYB_LNG_11_10_MASK)
{
/* Delay line length is configured to one input clock period*/
break;
}
}
i++;
}
if (DLYB_MAX_UNIT != i)
{
/* Determine how many unit delays (nb) span one input clock period */
lng = (DLYBx->CFGR & DLYB_CFGR_LNG) >> 16U;
nb = 10U;
while ((nb > 0U) && ((lng >> nb) == 0U))
{
nb--;
}
if (nb != 0U)
{
pdlyb_cfg->PhaseSel = nb ;
pdlyb_cfg->Units = i ;
/* Disable the length sampling */
DLYBx->CR = DLYB_CR_SEN;
return (uint32_t)SUCCESS;
}
}
/* Disable the length sampling */
DLYBx->CR = DLYB_CR_SEN;
return (uint32_t)ERROR;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_SD_MODULE_ENABLED || HAL_OSPI_MODULE_ENABLED || HAL_XSPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_dlyb.c
|
C
|
apache-2.0
| 7,459
|
/**
******************************************************************************
* @file stm32u5xx_ll_dma.c
* @author MCD Application Team
* @brief DMA LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_dma.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if (defined (GPDMA1) || defined (LPDMA1))
/** @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) == 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))) || \
(((INSTANCE) == LPDMA1) && \
(((Channel) == LL_DMA_CHANNEL_0) || \
((Channel) == LL_DMA_CHANNEL_1) || \
((Channel) == LL_DMA_CHANNEL_2) || \
((Channel) == LL_DMA_CHANNEL_3) || \
((Channel) == LL_DMA_CHANNEL_ALL))))
#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) == 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_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))
#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))
#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)
#if defined (LL_GPDMA1_REQUEST_ADC2)
#define IS_LL_DMA_REQUEST_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_REQUEST_ADC2)
#else
#define IS_LL_DMA_REQUEST_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_REQUEST_LPTIM3_UE)
#endif /* LL_GPDMA1_REQUEST_ADC2 */
#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_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_GPDMA_2D_NODE) || \
((__VALUE__) == LL_DMA_GPDMA_LINEAR_NODE) || \
((__VALUE__) == LL_DMA_LPDMA_LINEAR_NODE))
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
#define IS_LL_DMA_CHANNEL_SRC_SEC(__VALUE__) (((__VALUE__) == LL_DMA_CHANNEL_SRC_NSEC) || \
((__VALUE__) == LL_DMA_CHANNEL_SRC_SEC))
#define IS_LL_DMA_CHANNEL_DEST_SEC(__VALUE__) (((__VALUE__) == LL_DMA_CHANNEL_DEST_NSEC) || \
((__VALUE__) == LL_DMA_CHANNEL_DEST_SEC))
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/**
* @}
*/
/* 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_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_LPDMA1);
/* Release reset of DMA clock */
LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_LPDMA1);
}
}
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);
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
LL_DMA_DisableChannelSecure(DMAx, Channel);
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
}
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));
/* Check DMA instance */
if (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_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
* LinkAllocatedPort field is not supported by LPDMA channels.
* - 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
* DestAllocatedPort field is not supported by LPDMA channels.
* - DestHWordExchange: DMA_CTR1_DHX bit
* DestHWordExchange field is not supported by LPDMA channels.
* - DestByteExchange: DMA_CTR1_DBX bit
* DestByteExchange field is not supported by LPDMA channels.
* - DestIncMode: DMA_CTR1_DINC bit
* - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits
* - SrcAllocatedPort: DMA_CTR1_SAP bit
* SrcAllocatedPort field is not supported by LPDMA channels.
* - SrcByteExchange: DMA_CTR1_SBX bit
* SrcByteExchange field is not supported by LPDMA channels.
* - DataAlignment: DMA_CTR1_PAM [12:11] bits
* DataAlignment field is reduced to one bit by LPDMA channels.
* - SrcIncMode: DMA_CTR1_SINC bit
* - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits
* - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits
* SrcBurstLength field is not supported by LPDMA channels.
* - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits
* DestBurstLength field is not supported by LPDMA channels.
*/
LL_DMA_ConfigTransfer(DMAx, Channel, DMA_InitStruct->DestAllocatedPort | \
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_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
* - Direction: DMA_CTR2_DREQ bit
* - Direction: DMA_CTR2_SWREQ bit
* Direction field is reduced to one bit for LPDMA channels (SWREQ).
* - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits
* TriggerSelection field is reduced to 5 bits for LPDMA channels.
* - Request: DMA_CTR2_REQSEL [6:0] bits
* Request field is reduced to 5 bits for LPDMA channels.
*/
LL_DMA_ConfigChannelTransfer(DMAx, Channel, DMA_InitStruct->TransferEventMode | \
DMA_InitStruct->TriggerPolarity | \
DMA_InitStruct->BlkHWRequest | \
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->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->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_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 */
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
DMA_InitNodeStruct->DestSecure = LL_DMA_CHANNEL_DEST_NSEC;
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
DMA_InitNodeStruct->DestAllocatedPort = LL_DMA_DEST_ALLOCATED_PORT0;
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;
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
DMA_InitNodeStruct->SrcSecure = LL_DMA_CHANNEL_SRC_NSEC;
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
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->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(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));
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
assert_param(IS_LL_DMA_CHANNEL_SRC_SEC(DMA_InitNodeStruct->SrcSecure));
assert_param(IS_LL_DMA_CHANNEL_DEST_SEC(DMA_InitNodeStruct->DestSecure));
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/* 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_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_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_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
* DestAllocatedPort field is not supported by LPDMA channels.
* - DestHWordExchange: DMA_CTR1_DHX bit
* DestHWordExchange field is not supported by LPDMA channels.
* - DestByteExchange: DMA_CTR1_DBX bit
* DestByteExchange field is not supported by LPDMA channels.
* - DestIncMode: DMA_CTR1_DINC bit
* - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits
* - SrcAllocatedPort: DMA_CTR1_SAP bit
* SrcAllocatedPort field is not supported by LPDMA channels.
* - SrcByteExchange: DMA_CTR1_SBX bit
* SrcByteExchange field is not supported by LPDMA channels.
* - DataAlignment: DMA_CTR1_PAM [12:11] bits
* DataAlignment field is reduced to one bit for LPDMA channels.
* - SrcIncMode: DMA_CTR1_SINC bit
* - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits
* - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits
* SrcBurstLength field is not supported by LPDMA channels.
* - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits
* DestBurstLength field is not supported by LPDMA channels.
*/
pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->DestIncMode | \
DMA_InitNodeStruct->DestDataWidth | \
DMA_InitNodeStruct->DataAlignment | \
DMA_InitNodeStruct->SrcIncMode | \
DMA_InitNodeStruct->SrcDataWidth);
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->DestSecure | \
DMA_InitNodeStruct->SrcSecure);
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
/* Update CTR1 register fields for not LPDMA channels */
if (DMA_InitNodeStruct->NodeType != LL_DMA_LPDMA_LINEAR_NODE)
{
pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->DestAllocatedPort | \
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
* - BlkHWRequest: DMA_CTR2_BREQ bit
* - Direction: DMA_CTR2_DREQ bit
* - Direction: DMA_CTR2_SWREQ bit
* Direction field is reduced to one bit for LPDMA channels (SWREQ).
* - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits
* DataAlignment field is reduced to 5 bits for LPDMA channels.
* - Request: DMA_CTR2_REQSEL [6:0] bits
* DataAlignment field is reduced to 5 bits for LPDMA channels.
*/
pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->TransferEventMode | \
DMA_InitNodeStruct->TriggerPolarity | \
DMA_InitNodeStruct->BlkHWRequest | \
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);
}
/* Update CTR2 register fields for LPDMA */
if (DMA_InitNodeStruct->NodeType == LL_DMA_LPDMA_LINEAR_NODE)
{
pNode->LinkRegisters[reg_counter] &= (~(1UL << 21U) & ~(3UL << 5U));
}
/* 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_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_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_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_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 /* (defined (GPDMA1) || defined (LPDMA1)) */
/**
* @}
*/
#endif /* defined (USE_FULL_LL_DRIVER) */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_dma.c
|
C
|
apache-2.0
| 62,185
|
/**
******************************************************************************
* @file stm32u5xx_ll_dma2d.c
* @author MCD Application Team
* @brief DMA2D LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_dma2d.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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))
/**
* @}
*/
/* 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(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_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2D);
/* Release reset of DMA2D clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_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));
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_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->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;
}
/**
* @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(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(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(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(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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_dma2d.c
|
C
|
apache-2.0
| 25,384
|
/**
******************************************************************************
* @file stm32u5xx_ll_exti.c
* @author MCD Application Team
* @brief EXTI LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_exti.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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_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, 0xFF9E0000U);
/* 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);
/* Software interrupt event register set to default reset values */
LL_EXTI_WriteReg(SWIER1, 0x00000000U);
/* Pending register set to default reset values */
LL_EXTI_WriteReg(RPR1, 0xFFFFFFFFU);
LL_EXTI_WriteReg(FPR1, 0xFFFFFFFFU);
/* Privilege register set to default reset values */
LL_EXTI_WriteReg(PRIVCFGR1, 0x00000000U);
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/* Secure register set to default reset values */
LL_EXTI_WriteReg(SECCFGR1, 0x00000000U);
#endif /* __ARM_FEATURE_CMSE */
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_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;
}
}
}
}
/* 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);
}
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->LineCommand = DISABLE;
EXTI_InitStruct->Mode = LL_EXTI_MODE_IT;
EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (EXTI) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_exti.c
|
C
|
apache-2.0
| 7,464
|
/**
******************************************************************************
* @file stm32u5xx_ll_fmac.c
* @author MCD Application Team
* @brief Header for stm32u5xx_ll_fmac.c module
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_fmac.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined(FMAC)
/** @addtogroup FMAC_LL
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Global variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Functions Definition ------------------------------------------------------*/
/** @addtogroup FMAC_LL_Exported_Functions
* @{
*/
/** @addtogroup FMAC_LL_EF_Init
* @{
*/
/**
* @brief Initialize FMAC peripheral registers to their default reset values.
* @param FMACx FMAC Instance
* @retval ErrorStatus enumeration value:
* - SUCCESS: FMAC registers are initialized
* - ERROR: FMAC registers are not initialized
*/
ErrorStatus LL_FMAC_Init(FMAC_TypeDef *FMACx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_FMAC_ALL_INSTANCE(FMACx));
if (FMACx == FMAC)
{
/* Perform the reset */
LL_FMAC_EnableReset(FMACx);
/* Wait until flag is reset */
while (LL_FMAC_IsEnabledReset(FMACx) != 0UL)
{
}
}
else
{
status = ERROR;
}
return (status);
}
/**
* @brief De-Initialize FMAC peripheral registers to their default reset values.
* @param FMACx FMAC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: FMAC registers are de-initialized
* - ERROR: FMAC registers are not de-initialized
*/
ErrorStatus LL_FMAC_DeInit(FMAC_TypeDef *FMACx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_FMAC_ALL_INSTANCE(FMACx));
if (FMACx == FMAC)
{
/* Force FMAC reset */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_FMAC);
/* Release FMAC reset */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_FMAC);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(FMAC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_fmac.c
|
C
|
apache-2.0
| 3,249
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 FMC functional block makes the interface with synchronous and asynchronous static
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
(+) Independent Chip Select control for each memory bank
(+) Independent configuration for each memory bank
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
#if defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_SRAM_MODULE_ENABLED) || defined(HAL_NAND_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 | FMC_BTRx_DATAHLD))
/* --- BWTR Register ---*/
/* BWTR register clear mask */
#define BWTR_CLEAR_MASK ((uint32_t)(FMC_BWTRx_ADDSET | FMC_BWTRx_ADDHLD |\
FMC_BWTRx_DATAST | FMC_BWTRx_BUSTURN |\
FMC_BWTRx_ACCMOD | FMC_BWTRx_DATAHLD))
/* --- PCR Register ---*/
/* PCR register clear mask */
#define PCR_CLEAR_MASK ((uint32_t)(FMC_PCR_PWAITEN | FMC_PCR_PBKEN | \
FMC_PCR_PTYP | 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))
/**
* @}
*/
/* 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));
assert_param(IS_FMC_NBL_SETUPTIME(Init->NBLSetupTime));
assert_param(IS_FUNCTIONAL_STATE(Init->MaxChipSelectPulse));
/* 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->NBLSetupTime;
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_NBLSET;
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));
}
/* Check PSRAM chip select counter state */
if (Init->MaxChipSelectPulse == ENABLE)
{
/* Check the parameters */
assert_param(IS_FMC_MAX_CHIP_SELECT_PULSE_TIME(Init->MaxChipSelectPulseTime));
/* Configure PSRAM chip select counter value */
MODIFY_REG(Device->PCSCNTR, FMC_PCSCNTR_CSCOUNT, (uint32_t)(Init->MaxChipSelectPulseTime));
/* Enable PSRAM chip select counter for the bank */
switch (Init->NSBank)
{
case FMC_NORSRAM_BANK1 :
SET_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB1EN);
break;
case FMC_NORSRAM_BANK2 :
SET_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB2EN);
break;
case FMC_NORSRAM_BANK3 :
SET_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB3EN);
break;
default :
SET_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB4EN);
break;
}
}
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;
/* De-initialize PSRAM chip select counter */
switch (Bank)
{
case FMC_NORSRAM_BANK1 :
CLEAR_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB1EN);
break;
case FMC_NORSRAM_BANK2 :
CLEAR_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB2EN);
break;
case FMC_NORSRAM_BANK3 :
CLEAR_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB3EN);
break;
default :
CLEAR_BIT(Device->PCSCNTR, FMC_PCSCNTR_CNTB4EN);
break;
}
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_DATAHOLD_DURATION(Timing->DataHoldTime));
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 */
MODIFY_REG(Device->BTCR[Bank + 1U], BTR_CLEAR_MASK, (Timing->AddressSetupTime |
((Timing->AddressHoldTime) << FMC_BTRx_ADDHLD_Pos) |
((Timing->DataSetupTime) << FMC_BTRx_DATAST_Pos) |
((Timing->DataHoldTime) << FMC_BTRx_DATAHLD_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));
assert_param(IS_FMC_DATAHOLD_DURATION(Timing->DataHoldTime));
assert_param(IS_FMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration));
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 */
MODIFY_REG(Device->BWTR[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime |
((Timing->AddressHoldTime) << FMC_BWTRx_ADDHLD_Pos) |
((Timing->DataSetupTime) << FMC_BWTRx_DATAST_Pos) |
((Timing->DataHoldTime) << FMC_BWTRx_DATAHLD_Pos) |
Timing->AccessMode |
((Timing->BusTurnAroundDuration) << FMC_BWTRx_BUSTURN_Pos)));
}
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 */
MODIFY_REG(Device->PMEM, PMEM_CLEAR_MASK, (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 */
MODIFY_REG(Device->PATT, PATT_CLEAR_MASK, (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;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_NOR_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_fmc.c
|
C
|
apache-2.0
| 29,051
|
/**
******************************************************************************
* @file stm32u5xx_ll_gpio.c
* @author MCD Application Team
* @brief GPIO LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_gpio.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || \
defined (GPIOG) || defined (GPIOH) || defined (GPIOI) || defined (GPIOJ)
/** @addtogroup GPIO_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup GPIO_LL_Private_Macros
* @{
*/
#define IS_LL_GPIO_PIN(__VALUE__) (((0x00000000U) < (__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(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_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOA);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOA);
}
else if (GPIOx == GPIOB)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOB);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOB);
}
else if (GPIOx == GPIOC)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOC);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOC);
}
#if defined(GPIOD)
else if (GPIOx == GPIOD)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOD);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOD);
}
#endif /* GPIOD */
#if defined(GPIOE)
else if (GPIOx == GPIOE)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOE);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOE);
}
#endif /* GPIOE */
#if defined(GPIOF)
else if (GPIOx == GPIOF)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOF);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOF);
}
#endif /* GPIOF */
#if defined(GPIOG)
else if (GPIOx == GPIOG)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOG);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOG);
}
#endif /* GPIOG */
#if defined(GPIOH)
else if (GPIOx == GPIOH)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOH);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOH);
}
#endif /* GPIOH */
#if defined(GPIOI)
else if (GPIOx == GPIOI)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOI);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOI);
}
#endif /* GPIOI */
#if defined(GPIOJ)
else if (GPIOx == GPIOJ)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOJ);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOJ);
}
#endif /* GPIOJ */
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, 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) != 0U)
{
/* Get current io position */
currentpin = (GPIO_InitStruct->Pin) & (1UL << pinpos);
if (currentpin != 0U)
{
/* 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 */
assert_param(IS_LL_GPIO_SPEED(GPIO_InitStruct->Speed));
/* Speed mode configuration */
LL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed);
}
/* 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));
/* Speed mode configuration */
if (POSITION_VAL(currentpin) < 8U)
{
LL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate);
}
else
{
LL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate);
}
}
}
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);
}
/**
* @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 (GPIOI) || defined (GPIOJ) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_gpio.c
|
C
|
apache-2.0
| 10,417
|
/**
******************************************************************************
* @file stm32u5xx_ll_i2c.c
* @author MCD Application Team
* @brief I2C LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_i2c.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (I2C1) || defined (I2C2) || defined (I2C3) || defined (I2C4)
/** @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(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_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_I2C3);
/* Release reset of I2C clock */
LL_APB3_GRP1_ReleaseReset(LL_APB3_GRP1_PERIPH_I2C3);
}
else if (I2Cx == I2C4)
{
/* Force reset of I2C clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_I2C4);
/* Release reset of I2C clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_I2C4);
}
#if defined(I2C5)
else if (I2Cx == I2C5)
{
/* Force reset of I2C clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_I2C5);
/* Release reset of I2C clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_I2C5);
}
#endif /* I2C5 */
#if defined(I2C6)
else if (I2Cx == I2C6)
{
/* Force reset of I2C clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_I2C6);
/* Release reset of I2C clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_I2C6);
}
#endif /* I2C6 */
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, 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 || I2C4 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_i2c.c
|
C
|
apache-2.0
| 8,488
|
/**
******************************************************************************
* @file stm32u5xx_ll_icache.c
* @author MCD Application Team
* @brief ICACHE LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_icache.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined(ICACHE)
/** @defgroup ICACHE_LL ICACHE
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup ICACHE_LL_Private_Macros ICACHE Private Macros
* @{
*/
#define IS_LL_ICACHE_REGION(__VALUE__) (((__VALUE__) == LL_ICACHE_REGION_0) || \
((__VALUE__) == LL_ICACHE_REGION_1) || \
((__VALUE__) == LL_ICACHE_REGION_2) || \
((__VALUE__) == LL_ICACHE_REGION_3))
#define IS_LL_ICACHE_REGION_SIZE(__VALUE__) (((__VALUE__) == LL_ICACHE_REGIONSIZE_2MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_4MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_8MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_16MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_32MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_64MB) || \
((__VALUE__) == LL_ICACHE_REGIONSIZE_128MB))
#define IS_LL_ICACHE_MASTER_PORT(__VALUE__) (((__VALUE__) == LL_ICACHE_MASTER1_PORT) || \
((__VALUE__) == LL_ICACHE_MASTER2_PORT))
#define IS_LL_ICACHE_OUTPUT_BURST(__VALUE__) (((__VALUE__) == LL_ICACHE_OUTPUT_BURST_WRAP) || \
((__VALUE__) == LL_ICACHE_OUTPUT_BURST_INCR))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup ICACHE_LL_Exported_Functions
* @{
*/
/** @addtogroup ICACHE_LL_EF_REGION_Init
* @{
*/
/**
* @brief Configure and enable the memory remapped region.
* @note The Instruction Cache and corresponding region must be disabled.
* @param Region This parameter can be one of the following values:
* @arg @ref LL_ICACHE_REGION_0
* @arg @ref LL_ICACHE_REGION_1
* @arg @ref LL_ICACHE_REGION_2
* @arg @ref LL_ICACHE_REGION_3
* @param pICACHE_RegionStruct pointer to a @ref LL_ICACHE_RegionTypeDef structure.
* @retval None
*/
void LL_ICACHE_ConfigRegion(uint32_t Region, const LL_ICACHE_RegionTypeDef *const pICACHE_RegionStruct)
{
__IO uint32_t *p_reg;
uint32_t value;
/* Check the parameters */
assert_param(IS_LL_ICACHE_REGION(Region));
assert_param(IS_LL_ICACHE_REGION_SIZE(pICACHE_RegionStruct->Size));
assert_param(IS_LL_ICACHE_MASTER_PORT(pICACHE_RegionStruct->TrafficRoute));
assert_param(IS_LL_ICACHE_OUTPUT_BURST(pICACHE_RegionStruct->OutputBurstType));
/* Get region control register address */
p_reg = &(ICACHE->CRR0) + (1U * Region);
/* Region 2MB: BaseAddress size 8 bits, RemapAddress size 11 bits */
/* Region 4MB: BaseAddress size 7 bits, RemapAddress size 10 bits */
/* Region 8MB: BaseAddress size 6 bits, RemapAddress size 9 bits */
/* Region 16MB: BaseAddress size 5 bits, RemapAddress size 8 bits */
/* Region 32MB: BaseAddress size 4 bits, RemapAddress size 7 bits */
/* Region 64MB: BaseAddress size 3 bits, RemapAddress size 6 bits */
/* Region 128MB: BaseAddress size 2 bits, RemapAddress size 5 bits */
value = ((pICACHE_RegionStruct->BaseAddress & 0x1FFFFFFFU) >> 21U) & \
(0xFFU & ~(pICACHE_RegionStruct->Size - 1U));
value |= ((pICACHE_RegionStruct->RemapAddress >> 5U) & \
((uint32_t)(0x7FFU & ~(pICACHE_RegionStruct->Size - 1U)) << ICACHE_CRRx_REMAPADDR_Pos));
value |= (pICACHE_RegionStruct->Size << ICACHE_CRRx_RSIZE_Pos) | pICACHE_RegionStruct->TrafficRoute | \
pICACHE_RegionStruct->OutputBurstType;
*p_reg = (value | ICACHE_CRRx_REN); /* Configure and enable region */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ICACHE */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_icache.c
|
C
|
apache-2.0
| 5,263
|
/**
******************************************************************************
* @file stm32u5xx_ll_lpgpio.c
* @author MCD Application Team
* @brief LPGPIO LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_lpgpio.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (LPGPIO1)
/** @addtogroup LPGPIO_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup LPGPIO_LL_Private_Macros
* @{
*/
#define IS_LL_LPGPIO_PIN(__VALUE__) (((0x00000000U) < (__VALUE__)) && ((__VALUE__) <= (LL_LPGPIO_PIN_ALL)))
#define IS_LL_LPGPIO_MODE(__VALUE__) (((__VALUE__) == LL_LPGPIO_MODE_INPUT) ||\
((__VALUE__) == LL_LPGPIO_MODE_OUTPUT))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup LPGPIO_LL_Exported_Functions
* @{
*/
/** @addtogroup LPGPIO_LL_EF_Init
* @{
*/
/**
* @brief De-initialize LPGPIO registers (Registers restored to their default values).
* @param LPGPIOx LPGPIO Port
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPGPIO registers are de-initialized
* - ERROR: Wrong LPGPIO Port
*/
ErrorStatus LL_LPGPIO_DeInit(GPIO_TypeDef *LPGPIOx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_LPGPIO_ALL_INSTANCE(LPGPIOx));
/* Force and Release reset on clock of LPGPIOx Port */
if (LPGPIOx == LPGPIO1)
{
LL_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_LPGPIO1);
LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_LPGPIO1);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize LPGPIO registers according to the specified parameters in LPGPIO_InitStruct.
* @param LPGPIOx LPGPIO Port
* @param LPGPIO_InitStruct: pointer to a @ref LL_LPGPIO_InitTypeDef structure
* that contains the configuration information for the specified LPGPIO peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPGPIO registers are initialized according to LPGPIO_InitStruct content
* - ERROR: Not applicable
*/
ErrorStatus LL_LPGPIO_Init(GPIO_TypeDef *LPGPIOx, const LL_LPGPIO_InitTypeDef *const LPGPIO_InitStruct)
{
uint32_t pinpos;
uint32_t currentpin;
/* Check the parameters */
assert_param(IS_LPGPIO_ALL_INSTANCE(LPGPIOx));
assert_param(IS_LL_LPGPIO_PIN(LPGPIO_InitStruct->Pin));
assert_param(IS_LL_LPGPIO_MODE(LPGPIO_InitStruct->Mode));
/* ------------------------- Configure the port pins ---------------- */
/* Initialize pinpos on first pin set */
pinpos = POSITION_VAL(LPGPIO_InitStruct->Pin);
/* Configure the port pins */
while (((LPGPIO_InitStruct->Pin) >> pinpos) != 0U)
{
/* Get current io position */
currentpin = (LPGPIO_InitStruct->Pin) & (1UL << pinpos);
if (currentpin != 0U)
{
/* Pin Mode configuration */
LL_LPGPIO_SetPinMode(LPGPIOx, currentpin, LPGPIO_InitStruct->Mode);
}
pinpos++;
}
return (SUCCESS);
}
/**
* @brief Set each @ref LL_LPGPIO_InitTypeDef field to default value.
* @param LPGPIO_InitStruct: pointer to a @ref LL_LPGPIO_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_LPGPIO_StructInit(LL_LPGPIO_InitTypeDef *LPGPIO_InitStruct)
{
/* Reset LPGPIO init structure parameters values */
LPGPIO_InitStruct->Pin = LL_LPGPIO_PIN_ALL;
LPGPIO_InitStruct->Mode = LL_LPGPIO_MODE_INPUT;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (LPGPIO1) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_lpgpio.c
|
C
|
apache-2.0
| 4,745
|
/**
******************************************************************************
* @file stm32u5xx_ll_lptim.c
* @author MCD Application Team
* @brief LPTIM LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_lptim.h"
#include "stm32u5xx_ll_bus.h"
#include "stm32u5xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (LPTIM1) || defined (LPTIM2) || defined (LPTIM3) || defined (LPTIM4)
/** @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(LPTIM_TypeDef *LPTIMx)
{
ErrorStatus result = SUCCESS;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(LPTIMx));
if (LPTIMx == LPTIM1)
{
LL_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_LPTIM1);
LL_APB3_GRP1_ReleaseReset(LL_APB3_GRP1_PERIPH_LPTIM1);
}
else if (LPTIMx == LPTIM2)
{
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_LPTIM2);
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_LPTIM2);
}
else if (LPTIMx == LPTIM3)
{
LL_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_LPTIM3);
LL_APB3_GRP1_ReleaseReset(LL_APB3_GRP1_PERIPH_LPTIM3);
}
else if (LPTIMx == LPTIM4)
{
LL_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_LPTIM4);
LL_APB3_GRP1_ReleaseReset(LL_APB3_GRP1_PERIPH_LPTIM4);
}
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, 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 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_lptim.c
|
C
|
apache-2.0
| 6,433
|
/**
******************************************************************************
* @file stm32u5xx_ll_lpuart.c
* @author MCD Application Team
* @brief LPUART LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_lpuart.h"
#include "stm32u5xx_ll_rcc.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (LPUART1)
/** @addtogroup LPUART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup LPUART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* 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, 33000000].*/
#define IS_LL_LPUART_BAUDRATE(__BAUDRATE__) (((__BAUDRATE__) <= 33000000U) && ((__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(USART_TypeDef *LPUARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_LPUART_INSTANCE(LPUARTx));
if (LPUARTx == LPUART1)
{
/* Force reset of LPUART peripheral */
LL_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_LPUART1);
/* Release reset of LPUART peripheral */
LL_APB3_GRP1_ReleaseReset(LL_APB3_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, 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 = 9600U;
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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_lpuart.c
|
C
|
apache-2.0
| 11,666
|
/**
******************************************************************************
* @file stm32u5xx_ll_opamp.c
* @author MCD Application Team
* @brief OPAMP LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_opamp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (OPAMP1) || defined (OPAMP2)
/** @addtogroup OPAMP_LL OPAMP
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup OPAMP_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of OPAMP hierarchical scope: */
/* OPAMP instance. */
#define IS_LL_OPAMP_POWER_MODE(__POWER_MODE__) (((__POWER_MODE__) == LL_OPAMP_POWERMODE_NORMALPOWER_NORMALSPEED) ||\
((__POWER_MODE__) == LL_OPAMP_POWERMODE_NORMALPOWER_HIGHSPEED) ||\
((__POWER_MODE__) == LL_OPAMP_POWERMODE_LOWPOWER_NORMALSPEED)||\
((__POWER_MODE__) == LL_OPAMP_POWERMODE_LOWPOWER_HIGHSPEED))
#define IS_LL_OPAMP_FUNCTIONAL_MODE(__FUNCTIONAL_MODE__) (((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_STANDALONE) ||\
((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_FOLLOWER) ||\
((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA))
/* Note: Comparator non-inverting inputs parameters are the same on all */
/* OPAMP instances. */
/* However, comparator instance kept as macro parameter for */
/* compatibility with other STM32 families. */
#define IS_LL_OPAMP_INPUT_NONINVERTING(__OPAMPX__, __INPUT_NONINVERTING__) \
( ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO0) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINV_DAC1_CH1) \
)
/* Note: Comparator non-inverting inputs parameters are the same on all */
/* OPAMP instances. */
/* However, comparator instance kept as macro parameter for */
/* compatibility with other STM32 families. */
#define IS_LL_OPAMP_INPUT_INVERTING(__OPAMPX__, __INPUT_INVERTING__) \
( ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO0) \
|| ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO1) \
|| ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_CONNECT_NO) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup OPAMP_LL_Exported_Functions
* @{
*/
/** @addtogroup OPAMP_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected OPAMP instance
* to their default reset values.
* @param OPAMPx OPAMP instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: OPAMP registers are de-initialized
* - ERROR: OPAMP registers are not de-initialized
*/
ErrorStatus LL_OPAMP_DeInit(OPAMP_TypeDef *OPAMPx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx));
LL_OPAMP_WriteReg(OPAMPx, CSR, 0x00000000U);
return status;
}
/**
* @brief Initialize some features of OPAMP instance.
* @note This function reset bit of calibration mode to ensure
* to be in functional mode, in order to have OPAMP parameters
* (inputs selection, ...) set with the corresponding OPAMP mode
* to be effective.
* @note This function configures features of the selected OPAMP instance.
* Some features are also available at scope OPAMP common instance
* (common to several OPAMP instances).
* @param OPAMPx OPAMP instance
* @param OPAMP_InitStruct Pointer to a @ref LL_OPAMP_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: OPAMP registers are initialized
* - ERROR: OPAMP registers are not initialized
*/
ErrorStatus LL_OPAMP_Init(OPAMP_TypeDef *OPAMPx, LL_OPAMP_InitTypeDef *OPAMP_InitStruct)
{
/* Check the parameters */
assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx));
assert_param(IS_LL_OPAMP_POWER_MODE(OPAMP_InitStruct->PowerMode));
assert_param(IS_LL_OPAMP_FUNCTIONAL_MODE(OPAMP_InitStruct->FunctionalMode));
assert_param(IS_LL_OPAMP_INPUT_NONINVERTING(OPAMPx, OPAMP_InitStruct->InputNonInverting));
/* Note: OPAMP inverting input can be used with OPAMP in mode standalone */
/* or PGA with external capacitors for filtering circuit. */
/* Otherwise (OPAMP in mode follower), OPAMP inverting input is */
/* not used (not connected to GPIO pin). */
if (OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER)
{
assert_param(IS_LL_OPAMP_INPUT_INVERTING(OPAMPx, OPAMP_InitStruct->InputInverting));
}
/* Configuration of OPAMP instance : */
/* - PowerMode */
/* - Functional mode */
/* - Input non-inverting */
/* - Input inverting */
/* Note: Bit OPAMP_CSR_CALON reset to ensure to be in functional mode. */
if (OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER)
{
MODIFY_REG(OPAMPx->CSR,
OPAMP_CSR_OPALPM
| OPAMP_CSR_OPAMODE
| OPAMP_CSR_CALON
| OPAMP_CSR_VM_SEL
| OPAMP_CSR_VP_SEL
| OPAMP_CSR_HSM
,
OPAMP_InitStruct->PowerMode
| OPAMP_InitStruct->FunctionalMode
| OPAMP_InitStruct->InputNonInverting
| OPAMP_InitStruct->InputInverting
);
}
else
{
MODIFY_REG(OPAMPx->CSR,
OPAMP_CSR_OPALPM
| OPAMP_CSR_OPAMODE
| OPAMP_CSR_CALON
| OPAMP_CSR_VM_SEL
| OPAMP_CSR_VP_SEL
| OPAMP_CSR_HSM
,
OPAMP_InitStruct->PowerMode
| LL_OPAMP_MODE_FOLLOWER
| OPAMP_InitStruct->InputNonInverting
| LL_OPAMP_INPUT_INVERT_CONNECT_NO
);
}
/* Set the power supply range to high for performance purpose */
/* The OPAMP_CSR_OPARANGE is common configuration for all OPAMPs */
/* bit OPAMP_CSR_OPARANGE applies for both OPAMPs */
MODIFY_REG(OPAMP1->CSR, OPAMP_CSR_OPARANGE, OPAMP_CSR_OPARANGE);
return SUCCESS;
}
/**
* @brief Set each @ref LL_OPAMP_InitTypeDef field to default value.
* @param OPAMP_InitStruct pointer to a @ref LL_OPAMP_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_OPAMP_StructInit(LL_OPAMP_InitTypeDef *OPAMP_InitStruct)
{
/* Set OPAMP_InitStruct fields to default values */
OPAMP_InitStruct->PowerMode = LL_OPAMP_POWERMODE_NORMALPOWER_NORMALSPEED;
OPAMP_InitStruct->FunctionalMode = LL_OPAMP_MODE_FOLLOWER;
OPAMP_InitStruct->InputNonInverting = LL_OPAMP_INPUT_NONINVERT_IO0;
/* Note: Parameter discarded if OPAMP in functional mode follower, */
/* set anyway to its default value. */
OPAMP_InitStruct->InputInverting = LL_OPAMP_INPUT_INVERT_CONNECT_NO;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* OPAMP1 || OPAMP2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_opamp.c
|
C
|
apache-2.0
| 8,901
|
/**
******************************************************************************
* @file stm32u5xx_ll_pka.c
* @author MCD Application Team
* @brief PKA LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_pka.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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(PKA_TypeDef *PKAx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_PKA_ALL_INSTANCE(PKAx));
if (PKAx == PKA)
{
/* Force PKA reset */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_PKA);
/* Release PKA reset */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_pka.c
|
C
|
apache-2.0
| 5,601
|
/**
******************************************************************************
* @file stm32u5xx_ll_pwr.c
* @author MCD Application Team
* @brief PWR LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_pwr.h"
/** @addtogroup STM32U5xx_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();
/* Clear PWR wake up flags */
LL_PWR_ClearFlag_WU();
/* Reset privilege attribute for nsecure attribute */
LL_PWR_DisableNSecurePrivilege();
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/* Reset privilege attribute for nsecure attribute */
LL_PWR_DisableSecurePrivilege();
/* Reset secure attribute */
LL_PWR_ConfigSecure(0);
#endif /* defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) */
return SUCCESS;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(PWR) */
/**
* @}
*/
#endif /* defined (USE_FULL_LL_DRIVER) */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_pwr.c
|
C
|
apache-2.0
| 2,412
|
/**
******************************************************************************
* @file stm32u5xx_ll_rcc.c
* @author MCD Application Team
* @brief RCC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined(RCC)
/** @addtogroup RCC_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RCC_LL_Private_Macros
* @{
*/
#if defined(USART6)
#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART3_CLKSOURCE)\
|| ((__VALUE__) == LL_RCC_USART6_CLKSOURCE))
#else
#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART3_CLKSOURCE))
#endif /* defined(USART6) */
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_UART4_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_UART5_CLKSOURCE))
#define IS_LL_RCC_LPUART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPUART1_CLKSOURCE))
#if defined(I2C5) & defined(I2C6)
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C4_CLKSOURCE)\
|| ((__VALUE__) == LL_RCC_I2C5_CLKSOURCE)\
|| ((__VALUE__) == LL_RCC_I2C6_CLKSOURCE))
#else
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C4_CLKSOURCE))
#endif /* defined(I2C5) & defined(I2C6) */
#define IS_LL_RCC_SPI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SPI1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_SPI2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_SPI3_CLKSOURCE))
#define IS_LL_RCC_LPTIM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPTIM1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_LPTIM2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_LPTIM34_CLKSOURCE))
#define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SAI1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_SAI2_CLKSOURCE))
#define IS_LL_RCC_SDMMC_KERNELCLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SDMMC_KERNELCLKSOURCE))
#define IS_LL_RCC_SDMMC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SDMMC_CLKSOURCE))
#define IS_LL_RCC_RNG_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_RNG_CLKSOURCE))
#define IS_LL_RCC_USB_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USB_CLKSOURCE))
#define IS_LL_RCC_ADCDAC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADCDAC_CLKSOURCE))
#define IS_LL_RCC_MDF1_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_MDF1_CLKSOURCE))
#define IS_LL_RCC_DAC1_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DAC1_CLKSOURCE))
#define IS_LL_RCC_ADF1_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADF1_CLKSOURCE))
#define IS_LL_RCC_OCTOSPI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_OCTOSPI_CLKSOURCE))
#if defined(HSPI1)
#define IS_LL_RCC_HSPI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_HSPI_CLKSOURCE))
#endif /* defined(HSPI1) */
#define IS_LL_RCC_SAES_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SAES_CLKSOURCE))
#define IS_LL_RCC_FDCAN_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_FDCAN_CLKSOURCE))
#if defined(DSI)
#define IS_LL_RCC_DSI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DSI_CLKSOURCE))
#endif /* defined(DSI) */
#if defined(LTDC)
#define IS_LL_RCC_LTDC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LTDC_CLKSOURCE))
#endif /* defined(LTDC) */
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup RCC_LL_Private_Functions RCC Private functions
* @{
*/
static uint32_t RCC_GetSystemClockFreq(void);
static uint32_t RCC_GetHCLKClockFreq(uint32_t SYSCLK_Frequency);
static uint32_t RCC_GetPCLK1ClockFreq(uint32_t HCLK_Frequency);
static uint32_t RCC_GetPCLK2ClockFreq(uint32_t HCLK_Frequency);
static uint32_t RCC_GetPCLK3ClockFreq(uint32_t HCLK_Frequency);
static uint32_t RCC_PLL1_GetFreqDomain_SYS(void);
static uint32_t RCC_PLL1_GetFreqDomain_SAI(void);
static uint32_t RCC_PLL1_GetFreqDomain_48M(void);
static uint32_t RCC_PLL2_GetFreqDomain_SAI(void);
static uint32_t RCC_PLL2_GetFreqDomain_48M(void);
static uint32_t RCC_PLL2_GetFreqDomain_ADC(void);
static uint32_t RCC_PLL3_GetFreqDomain_SAI(void);
static uint32_t RCC_PLL3_GetFreqDomain_48M(void);
#if defined(HSPI1) || defined(LTDC)
static uint32_t RCC_PLL3_GetFreqDomain_HSPI_LTDC(void);
#endif /* HSPI1 || LTDC */
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RCC_LL_Exported_Functions
* @{
*/
/** @addtogroup RCC_LL_EF_Init
* @{
*/
/**
* @brief Reset the RCC clock configuration to the default reset state.
* @note The default reset state of the clock configuration is given below:
* - MSI ON and used as system clock source
* - HSE, HSI, PLL1, PLL2 and PLL3 OFF
* - AHB, APB1, APB2 and APB3 prescaler set to 1.
* - CSS, MCO OFF
* - All interrupts disabled
* @note This function doesn't modify the configuration of the
* - Peripheral clocks
* - LSI, LSE and RTC clocks
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RCC registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_RCC_DeInit(void)
{
uint32_t vl_mask;
/* Set MSION bit */
LL_RCC_MSIS_Enable();
/* Insure MSIRDY bit is set before writing default MSIRANGE value */
while (LL_RCC_MSIS_IsReady() == 0U)
{
}
/* Set MSIRANGE default value */
LL_RCC_MSIS_SetRange(LL_RCC_MSISRANGE_4);
/* Set MSITRIM bits to the reset value*/
LL_RCC_MSI_SetCalibTrimming(0, LL_RCC_MSI_OSCILLATOR_1);
/* Set HSITRIM bits to the reset value*/
LL_RCC_HSI_SetCalibTrimming(0x40U);
/* Reset CFGR register */
LL_RCC_WriteReg(CFGR1, 0x00000000U);
LL_RCC_WriteReg(CFGR2, 0x00000000U);
LL_RCC_WriteReg(CFGR3, 0x00000000U);
/* Read CR register */
vl_mask = LL_RCC_ReadReg(CR);
/* Reset HSION, HSIKERON, HSEON, PLL1ON, PLL2ON and PLL3ON bits */
CLEAR_BIT(vl_mask, (RCC_CR_HSION | RCC_CR_HSIKERON | RCC_CR_HSEON |
RCC_CR_PLL1ON | RCC_CR_PLL2ON | RCC_CR_PLL3ON));
/* Write new mask in CR register */
LL_RCC_WriteReg(CR, vl_mask);
/* Wait for PLL1RDY, PLL2RDY and PLL3RDY bits to be reset */
while (READ_BIT(RCC->CR, RCC_CR_PLL1RDY | RCC_CR_PLL2RDY | RCC_CR_PLL3RDY) != 0U)
{
}
/* Reset PLL1DIVR register */
LL_RCC_WriteReg(PLL1DIVR, 0x01010280U);
/* Reset PLL2DIVR register */
LL_RCC_WriteReg(PLL2DIVR, 0x01010280U);
/* Reset PLL3DIVR register */
LL_RCC_WriteReg(PLL3DIVR, 0x01010280U);
/* Reset HSEBYP bit */
LL_RCC_HSE_DisableBypass();
/* Disable all interrupts */
LL_RCC_WriteReg(CIER, 0x00000000U);
/* Clear all interrupt flags */
vl_mask = RCC_CICR_LSIRDYC | RCC_CICR_LSERDYC | RCC_CICR_MSISRDYC | RCC_CICR_HSIRDYC | RCC_CICR_HSERDYC | \
RCC_CICR_PLL1RDYC | RCC_CICR_PLL2RDYC | RCC_CICR_PLL3RDYC | RCC_CICR_HSI48RDYC | RCC_CICR_CSSC | \
RCC_CICR_MSIKRDYC;
LL_RCC_WriteReg(CICR, vl_mask);
/* Clear reset flags */
LL_RCC_ClearResetFlags();
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
/* Reset secure configuration */
LL_RCC_ConfigSecure(LL_RCC_ALL_NSEC);
#endif /* __ARM_FEATURE_CMSE && (__ARM_FEATURE_CMSE == 3U) */
return SUCCESS;
}
/**
* @}
*/
/** @addtogroup RCC_LL_EF_Get_Freq
* @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks
* and different peripheral clocks available on the device.
* @note If SYSCLK source is MSI, function returns values based on MSI_VALUE(*)
* @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(**)
* @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(***)
* @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(***)
* or HSI_VALUE(**) or MSI_VALUE(*) multiplied/divided by the PLL factors.
* @note (*) MSI_VALUE is a constant defined in this file (default value
* 4 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
* @note (**) HSI_VALUE is a constant defined in this file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
* @note (***) HSE_VALUE is a constant defined in this file (default value
* 8 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
* @note The result of this function could be incorrect when using fractional
* value for HSE crystal.
* @note This function can be used by the user application to compute the
* baud-rate for the communication peripherals or configure other parameters.
* @{
*/
/**
* @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks
* @note Each time SYSCLK, HCLK, PCLK1, PCLK2 and/or PCLK3 clock changes, this function
* must be called to update structure fields. Otherwise, any
* configuration based on this function will be incorrect.
* @param RCC_Clocks pointer to a @ref LL_RCC_ClocksTypeDef structure which will hold the clocks frequencies
* @retval None
*/
void LL_RCC_GetSystemClocksFreq(LL_RCC_ClocksTypeDef *RCC_Clocks)
{
/* Get SYSCLK frequency */
RCC_Clocks->SYSCLK_Frequency = RCC_GetSystemClockFreq();
/* HCLK clock frequency */
RCC_Clocks->HCLK_Frequency = RCC_GetHCLKClockFreq(RCC_Clocks->SYSCLK_Frequency);
/* PCLK1 clock frequency */
RCC_Clocks->PCLK1_Frequency = RCC_GetPCLK1ClockFreq(RCC_Clocks->HCLK_Frequency);
/* PCLK2 clock frequency */
RCC_Clocks->PCLK2_Frequency = RCC_GetPCLK2ClockFreq(RCC_Clocks->HCLK_Frequency);
/* PCLK3 clock frequency */
RCC_Clocks->PCLK3_Frequency = RCC_GetPCLK3ClockFreq(RCC_Clocks->HCLK_Frequency);
}
/**
* @brief Return USARTx clock frequency
* @param USARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_USART1_CLKSOURCE
* @arg @ref LL_RCC_USART2_CLKSOURCE
* @arg @ref LL_RCC_USART3_CLKSOURCE
* @arg @ref LL_RCC_USART6_CLKSOURCE (*)
* @retval USART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*
* (*) : USART6 is available only for STM32U59xxx and STM32U5Axxx devices.
*/
uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource)
{
uint32_t usart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_USART_CLKSOURCE(USARTxSource));
if (USARTxSource == LL_RCC_USART1_CLKSOURCE)
{
/* USART1CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART1_CLKSOURCE_SYSCLK: /* USART1 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART1_CLKSOURCE_HSI: /* USART1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_LSE: /* USART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_PCLK2: /* USART1 Clock is PCLK2 */
usart_frequency = RCC_GetPCLK2ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (USARTxSource == LL_RCC_USART2_CLKSOURCE)
{
/* USART2CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART2_CLKSOURCE_SYSCLK: /* USART2 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART2_CLKSOURCE_HSI: /* USART2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_LSE: /* USART2 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_PCLK1: /* USART2 Clock is PCLK1 */
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (USARTxSource == LL_RCC_USART3_CLKSOURCE)
{
/* USART3CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART3_CLKSOURCE_SYSCLK: /* USART3 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART3_CLKSOURCE_HSI: /* USART3 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_LSE: /* USART3 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_PCLK1: /* USART3 Clock is PCLK1 */
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
#if defined (USART6)
else if (USARTxSource == LL_RCC_USART6_CLKSOURCE)
{
/* USART6CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART6_CLKSOURCE_SYSCLK: /* USART6 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART6_CLKSOURCE_HSI: /* USART6 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART6_CLKSOURCE_LSE: /* USART6 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART6_CLKSOURCE_PCLK1: /* USART6 Clock is PCLK1 */
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
#endif /* USART6 */
else
{
/* nothing to do */
}
return usart_frequency;
}
/**
* @brief Return UARTx clock frequency
* @param UARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_UART4_CLKSOURCE
* @arg @ref LL_RCC_UART5_CLKSOURCE
* @retval UART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
uint32_t LL_RCC_GetUARTClockFreq(uint32_t UARTxSource)
{
uint32_t uart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_UART_CLKSOURCE(UARTxSource));
if (UARTxSource == LL_RCC_UART4_CLKSOURCE)
{
/* UART4CLK clock frequency */
switch (LL_RCC_GetUARTClockSource(UARTxSource))
{
case LL_RCC_UART4_CLKSOURCE_SYSCLK: /* UART4 Clock is System Clock */
uart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_UART4_CLKSOURCE_HSI: /* UART4 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_LSE: /* UART4 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_PCLK1: /* UART4 Clock is PCLK1 */
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (UARTxSource == LL_RCC_UART5_CLKSOURCE)
{
/* UART5CLK clock frequency */
switch (LL_RCC_GetUARTClockSource(UARTxSource))
{
case LL_RCC_UART5_CLKSOURCE_SYSCLK: /* UART5 Clock is System Clock */
uart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_UART5_CLKSOURCE_HSI: /* UART5 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_LSE: /* UART5 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_PCLK1: /* UART5 Clock is PCLK1 */
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else
{
/* nothing to do */
}
return uart_frequency;
}
/**
* @brief Return SPIx clock frequency
* @param SPIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SPI1_CLKSOURCE
* @arg @ref LL_RCC_SPI2_CLKSOURCE
* @arg @ref LL_RCC_SPI3_CLKSOURCE
* @retval SPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or MSIK) is not ready
*/
uint32_t LL_RCC_GetSPIClockFreq(uint32_t SPIxSource)
{
uint32_t SPI_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SPI_CLKSOURCE(SPIxSource));
if (SPIxSource == LL_RCC_SPI1_CLKSOURCE)
{
/* SPI1 CLK clock frequency */
switch (LL_RCC_GetSPIClockSource(SPIxSource))
{
case LL_RCC_SPI1_CLKSOURCE_SYSCLK: /* SPI1 Clock is System Clock */
SPI_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_SPI1_CLKSOURCE_HSI: /* SPI1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
SPI_frequency = HSI_VALUE;
}
break;
case LL_RCC_SPI1_CLKSOURCE_MSIK: /* SPI1 Clock is MSIK Osc.*/
SPI_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_SPI1_CLKSOURCE_PCLK2: /* SPI1 Clock is PCLK2 */
SPI_frequency = RCC_GetPCLK2ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (SPIxSource == LL_RCC_SPI2_CLKSOURCE)
{
/* SPI2 CLK clock frequency */
switch (LL_RCC_GetSPIClockSource(SPIxSource))
{
case LL_RCC_SPI2_CLKSOURCE_SYSCLK: /* SPI2 Clock is System Clock */
SPI_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_SPI2_CLKSOURCE_HSI: /* SPI2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
SPI_frequency = HSI_VALUE;
}
break;
case LL_RCC_SPI2_CLKSOURCE_MSIK: /* SPI2 Clock is MSIK Osc.*/
SPI_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_SPI2_CLKSOURCE_PCLK1: /* SPI2 Clock is PCLK1 */
SPI_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (SPIxSource == LL_RCC_SPI3_CLKSOURCE)
{
/* SPI3 CLK clock frequency */
switch (LL_RCC_GetSPIClockSource(SPIxSource))
{
case LL_RCC_SPI3_CLKSOURCE_SYSCLK: /* SPI3 Clock is System Clock */
SPI_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_SPI3_CLKSOURCE_HSI: /* SPI3 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
SPI_frequency = HSI_VALUE;
}
break;
case LL_RCC_SPI3_CLKSOURCE_MSIK: /* SPI3 Clock is MSIK Osc. */
SPI_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_SPI3_CLKSOURCE_PCLK3: /* SPI3 Clock is PCLK3 */
SPI_frequency = RCC_GetPCLK3ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else
{
/* nothing to do */
}
return SPI_frequency;
}
/**
* @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
* @arg @ref LL_RCC_I2C3_CLKSOURCE
* @arg @ref LL_RCC_I2C4_CLKSOURCE
* @retval I2C clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or MSIK) is not ready
*/
uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource)
{
uint32_t i2c_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_I2C_CLKSOURCE(I2CxSource));
if (I2CxSource == LL_RCC_I2C1_CLKSOURCE)
{
/* I2C1 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C1_CLKSOURCE_SYSCLK: /* I2C1 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C1_CLKSOURCE_HSI: /* I2C1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C1_CLKSOURCE_MSIK: /* I2C1 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C1_CLKSOURCE_PCLK1: /* I2C1 Clock is PCLK1 */
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
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_HSI: /* I2C2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C2_CLKSOURCE_MSIK: /* I2C2 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C2_CLKSOURCE_PCLK1: /* I2C2 Clock is PCLK1 */
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (I2CxSource == LL_RCC_I2C3_CLKSOURCE)
{
/* I2C3 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C3_CLKSOURCE_SYSCLK: /* I2C3 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C3_CLKSOURCE_HSI: /* I2C3 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C3_CLKSOURCE_MSIK: /* I2C3 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C3_CLKSOURCE_PCLK3: /* I2C3 Clock is PCLK3 */
i2c_frequency = RCC_GetPCLK3ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (I2CxSource == LL_RCC_I2C4_CLKSOURCE)
{
/* I2C4 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C4_CLKSOURCE_SYSCLK: /* I2C4 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C4_CLKSOURCE_HSI: /* I2C4 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C4_CLKSOURCE_MSIK: /* I2C4 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C4_CLKSOURCE_PCLK1: /* I2C4 Clock is PCLK1 */
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
#if defined(I2C5)
else if (I2CxSource == LL_RCC_I2C5_CLKSOURCE)
{
/* I2C5 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C5_CLKSOURCE_SYSCLK: /* I2C5 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C5_CLKSOURCE_HSI: /* I2C5 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C5_CLKSOURCE_MSIK: /* I2C5 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C5_CLKSOURCE_PCLK1: /* I2C5 Clock is PCLK1 */
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
#endif /* I2C5 */
#if defined(I2C6)
else if (I2CxSource == LL_RCC_I2C6_CLKSOURCE)
{
/* I2C6 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C6_CLKSOURCE_SYSCLK: /* I2C6 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C6_CLKSOURCE_HSI: /* I2C6 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C6_CLKSOURCE_MSIK: /* I2C6 Clock is MSIK Osc.*/
i2c_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
case LL_RCC_I2C6_CLKSOURCE_PCLK1: /* I2C6 Clock is PCLK1 */
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
#endif /* I2C6 */
else
{
/* nothing to do */
}
return i2c_frequency;
}
/**
* @brief Return LPUARTx clock frequency
* @param LPUARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LPUART1_CLKSOURCE
* @retval LPUART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
uint32_t LL_RCC_GetLPUARTClockFreq(uint32_t LPUARTxSource)
{
uint32_t lpuart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_LPUART_CLKSOURCE(LPUARTxSource));
/* LPUART1CLK clock frequency */
switch (LL_RCC_GetLPUARTClockSource(LPUARTxSource))
{
case LL_RCC_LPUART1_CLKSOURCE_SYSCLK: /* LPUART1 Clock is System Clock */
lpuart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_LPUART1_CLKSOURCE_HSI: /* LPUART1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
lpuart_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_LSE: /* LPUART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
lpuart_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_PCLK3: /* LPUART1 Clock is PCLK3 */
lpuart_frequency = RCC_GetPCLK3ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
return lpuart_frequency;
}
/**
* @brief Return LPTIMx clock frequency
* @param LPTIMxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LPTIM1_CLKSOURCE
* @arg @ref LL_RCC_LPTIM2_CLKSOURCE
* @arg @ref LL_RCC_LPTIM34_CLKSOURCE
* @retval LPTIM clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI, LSI or LSE) is not ready
*/
uint32_t LL_RCC_GetLPTIMClockFreq(uint32_t LPTIMxSource)
{
uint32_t lptim_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_LPTIM_CLKSOURCE(LPTIMxSource));
if (LPTIMxSource == LL_RCC_LPTIM1_CLKSOURCE)
{
/* LPTIM1CLK clock frequency */
switch (LL_RCC_GetLPTIMClockSource(LPTIMxSource))
{
case LL_RCC_LPTIM1_CLKSOURCE_LSI: /* LPTIM1 Clock is LSI Osc. */
if (LL_RCC_LSI_IsReady() == 1U)
{
if (READ_BIT(RCC->BDCR, RCC_BDCR_LSIPREDIV) == RCC_BDCR_LSIPREDIV)
{
lptim_frequency = LSI_VALUE / 128U;
}
else
{
lptim_frequency = LSI_VALUE;
}
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_HSI: /* LPTIM1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_LSE: /* LPTIM1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_MSIK: /* LPTIM1 Clock is MSIK Osc.*/
lptim_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
default:
/* unreachable code */
break;
}
}
else if (LPTIMxSource == LL_RCC_LPTIM2_CLKSOURCE)
{
/* LPTIM2CLK clock frequency */
switch (LL_RCC_GetLPTIMClockSource(LPTIMxSource))
{
case LL_RCC_LPTIM2_CLKSOURCE_LSI: /* LPTIM2 Clock is LSI Osc. */
if (LL_RCC_LSI_IsReady() == 1U)
{
if (READ_BIT(RCC->BDCR, RCC_BDCR_LSIPREDIV) == RCC_BDCR_LSIPREDIV)
{
lptim_frequency = LSI_VALUE / 128U;
}
else
{
lptim_frequency = LSI_VALUE;
}
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_HSI: /* LPTIM2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_LSE: /* LPTIM2 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_PCLK1: /* LPTIM2 Clock is PCLK1 */
lptim_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
/* unreachable code */
break;
}
}
else if (LPTIMxSource == LL_RCC_LPTIM34_CLKSOURCE)
{
/* LPTIM34CLK clock frequency */
switch (LL_RCC_GetLPTIMClockSource(LPTIMxSource))
{
case LL_RCC_LPTIM34_CLKSOURCE_LSI: /* LPTIM34 Clock is LSI Osc. */
if (LL_RCC_LSI_IsReady() == 1U)
{
if (READ_BIT(RCC->BDCR, RCC_BDCR_LSIPREDIV) == RCC_BDCR_LSIPREDIV)
{
lptim_frequency = LSI_VALUE / 128U;
}
else
{
lptim_frequency = LSI_VALUE;
}
}
break;
case LL_RCC_LPTIM34_CLKSOURCE_HSI: /* LPTIM34 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() == 1U)
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM34_CLKSOURCE_LSE: /* LPTIM34 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() == 1U)
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM34_CLKSOURCE_MSIK: /* LPTIM34 Clock is MSIK */
lptim_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
default:
/* unreachable code */
break;
}
}
else
{
/* nothing to do */
}
return lptim_frequency;
}
/**
* @brief Return SAIx clock frequency
* @param SAIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SAI1_CLKSOURCE
* @arg @ref LL_RCC_SAI2_CLKSOURCE
* @retval SAI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that PLL is not ready
*/
uint32_t LL_RCC_GetSAIClockFreq(uint32_t SAIxSource)
{
uint32_t sai_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SAI_CLKSOURCE(SAIxSource));
if (SAIxSource == LL_RCC_SAI1_CLKSOURCE)
{
/* SAI1CLK clock frequency */
switch (LL_RCC_GetSAIClockSource(SAIxSource))
{
case LL_RCC_SAI1_CLKSOURCE_PLL2: /* PLL2 clock used as SAI1 clock source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL2_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI1_CLKSOURCE_PLL3: /* PLL3 clock used as SAI1 clock source */
if (LL_RCC_PLL3_IsReady() == 1U)
{
if (LL_RCC_PLL3_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL3_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI1_CLKSOURCE_PLL1: /* PLL1 clock used as SAI1 clock source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL1_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI1_CLKSOURCE_PIN: /* External input clock used as SAI1 clock source */
sai_frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
default:
/* unreachable code */
break;
}
}
else if (SAIxSource == LL_RCC_SAI2_CLKSOURCE)
{
/* SAI2CLK clock frequency */
switch (LL_RCC_GetSAIClockSource(SAIxSource))
{
case LL_RCC_SAI2_CLKSOURCE_PLL2: /* PLL2 clock used as SAI2 clock source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL2_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI2_CLKSOURCE_PLL3: /* PLL3 clock used as SAI2 clock source */
if (LL_RCC_PLL3_IsReady() == 1U)
{
if (LL_RCC_PLL3_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL3_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI2_CLKSOURCE_PLL1: /* PLL1 clock used as SAI2 clock source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_SAI() != 0U)
{
sai_frequency = RCC_PLL1_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_SAI2_CLKSOURCE_PIN: /* External input clock used as SAI2 clock source */
sai_frequency = EXTERNAL_SAI2_CLOCK_VALUE;
break;
default:
/* unreachable code */
break;
}
}
else
{
/* nothing to do */
}
return sai_frequency;
}
/**
* @brief Return SDMMCx kernel clock frequency
* @param SDMMCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SDMMC_KERNELCLKSOURCE
* @retval SDMMC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator or PLL is not ready
*/
uint32_t LL_RCC_GetSDMMCKernelClockFreq(uint32_t SDMMCxSource)
{
uint32_t sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SDMMC_KERNELCLKSOURCE(SDMMCxSource));
/* SDMMC12CLK kernel clock frequency */
switch (LL_RCC_GetSDMMCKernelClockSource(SDMMCxSource))
{
case LL_RCC_SDMMC12_KERNELCLKSOURCE_48CLK: /* 48MHz clock from internal multiplexor used as SDMMC1/2 clock source */
sdmmc_frequency = LL_RCC_GetSDMMCClockFreq(LL_RCC_SDMMC_CLKSOURCE);
break;
case LL_RCC_SDMMC12_KERNELCLKSOURCE_PLL1: /* PLL1 "P" output (PLL1CLK) clock used as SDMMC1/2 clock source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_SAI() != 0U)
{
sdmmc_frequency = RCC_PLL1_GetFreqDomain_SAI();
}
}
break;
default:
/* unreachable code */
break;
}
return sdmmc_frequency;
}
/**
* @brief Return SDMMCx clock frequency
* @param SDMMCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SDMMC_CLKSOURCE
* @retval SDMMC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI /MSIK /HSI) or PLL is not ready
*/
uint32_t LL_RCC_GetSDMMCClockFreq(uint32_t SDMMCxSource)
{
uint32_t sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SDMMC_CLKSOURCE(SDMMCxSource));
/* SDMMC1CLK clock frequency */
switch (LL_RCC_GetSDMMCClockSource(SDMMCxSource))
{
case LL_RCC_SDMMC12_CLKSOURCE_PLL2: /* PLL2 clock used as SDMMC12 clock source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_48M() != 0U)
{
sdmmc_frequency = RCC_PLL2_GetFreqDomain_48M();
}
}
break;
case LL_RCC_SDMMC12_CLKSOURCE_PLL1: /* PLL1 clock used as SDMMC12 clock source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_48M() != 0U)
{
sdmmc_frequency = RCC_PLL1_GetFreqDomain_48M();
}
}
break;
case LL_RCC_SDMMC12_CLKSOURCE_MSIK: /* MSIK clock used as SDMMC12 clock source */
if (LL_RCC_MSIS_IsReady() == 1U)
{
sdmmc_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
}
break;
case LL_RCC_SDMMC12_CLKSOURCE_HSI48: /* HSI48 used as SDMMC1 clock source */
if (LL_RCC_HSI48_IsReady() == 1U)
{
sdmmc_frequency = HSI48_VALUE;
}
break;
default:
/* unreachable code */
break;
}
return sdmmc_frequency;
}
/**
* @brief Return RNGx clock frequency
* @param RNGxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_RNG_CLKSOURCE
* @retval RNG clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI or HSI48) or PLL is not ready
*/
uint32_t LL_RCC_GetRNGClockFreq(uint32_t RNGxSource)
{
uint32_t rng_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_RNG_CLKSOURCE(RNGxSource));
/* RNGCLK clock frequency */
switch (LL_RCC_GetRNGClockSource(RNGxSource))
{
case LL_RCC_RNG_CLKSOURCE_HSI: /* HSI clock used as RNG clock source */
if (LL_RCC_HSI_IsReady() == 1U)
{
rng_frequency = HSI_VALUE;
}
break;
case LL_RCC_RNG_CLKSOURCE_HSI48: /* HSI48 clock used as RNG clock source */
if (LL_RCC_HSI48_IsReady() == 1U)
{
rng_frequency = HSI48_VALUE;
}
break;
case LL_RCC_RNG_CLKSOURCE_HSI48_DIV2: /* HSI48DIV2 clock used as RNG clock source */
if (LL_RCC_HSI48_IsReady() == 1U)
{
rng_frequency = (HSI48_VALUE / 2U);
}
break;
default:
/* unreachable code */
break;
}
return rng_frequency;
}
/**
* @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 (MSI /HSI48) or PLL is not ready
*/
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))
{
case LL_RCC_USB_CLKSOURCE_PLL2: /* PLL2 clock used as USB clock source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_48M() != 0U)
{
usb_frequency = RCC_PLL2_GetFreqDomain_48M();
}
}
break;
case LL_RCC_USB_CLKSOURCE_PLL1: /* PLL1 clock used as USB clock source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_48M() != 0U)
{
usb_frequency = RCC_PLL1_GetFreqDomain_48M();
}
}
break;
case LL_RCC_USB_CLKSOURCE_MSIK: /* MSIK clock used as USB clock source */
if (LL_RCC_MSIK_IsReady() == 1U)
{
usb_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
}
break;
case LL_RCC_USB_CLKSOURCE_HSI48: /* HSI48 clock used as USB clock source */
if (LL_RCC_HSI48_IsReady() == 1U)
{
usb_frequency = HSI48_VALUE;
}
break;
default:
/* unreachable code */
break;
}
return usb_frequency;
}
/**
* @brief Return ADCxDAC clock frequency
* @param ADCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_ADCDAC_CLKSOURCE
* @retval ADC/DAC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI /HSI /MSIK) or PLL is not ready
*/
uint32_t LL_RCC_GetADCDACClockFreq(uint32_t ADCxSource)
{
uint32_t adcdac_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_ADCDAC_CLKSOURCE(ADCxSource));
/* ADCCLK clock frequency */
switch (LL_RCC_GetADCDACClockSource(ADCxSource))
{
case LL_RCC_ADCDAC_CLKSOURCE_HCLK: /* ADCDAC Clock is SYSCLK */
adcdac_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADCDAC_CLKSOURCE_SYSCLK: /* SYSCLK clock used as ADCDAC clock source */
adcdac_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADCDAC_CLKSOURCE_PLL2: /* PLL2 clock used as ADCDAC clock source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_ADC() != 0U)
{
adcdac_frequency = RCC_PLL2_GetFreqDomain_ADC();
}
}
break;
case LL_RCC_ADCDAC_CLKSOURCE_HSI: /*HSI clock used as ADCDAC clock source */
if (LL_RCC_HSI_IsReady() == 1U)
{
adcdac_frequency = HSI_VALUE;
}
break;
case LL_RCC_ADCDAC_CLKSOURCE_HSE: /*HSE clock used as ADCDAC clock source */
if (LL_RCC_HSE_IsReady() == 1U)
{
adcdac_frequency = HSE_VALUE;
}
break;
case LL_RCC_ADCDAC_CLKSOURCE_MSIK: /* MSIK clock used as ADCDAC clock source */
if (LL_RCC_MSIK_IsReady() == 1U)
{
adcdac_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
}
break;
default:
/* unreachable code */
break;
}
return adcdac_frequency;
}
/**
* @brief Return ADF1 clock frequency
* @param ADF1Source This parameter can be one of the following values:
* @arg @ref LL_RCC_ADF1_CLKSOURCE
* @retval ADF1 clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSIK) or PLL is not ready
*/
uint32_t LL_RCC_GetADF1ClockFreq(uint32_t ADF1Source)
{
uint32_t ADF1_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_ADF1_CLKSOURCE(ADF1Source));
/* ADF11CLK clock frequency */
switch (LL_RCC_GetADF1ClockSource(ADF1Source))
{
case LL_RCC_ADF1_CLKSOURCE_HCLK: /* ADF1 Clock is SYSCLK */
ADF1_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADF1_CLKSOURCE_PLL1: /* ADF1 Clock is PLL1 */
if (LL_RCC_PLL1_IsReady() != 0U)
{
if (LL_RCC_PLL1_IsEnabledDomain_SAI() != 0U)
{
ADF1_frequency = RCC_PLL1_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_ADF1_CLKSOURCE_PLL3: /* ADF1 Clock is PLL3 */
if (LL_RCC_PLL3_IsReady() != 0U)
{
if (LL_RCC_PLL3_IsEnabledDomain_48M() != 0U)
{
ADF1_frequency = RCC_PLL3_GetFreqDomain_48M();
}
}
break;
case LL_RCC_ADF1_CLKSOURCE_PIN: /* External input clock used as ADF1 clock source */
ADF1_frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case LL_RCC_ADF1_CLKSOURCE_MSIK: /* ADF1 Clock is MSIK */
ADF1_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
default:
/* unreachable code */
break;
}
return ADF1_frequency;
}
/**
* @brief Return MDF1 clock frequency
* @param MDF1Source This parameter can be one of the following values:
* @arg @ref LL_RCC_MDF1_CLKSOURCE
* @retval MDF1 clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSIK) or PLL is not ready
*/
uint32_t LL_RCC_GetMDF1ClockFreq(uint32_t MDF1Source)
{
uint32_t MDF1_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_MDF1_CLKSOURCE(MDF1Source));
/* MDF11CLK clock frequency */
switch (LL_RCC_GetMDF1ClockSource(MDF1Source))
{
case LL_RCC_MDF1_CLKSOURCE_HCLK: /* MDF1 Clock is SYSCLK */
MDF1_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_MDF1_CLKSOURCE_PLL1: /* MDF1 Clock is PLL1 */
if (LL_RCC_PLL1_IsReady() != 0U)
{
if (LL_RCC_PLL1_IsEnabledDomain_SAI() != 0U)
{
MDF1_frequency = RCC_PLL1_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_MDF1_CLKSOURCE_PLL3: /* MDF1 Clock is PLL3 */
if (LL_RCC_PLL3_IsReady() != 0U)
{
if (LL_RCC_PLL3_IsEnabledDomain_48M() != 0U)
{
MDF1_frequency = RCC_PLL3_GetFreqDomain_48M();
}
}
break;
case LL_RCC_MDF1_CLKSOURCE_PIN: /* External input clock used as MDF1 clock source */
MDF1_frequency = EXTERNAL_SAI1_CLOCK_VALUE;
break;
case LL_RCC_MDF1_CLKSOURCE_MSIK: /* MDF1 Clock is MSIK */
MDF1_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
break;
default:
/* unreachable code */
break;
}
return MDF1_frequency;
}
/**
* @brief Return DAC1 clock frequency
* @param DAC1Source This parameter can be one of the following values:
* @arg @ref LL_RCC_DAC1_CLKSOURCE
* @retval DAC1 clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that LSI or LSE oscillator is not ready
*/
uint32_t LL_RCC_GetDAC1ClockFreq(uint32_t DAC1Source)
{
uint32_t DAC1_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_DAC1_CLKSOURCE(DAC1Source));
/* DAC1CLK clock frequency */
switch (LL_RCC_GetDAC1ClockSource(DAC1Source))
{
case LL_RCC_DAC1_CLKSOURCE_LSI: /* DAC1 Clock is LSI */
DAC1_frequency = LSI_VALUE;
break;
case LL_RCC_DAC1_CLKSOURCE_LSE: /* DAC1 Clock is LSE */
DAC1_frequency = LSE_VALUE;
break;
default:
/* unreachable code */
break;
}
return DAC1_frequency;
}
/**
* @brief Return OCTOSPI clock frequency
* @param OCTOSPIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_OCTOSPI_CLKSOURCE
* @retval OCTOSPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator MSIK or PLL is not ready
*/
uint32_t LL_RCC_GetOCTOSPIClockFreq(uint32_t OCTOSPIxSource)
{
uint32_t octospi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_OCTOSPI_CLKSOURCE(OCTOSPIxSource));
/* OCTOSPI clock frequency */
switch (LL_RCC_GetOCTOSPIClockSource(OCTOSPIxSource))
{
case LL_RCC_OCTOSPI_CLKSOURCE_SYSCLK: /* OCTOSPI clock is SYSCLK */
octospi_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_OCTOSPI_CLKSOURCE_MSIK: /* MSIk clock used as OCTOSPI clock */
if (LL_RCC_MSIK_IsReady() == 1U)
{
octospi_frequency = __LL_RCC_CALC_MSIK_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIK_GetRange() :
LL_RCC_MSIK_GetRangeAfterStandby()));
}
break;
case LL_RCC_OCTOSPI_CLKSOURCE_PLL1: /* PLL1 clock used as OCTOSPI source */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_48M() != 0U)
{
octospi_frequency = RCC_PLL1_GetFreqDomain_48M();
}
}
break;
case LL_RCC_OCTOSPI_CLKSOURCE_PLL2: /* PLL2 clock used as OCTOSPI source */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_48M() != 0U)
{
octospi_frequency = RCC_PLL2_GetFreqDomain_48M();
}
}
break;
default:
/* unreachable code */
break;
}
return octospi_frequency;
}
/**
* @brief Return SAESx clock frequency
* @param SAESxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SAES_CLKSOURCE
* @retval SAEx clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator SHSI is not ready
*/
uint32_t LL_RCC_GetSAESClockFreq(uint32_t SAESxSource)
{
uint32_t rng_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SAES_CLKSOURCE(SAESxSource));
/* SAESCLK clock frequency */
switch (LL_RCC_GetSAESClockSource(SAESxSource))
{
case LL_RCC_SAES_CLKSOURCE_SHSI: /* SHSI clock used as SAES clock source */
if (LL_RCC_SHSI_IsReady() == 1U)
{
rng_frequency = HSI_VALUE;
}
break;
case LL_RCC_SAES_CLKSOURCE_SHSI_DIV2: /* SHSIDIV2 clock used as SAES clock source */
if (LL_RCC_SHSI_IsReady() == 1U)
{
rng_frequency = (HSI_VALUE / 2U);
}
break;
default:
/* unreachable code */
break;
}
return rng_frequency;
}
/**
* @brief Return FDCAN kernel clock frequency
* @param FDCANxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_FDCAN_CLKSOURCE
* @retval FDCAN kernel clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator HSE or PLL is not ready
*/
uint32_t LL_RCC_GetFDCANClockFreq(uint32_t FDCANxSource)
{
uint32_t fdcan_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_FDCAN_CLKSOURCE(FDCANxSource));
/* FDCAN kernel clock frequency */
switch (LL_RCC_GetFDCANClockSource(FDCANxSource))
{
case LL_RCC_FDCAN_CLKSOURCE_HSE: /* HSE clock used as FDCAN kernel clock */
if (LL_RCC_HSE_IsReady() == 1U)
{
fdcan_frequency = HSE_VALUE;
}
break;
case LL_RCC_FDCAN_CLKSOURCE_PLL1: /* PLL2 clock used as FDCAN kernel clock */
if (LL_RCC_PLL1_IsReady() == 1U)
{
if (LL_RCC_PLL1_IsEnabledDomain_48M() != 0U)
{
fdcan_frequency = RCC_PLL1_GetFreqDomain_48M();
}
}
break;
case LL_RCC_FDCAN_CLKSOURCE_PLL2: /* PLL2 clock used as FDCAN kernel clock */
if (LL_RCC_PLL2_IsReady() == 1U)
{
if (LL_RCC_PLL2_IsEnabledDomain_SAI() != 0U)
{
fdcan_frequency = RCC_PLL2_GetFreqDomain_SAI();
}
}
break;
default:
/* unreachable code */
break;
}
return fdcan_frequency;
}
#if defined(DSI)
/**
* @brief Return DSI clock frequency
* @param DSIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_DSI_CLKSOURCE
* @retval DSI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that external clock is used
*/
uint32_t LL_RCC_GetDSIClockFreq(uint32_t DSIxSource)
{
uint32_t dsi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
switch (LL_RCC_GetDSIClockSource(DSIxSource))
{
case LL_RCC_LTDC_CLKSOURCE_PLL3:
if (LL_RCC_PLL3_IsReady() != 0U)
{
if (LL_RCC_PLL3_IsEnabledDomain_SAI() != 0U)
{
dsi_frequency = RCC_PLL3_GetFreqDomain_SAI();
}
}
break;
case LL_RCC_DSI_CLKSOURCE_PHY:
dsi_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
default:
/* Nothing to do */
break;
}
return dsi_frequency;
}
#endif /* defined(DSI) */
#if defined(HSPI1)
/**
* @brief Return HSPI clock frequency
* @param HSPIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_HSPI_CLKSOURCE
* @retval HSPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
*/
uint32_t LL_RCC_GetHSPIClockFreq(uint32_t HSPIxSource)
{
uint32_t hspi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
switch (LL_RCC_GetHSPIClockSource(HSPIxSource))
{
case LL_RCC_HSPI_CLKSOURCE_SYSCLK:
hspi_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_HSPI_CLKSOURCE_PLL1:
if (LL_RCC_PLL1_IsReady() != 0U)
{
if (LL_RCC_PLL1_IsEnabledDomain_48M() != 0U)
{
hspi_frequency = RCC_PLL1_GetFreqDomain_48M();
}
}
break;
case LL_RCC_HSPI_CLKSOURCE_PLL2:
if (LL_RCC_PLL2_IsReady() != 0U)
{
if (LL_RCC_PLL2_IsEnabledDomain_48M() != 0U)
{
hspi_frequency = RCC_PLL2_GetFreqDomain_48M();
}
}
break;
case LL_RCC_HSPI_CLKSOURCE_PLL3:
if (LL_RCC_PLL3_IsReady() != 0U)
{
if (LL_RCC_PLL3_IsEnabledDomain_HSPI_LTDC() != 0U)
{
hspi_frequency = RCC_PLL3_GetFreqDomain_HSPI_LTDC();
}
}
break;
default:
/* Nothing to do */
break;
}
return hspi_frequency;
}
#endif /* defined(HSPI1) */
#if defined(LTDC)
/**
* @brief Return LTDC clock frequency
* @param LTDCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LTDC_CLKSOURCE
* @retval HSPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
*/
uint32_t LL_RCC_GetLTDCClockFreq(uint32_t LTDCxSource)
{
uint32_t ltdc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
switch (LL_RCC_GetHSPIClockSource(LTDCxSource))
{
case LL_RCC_LTDC_CLKSOURCE_PLL2:
if (LL_RCC_PLL2_IsReady() != 0U)
{
if (LL_RCC_PLL2_IsEnabledDomain_ADC() != 0U)
{
ltdc_frequency = RCC_PLL2_GetFreqDomain_ADC();
}
}
break;
case LL_RCC_LTDC_CLKSOURCE_PLL3:
if (LL_RCC_PLL3_IsReady() != 0U)
{
if (LL_RCC_PLL3_IsEnabledDomain_HSPI_LTDC() != 0U)
{
ltdc_frequency = RCC_PLL3_GetFreqDomain_HSPI_LTDC();
}
}
break;
default:
/* Nothing to do */
break;
}
return ltdc_frequency;
}
#endif /* defined(LTDC) */
/**
* @}
*/
/**
* @}
*/
/** @addtogroup RCC_LL_Private_Functions
* @{
*/
/**
* @brief Return SYSTEM clock frequency
* @retval SYSTEM clock frequency (in Hz)
*/
static uint32_t RCC_GetSystemClockFreq(void)
{
uint32_t frequency;
/* Get SYSCLK source -------------------------------------------------------*/
switch (LL_RCC_GetSysClkSource())
{
case LL_RCC_SYS_CLKSOURCE_STATUS_MSIS: /* MSIS used as system clock source */
frequency = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_HSI: /* HSI used as system clock source */
frequency = HSI_VALUE;
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_HSE: /* HSE used as system clock source */
frequency = HSE_VALUE;
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_PLL1: /* PLL1 used as system clock source */
frequency = RCC_PLL1_GetFreqDomain_SYS();
break;
default:
frequency = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return frequency;
}
/**
* @brief Return HCLK clock frequency
* @param SYSCLK_Frequency SYSCLK clock frequency
* @retval HCLK clock frequency (in Hz)
*/
static uint32_t RCC_GetHCLKClockFreq(uint32_t SYSCLK_Frequency)
{
/* HCLK clock frequency */
return __LL_RCC_CALC_HCLK_FREQ(SYSCLK_Frequency, LL_RCC_GetAHBPrescaler());
}
/**
* @brief Return PCLK1 clock frequency
* @param HCLK_Frequency HCLK clock frequency
* @retval PCLK1 clock frequency (in Hz)
*/
static uint32_t RCC_GetPCLK1ClockFreq(uint32_t HCLK_Frequency)
{
/* PCLK1 clock frequency */
return __LL_RCC_CALC_PCLK1_FREQ(HCLK_Frequency, LL_RCC_GetAPB1Prescaler());
}
/**
* @brief Return PCLK2 clock frequency
* @param HCLK_Frequency HCLK clock frequency
* @retval PCLK2 clock frequency (in Hz)
*/
static uint32_t RCC_GetPCLK2ClockFreq(uint32_t HCLK_Frequency)
{
/* PCLK2 clock frequency */
return __LL_RCC_CALC_PCLK2_FREQ(HCLK_Frequency, LL_RCC_GetAPB2Prescaler());
}
/**
* @brief Return PCLK3 clock frequency
* @param HCLK_Frequency HCLK clock frequency
* @retval PCLK3 clock frequency (in Hz)
*/
static uint32_t RCC_GetPCLK3ClockFreq(uint32_t HCLK_Frequency)
{
/* PCLK2 clock frequency */
return __LL_RCC_CALC_PCLK3_FREQ(HCLK_Frequency, LL_RCC_GetAPB3Prescaler());
}
/**
* @brief Return PLL1 clock frequency used for system domain
* @retval PLL1 clock frequency (in Hz)
*/
static uint32_t RCC_PLL1_GetFreqDomain_SYS(void)
{
uint32_t pllinputfreq;
uint32_t pllsource;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = LL_RCC_PLL1_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLL1SOURCE_MSIS: /* MSIS used as PLL1 clock source */
pllinputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL1SOURCE_HSI: /* HSI used as PLL1 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLL1SOURCE_HSE: /* HSE used as PLL1 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL1CLK_FREQ(pllinputfreq, LL_RCC_PLL1_GetDivider(),
LL_RCC_PLL1_GetN(), LL_RCC_PLL1_GetR());
}
/**
* @brief Return PLL1 clock frequency used for SAI domain
* @retval PLL1 clock frequency (in Hz)
*/
static uint32_t RCC_PLL1_GetFreqDomain_SAI(void)
{
uint32_t pll1inputfreq;
uint32_t pll1outputfreq;
uint32_t pll1source;
uint32_t pll1n;
uint32_t pll1pdiv;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE / PLLM) * PLLN
SAI Domain clock = PLL_VCO / PLL1P
*/
pll1source = LL_RCC_PLL1_GetMainSource();
switch (pll1source)
{
case LL_RCC_PLL1SOURCE_MSIS: /* MSI used as PLL1 clock source */
pll1inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL1SOURCE_HSI: /* HSI used as PLL1 clock source */
pll1inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL1SOURCE_HSE: /* HSE used as PLL1 clock source */
pll1inputfreq = HSE_VALUE;
break;
default:
pll1inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
pll1n = LL_RCC_PLL1_GetN();
pll1pdiv = LL_RCC_PLL1_GetP();
if ((pll1n >= 8U) && (pll1pdiv >= 2U))
{
pll1outputfreq = __LL_RCC_CALC_PLL1CLK_SAI_FREQ(pll1inputfreq, LL_RCC_PLL1_GetDivider(),
pll1n, pll1pdiv);
}
else
{
pll1outputfreq = 0; /* Invalid PLL1N or PLL1PDIV value */
}
return pll1outputfreq;
}
/**
* @brief Return PLL clock frequency used for 48 MHz domain
* @retval PLL clock frequency (in Hz)
*/
static uint32_t RCC_PLL1_GetFreqDomain_48M(void)
{
uint32_t pll1inputfreq;
uint32_t pll1source;
/* PLL1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL1M) * PLL1N
48M Domain clock = PLL1_VCO / PLL1Q
*/
pll1source = LL_RCC_PLL1_GetMainSource();
switch (pll1source)
{
case LL_RCC_PLL1SOURCE_MSIS: /* MSI used as PLL1 clock source */
pll1inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL1SOURCE_HSI: /* HSI used as PLL1 clock source */
pll1inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL1SOURCE_HSE: /* HSE used as PLL1 clock source */
pll1inputfreq = HSE_VALUE;
break;
default:
pll1inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL1CLK_48M_FREQ(pll1inputfreq, LL_RCC_PLL1_GetDivider(),
LL_RCC_PLL1_GetN(), LL_RCC_PLL1_GetQ());
}
/**
* @brief Return PLL2 clock frequency used for SAI domain
* @retval PLL2 clock frequency (in Hz)
*/
static uint32_t RCC_PLL2_GetFreqDomain_SAI(void)
{
uint32_t pll2inputfreq;
uint32_t pll2outputfreq;
uint32_t pll2source;
uint32_t pll2n;
uint32_t pll2pdiv;
/* PLL2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL2M) * PLL2N */
/* SAI Domain clock = PLL2_VCO / PLL2P */
pll2source = LL_RCC_PLL2_GetSource();
switch (pll2source)
{
case LL_RCC_PLL2SOURCE_MSIS: /* MSI used as PLLSAI1 clock source */
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL2SOURCE_HSI: /* HSI used as PLL2 clock source */
pll2inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL2SOURCE_HSE: /* HSE used as PLL2 clock source */
pll2inputfreq = HSE_VALUE;
break;
default:
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
pll2n = LL_RCC_PLL2_GetN();
pll2pdiv = LL_RCC_PLL2_GetP();
if ((pll2n >= 8U) && (pll2pdiv >= 2U))
{
pll2outputfreq = __LL_RCC_CALC_PLL2CLK_SAI_FREQ(pll2inputfreq, LL_RCC_PLL2_GetDivider(),
pll2n, pll2pdiv);
}
else
{
pll2outputfreq = 0; /* Invalid PLL2N or PLL2PDIV value */
}
return pll2outputfreq;
}
/**
* @brief Return PLL2 clock frequency used for 48Mhz domain
* @retval PLL2 clock frequency (in Hz)
*/
static uint32_t RCC_PLL2_GetFreqDomain_48M(void)
{
uint32_t pll2inputfreq;
uint32_t pll2source;
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL2M) * PLL2N */
/* 48M Domain clock = PLL2_VCO / PLL2Q */
pll2source = LL_RCC_PLL2_GetSource();
switch (pll2source)
{
case LL_RCC_PLL2SOURCE_MSIS: /* MSI used as PLL2 clock source */
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL2SOURCE_HSI: /* HSI used as PLL2 clock source */
pll2inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL2SOURCE_HSE: /* HSE used as PLL2 clock source */
pll2inputfreq = HSE_VALUE;
break;
default:
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL2CLK_48M_FREQ(pll2inputfreq, LL_RCC_PLL2_GetDivider(),
LL_RCC_PLL2_GetN(), LL_RCC_PLL2_GetQ());
}
/**
* @brief Return PLL2 clock frequency used for ADC domain
* @retval PLL2 clock frequency (in Hz)
*/
static uint32_t RCC_PLL2_GetFreqDomain_ADC(void)
{
uint32_t pll2inputfreq;
uint32_t pll2source;
/* PLL2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL2M) * PLL2N */
/* 48M Domain clock = PLL2_VCO / PLL2R */
pll2source = LL_RCC_PLL2_GetSource();
switch (pll2source)
{
case LL_RCC_PLL2SOURCE_MSIS: /* MSI used as PLL2 clock source */
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL2SOURCE_HSI: /* HSI used as PLL2 clock source */
pll2inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL2SOURCE_HSE: /* HSE used as PLL2 clock source */
pll2inputfreq = HSE_VALUE;
break;
default:
pll2inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL2CLK_ADC_FREQ(pll2inputfreq, LL_RCC_PLL2_GetDivider(),
LL_RCC_PLL2_GetN(), LL_RCC_PLL2_GetR());
}
/**
* @brief Return PLL3 clock frequency used for SAI domain
* @retval PLL3 clock frequency (in Hz)
*/
static uint32_t RCC_PLL3_GetFreqDomain_SAI(void)
{
uint32_t pll3inputfreq;
uint32_t pll3outputfreq;
uint32_t pll3source;
uint32_t pll3n;
uint32_t pll3pdiv;
/* PLL3_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL3M) * PLL3N */
/* SAI Domain clock = PLL3_VCO / PLL3P */
pll3source = LL_RCC_PLL3_GetSource();
switch (pll3source)
{
case LL_RCC_PLL3SOURCE_MSIS: /* MSI used as PLL3 clock source */
pll3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL3SOURCE_HSI: /* HSI used as PLL3 clock source */
pll3inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL3SOURCE_HSE: /* HSE used as PLL3 clock source */
pll3inputfreq = HSE_VALUE;
break;
default:
pll3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
pll3n = LL_RCC_PLL3_GetN();
pll3pdiv = LL_RCC_PLL3_GetP();
if ((pll3n >= 8U) && (pll3pdiv >= 2U))
{
pll3outputfreq = __LL_RCC_CALC_PLL3CLK_SAI_FREQ(pll3inputfreq, LL_RCC_PLL3_GetDivider(),
pll3n, pll3pdiv);
}
else
{
pll3outputfreq = 0; /* Invalid PLL3N or PLL3PDIV value */
}
return pll3outputfreq;
}
/**
* @}
*/
/**
* @brief Return PLL3clock frequency used for 48Mhz domain
* @retval PLL3 clock frequency (in Hz)
*/
static uint32_t RCC_PLL3_GetFreqDomain_48M(void)
{
uint32_t PLL3inputfreq;
uint32_t PLL3source;
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL3M) * PLL3N */
/* 48M Domain clock = PLL3_VCO / PLL3Q */
PLL3source = LL_RCC_PLL3_GetSource();
switch (PLL3source)
{
case LL_RCC_PLL3SOURCE_MSIS: /* MSI used as PLL3 clock source */
PLL3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL3SOURCE_HSI: /* HSI used as PLL3 clock source */
PLL3inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL3SOURCE_HSE: /* HSE used as PLL3 clock source */
PLL3inputfreq = HSE_VALUE;
break;
default:
PLL3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL3CLK_48M_FREQ(PLL3inputfreq, LL_RCC_PLL3_GetDivider(),
LL_RCC_PLL3_GetN(), LL_RCC_PLL3_GetQ());
}
#if defined(HSPI1) || defined(LTDC)
/**
* @brief Return PLL3 clock frequency used for HSPI_LTDC domain
* @retval PLL3 clock frequency (in Hz)
*/
static uint32_t RCC_PLL3_GetFreqDomain_HSPI_LTDC(void)
{
uint32_t pll3inputfreq;
uint32_t pll3source;
/* PLL3_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLL2M) * PLL3N */
pll3source = LL_RCC_PLL3_GetSource();
switch (pll3source)
{
case LL_RCC_PLL3SOURCE_MSIS: /* MSI used as PLL2 clock source */
pll3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
case LL_RCC_PLL3SOURCE_HSI: /* HSI used as PLL2 clock source */
pll3inputfreq = HSI_VALUE;
break;
case LL_RCC_PLL3SOURCE_HSE: /* HSE used as PLL2 clock source */
pll3inputfreq = HSE_VALUE;
break;
default:
pll3inputfreq = __LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
((LL_RCC_MSI_IsEnabledRangeSelect() == 1U) ?
LL_RCC_MSIS_GetRange() :
LL_RCC_MSIS_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLL3CLK_HSPI_LTDC_FREQ(pll3inputfreq, LL_RCC_PLL3_GetDivider(),
LL_RCC_PLL3_GetN(), LL_RCC_PLL3_GetR());
}
#endif /* HSPI1 || LTDC */
/**
* @}
*/
#endif /* defined(RCC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_rcc.c
|
C
|
apache-2.0
| 79,204
|
/**
******************************************************************************
* @file stm32u5xx_ll_rng.c
* @author MCD Application Team
* @brief RNG LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_rng.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (RNG)
/** @addtogroup RNG_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup RNG_LL_Private_Macros RNG Private Macros
* @{
*/
#define IS_LL_RNG_CED(__MODE__) (((__MODE__) == LL_RNG_CED_ENABLE) || \
((__MODE__) == LL_RNG_CED_DISABLE))
#define IS_LL_RNG_CLOCK_DIVIDER(__CLOCK_DIV__) ((__CLOCK_DIV__) <=0x0Fu)
#define IS_LL_RNG_NIST_COMPLIANCE(__NIST_COMPLIANCE__) (((__NIST_COMPLIANCE__) == LL_RNG_NIST_COMPLIANT) || \
((__NIST_COMPLIANCE__) == LL_RNG_NOTNIST_COMPLIANT))
#define IS_LL_RNG_CONFIG1 (__CONFIG1__) ((__CONFIG1__) <= 0x3FUL)
#define IS_LL_RNG_CONFIG2 (__CONFIG2__) ((__CONFIG2__) <= 0x07UL)
#define IS_LL_RNG_CONFIG3 (__CONFIG3__) ((__CONFIG3__) <= 0xFUL)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RNG_LL_Exported_Functions
* @{
*/
/** @addtogroup RNG_LL_EF_Init
* @{
*/
/**
* @brief De-initialize RNG registers (Registers restored to their default values).
* @param RNGx RNG Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RNG registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_RNG_DeInit(RNG_TypeDef *RNGx)
{
/* Check the parameters */
assert_param(IS_RNG_ALL_INSTANCE(RNGx));
/* Enable RNG reset state */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_RNG);
/* Release RNG from reset state */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_RNG);
return (SUCCESS);
}
/**
* @brief Initialize RNG registers according to the specified parameters in RNG_InitStruct.
* @param RNGx RNG Instance
* @param RNG_InitStruct pointer to a LL_RNG_InitTypeDef structure
* that contains the configuration information for the specified RNG peripheral.
* @retval An ErrorStatus enumeration value:
* - 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)
{
/* Check the parameters */
assert_param(IS_RNG_ALL_INSTANCE(RNGx));
assert_param(IS_LL_RNG_CED(RNG_InitStruct->ClockErrorDetection));
/* Clock Error Detection Configuration when CONDRT bit is set to 1 */
MODIFY_REG(RNGx->CR, RNG_CR_CED | RNG_CR_CONDRST, RNG_InitStruct->ClockErrorDetection | RNG_CR_CONDRST);
/* Writing bits CONDRST=0*/
CLEAR_BIT(RNGx->CR, RNG_CR_CONDRST);
return (SUCCESS);
}
/**
* @brief Set each @ref LL_RNG_InitTypeDef field to default value.
* @param RNG_InitStruct pointer to a @ref LL_RNG_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_RNG_StructInit(LL_RNG_InitTypeDef *RNG_InitStruct)
{
/* Set RNG_InitStruct fields to default values */
RNG_InitStruct->ClockErrorDetection = LL_RNG_CED_ENABLE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* RNG */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_rng.c
|
C
|
apache-2.0
| 4,433
|
/**
******************************************************************************
* @file stm32u5xx_ll_rtc.c
* @author MCD Application Team
* @brief RTC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_rtc.h"
#include "stm32u5xx_ll_cortex.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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(__VALUE__) (((__VALUE__) == LL_RTC_MONTH_JANUARY) \
|| ((__VALUE__) == LL_RTC_MONTH_FEBRUARY) \
|| ((__VALUE__) == LL_RTC_MONTH_MARCH) \
|| ((__VALUE__) == LL_RTC_MONTH_APRIL) \
|| ((__VALUE__) == LL_RTC_MONTH_MAY) \
|| ((__VALUE__) == LL_RTC_MONTH_JUNE) \
|| ((__VALUE__) == LL_RTC_MONTH_JULY) \
|| ((__VALUE__) == LL_RTC_MONTH_AUGUST) \
|| ((__VALUE__) == LL_RTC_MONTH_SEPTEMBER) \
|| ((__VALUE__) == LL_RTC_MONTH_OCTOBER) \
|| ((__VALUE__) == LL_RTC_MONTH_NOVEMBER) \
|| ((__VALUE__) == LL_RTC_MONTH_DECEMBER))
#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, 0x00000000U);
WRITE_REG(RTCx->DR, (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0));
WRITE_REG(RTCx->CR, 0x00000000U);
WRITE_REG(RTCx->WUTR, RTC_WUTR_WUT);
WRITE_REG(RTCx->PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT));
WRITE_REG(RTCx->ALRMAR, 0x00000000U);
WRITE_REG(RTCx->ALRMBR, 0x00000000U);
WRITE_REG(RTCx->SHIFTR, 0x00000000U);
WRITE_REG(RTCx->CALR, 0x00000000U);
WRITE_REG(RTCx->ALRMASSR, 0x00000000U);
WRITE_REG(RTCx->ALRMBSSR, 0x00000000U);
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTCx);
/* 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 */
/* Reset TAMP CR1 and CR2 registers */
WRITE_REG(TAMP->CR1, 0x00000000U);
WRITE_REG(TAMP->CR2, 0x00000000U);
#if defined (RTC_OTHER_SUPPORT)
WRITE_REG(TAMP->CR3, 0x00000000U);
WRITE_REG(TAMP->SECCFGR, 0x00000000U);
WRITE_REG(TAMP->PRIVCFGR, 0x00000000U);
#endif /* RTC_OTHER_SUPPORT */
WRITE_REG(TAMP->FLTCR, 0x00000000U);
#if defined (RTC_ACTIVE_TAMPER_SUPPORT)
WRITE_REG(TAMP->ATCR1, 0x00070000U);
WRITE_REG(TAMP->ATCR2, 0x00000000U);
#endif /* RTC_ACTIVE_TAMPER_SUPPORT */
WRITE_REG(TAMP->IER, 0x00000000U);
WRITE_REG(TAMP->SCR, 0xFFFFFFFFU);
WRITE_REG(TAMP->ERCFGR, 0x00000000U);
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 = 0x00U;
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_DAY(RTC_DateStruct->Day));
}
else
{
assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year)));
assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day)));
}
assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month));
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;
ErrorStatus status = SUCCESS;
uint32_t tmp;
/* 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 != 0U))
{
if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
{
timeout--;
}
tmp = LL_RTC_IsActiveFlag_RS(RTCx);
if (timeout == 0U)
{
status = ERROR;
}
}
if (status != ERROR)
{
timeout = RTC_SYNCHRO_TIMEOUT;
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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_rtc.c
|
C
|
apache-2.0
| 31,581
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_HAL_Driver
* @{
*/
/** @defgroup SDMMC_LL SDMMC Low Layer
* @brief Low layer module for SD
* @{
*/
#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(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(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(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(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(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(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 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 */
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_sdmmc.c
|
C
|
apache-2.0
| 58,525
|
/**
******************************************************************************
* @file stm32u5xx_ll_spi.c
* @author MCD Application Team
* @brief SPI LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_spi.h"
#include "stm32u5xx_ll_bus.h"
#include "stm32u5xx_ll_rcc.h"
#ifdef GENERATOR_I2S_PRESENT
#include "stm32u5xx_ll_rcc.h"
#endif /* GENERATOR_I2S_PRESENT*/
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined(SPI1) || defined(SPI2) || defined(SPI3)
/** @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(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_APB3_GRP1_ForceReset(LL_APB3_GRP1_PERIPH_SPI3);
/* Release reset of SPI clock */
LL_APB3_GRP1_ReleaseReset(LL_APB3_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_APB5_GRP1_ForceReset(LL_APB5_GRP1_PERIPH_SPI6);
/* Release reset of SPI clock */
LL_APB5_GRP1_ReleaseReset(LL_APB5_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);
}
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;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(SPI1) || defined(SPI2) || defined(SPI3) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_spi.c
|
C
|
apache-2.0
| 25,642
|
/**
******************************************************************************
* @file stm32u5xx_ll_tim.c
* @author MCD Application Team
* @brief TIM LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_tim.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (TIM1) \
|| defined (TIM2) \
|| defined (TIM3) \
|| defined (TIM4) \
|| defined (TIM5) \
|| defined (TIM6) \
|| defined (TIM7) \
|| defined (TIM8) \
|| defined (TIM15) \
|| defined (TIM16) \
|| defined (TIM17) \
|| defined (TIM20)
/** @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_ASSYMETRIC_PWM1) \
|| ((__VALUE__) == LL_TIM_OCMODE_ASSYMETRIC_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, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC5Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC6Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC4Config(TIM_TypeDef *TIMx, 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(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 == TIM8)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM8);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM8);
}
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, 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, 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, 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, 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, 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, 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));
/* 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_MOE, TIM_BDTRInitStruct->AutomaticOutput);
if (IS_TIM_ADVANCED_INSTANCE(TIMx))
{
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);
}
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, 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));
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);
/* 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->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* 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, 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));
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);
/* 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->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* 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, 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));
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);
/* 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->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* 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, 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));
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);
/* 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->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* 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, 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, 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, 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, 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, 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, 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 CC2E 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 || TIM8 || TIM15 || TIM16 || TIM17 || TIM20 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_tim.c
|
C
|
apache-2.0
| 55,605
|
/**
******************************************************************************
* @file stm32u5xx_ll_ucpd.c
* @author MCD Application Team
* @brief UCPD LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_ucpd.h"
#include "stm32u5xx_ll_bus.h"
#include "stm32u5xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_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, 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 */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_ucpd.c
|
C
|
apache-2.0
| 4,789
|
/**
******************************************************************************
* @file stm32u5xx_ll_usart.c
* @author MCD Application Team
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_usart.h"
#include "stm32u5xx_ll_rcc.h"
#include "stm32u5xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (UART4) || defined (UART5)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* 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__) <= 20000000U)
/* __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(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);
}
#if defined(USART6)
else if (USARTx == USART6)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART6);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART6);
}
#endif /* USART6 */
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, 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_USART2_CLKSOURCE);
}
else if (USARTx == USART3)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE);
}
else if (USARTx == UART4)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART4_CLKSOURCE);
}
else if (USARTx == UART5)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART5_CLKSOURCE);
}
#if defined(USART6)
else if (USARTx == USART6)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART6_CLKSOURCE);
}
#endif /* USART6 */
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 = 9600U;
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, 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 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_usart.c
|
C
|
apache-2.0
| 18,317
|
/**
******************************************************************************
* @file stm32u5xx_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) 2021 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_OTG_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 "stm32u5xx_hal.h"
/** @addtogroup STM32U5xx_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 (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx)
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
/* 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);
}
#endif /* defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx) */
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(1U);
ms++;
} while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < 50U));
}
else if (mode == USB_DEVICE_MODE)
{
USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD;
do
{
HAL_Delay(1U);
ms++;
} while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < 50U));
}
else
{
return HAL_ERROR;
}
if (ms == 50U)
{
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;
}
/* 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 defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx)
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;
#endif /* defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx) */
}
else
{
#if defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx)
/* B-peripheral session valid override disable */
USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN;
USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL;
#endif /* defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx) */
/* Enable HW VBUS sensing */
USBx->GCCFG |= USB_OTG_GCCFG_VBDEN;
}
/* Restart the Phy Clock */
USBx_PCGCCTL = 0U;
/* Device mode configuration */
USBx_DEVICE->DCFG |= DCFG_FRAME_INTERVAL_80;
#if defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx)
if (cfg.phy_itface == USB_OTG_HS_EMBEDDED_PHY)
{
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
#endif /* defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx) */
{
/* 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 > 200000U)
{
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 > 200000U)
{
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 > 200000U)
{
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 > 200000U)
{
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(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(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(USB_OTG_GlobalTypeDef *USBx, 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(USB_OTG_GlobalTypeDef *USBx, 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(USB_OTG_GlobalTypeDef *USBx, 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(USB_OTG_GlobalTypeDef *USBx, 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);
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 (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_EP0StartXfer : setup and starts a transfer over the EP 0
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @param dma USB dma enabled or disabled
* This parameter can be one of these values:
* 0 : DMA feature not used
* 1 : DMA feature used
* @retval HAL status
*/
HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma)
{
uint32_t USBx_BASE = (uint32_t)USBx;
uint32_t epnum = (uint32_t)ep->num;
/* 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 (ep->xfer_len > ep->maxpacket)
{
ep->xfer_len = ep->maxpacket;
}
USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1U << 19));
USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len);
}
if (dma == 1U)
{
if ((uint32_t)ep->dma_addr != 0U)
{
USBx_INEP(epnum)->DIEPDMA = (uint32_t)(ep->dma_addr);
}
/* 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);
/* Enable the Tx FIFO Empty Interrupt for this EP */
if (ep->xfer_len > 0U)
{
USBx_DEVICE->DIEPEMPMSK |= 1UL << (ep->num & EP_ADDR_MSK);
}
}
}
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 (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_PKTCNT & (1U << 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);
}
}
/* 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(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(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(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(USB_OTG_GlobalTypeDef *USBx, 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(USB_OTG_GlobalTypeDef *USBx, 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(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(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(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 HAL status
*/
uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef *USBx)
{
uint32_t tmpreg;
tmpreg = USBx->GINTSTS;
tmpreg &= USBx->GINTMSK;
return tmpreg;
}
/**
* @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status
* @param USBx Selected device
* @retval HAL status
*/
uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx)
{
uint32_t 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 HAL status
*/
uint32_t USB_ReadDevAllInEpInterrupt(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(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(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(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(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(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup)
{
uint32_t USBx_BASE = (uint32_t)USBx;
uint32_t gSNPSiD = *(__IO 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 > 200000U)
{
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 > 200000U)
{
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;
/* Restart the Phy Clock */
USBx_PCGCCTL = 0U;
#if defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx)
/* Disable VBUS override */
USBx->GCCFG &= ~(USB_OTG_GCCFG_VBVALOVAL | USB_OTG_GCCFG_VBVALEXTOEN);
#endif /* defined (STM32U595xx) || defined (STM32U5A5xx) || defined (STM32U599xx) || defined (STM32U5A9xx) */
/* Disable VBUS sensing */
USBx->GCCFG &= ~(USB_OTG_GCCFG_VBDEN);
#if defined (STM32U575xx) || defined (STM32U585xx)
/* Disable Battery chargin detector */
USBx->GCCFG &= ~(USB_OTG_GCCFG_BCDEN);
#endif /* defined (STM32U575xx) || defined (STM32U585xx) */
if ((USBx->CID & (0x1U << 14)) != 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 = 0xFFFFFFFFU;
USBx_HC(i)->HCINTMSK = 0U;
}
/* Disable all interrupts. */
USBx->GINTMSK = 0U;
/* Clear any pending interrupts */
USBx->GINTSTS = 0xFFFFFFFFU;
if ((USBx->CID & (0x1U << 14)) != 0U)
{
/* 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
{
/* 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(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 = 48000U;
}
else if (freq == HCFG_6_MHZ)
{
USBx_HOST->HFIR = 6000U;
}
else
{
/* ... */
}
return HAL_OK;
}
/**
* @brief USB_OTG_ResetPort : Reset Host Port
* @param USBx Selected device
* @retval HAL status
* @note (1)The application must wait at least 10 ms
* before clearing the reset bit.
*/
HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx)
{
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(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 *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 *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 = 0xFFFFFFFFU;
/* 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 ((USBx->CID & (0x1U << 14)) != 0U)
{
USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET |
USB_OTG_HCINTMSK_ACKM;
}
}
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;
}
/* 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) | 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 = 256U;
if (((USBx->CID & (0x1U << 14)) != 0U) && (hc->speed == USBH_HS_SPEED))
{
/* in DMA mode host Core automatically issues ping in case of NYET/NAK */
if ((dma == 1U) && ((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK)))
{
USBx_HC((uint32_t)ch_num)->HCINTMSK &= ~(USB_OTG_HCINTMSK_NYET |
USB_OTG_HCINTMSK_ACKM |
USB_OTG_HCINTMSK_NAKM);
}
if ((dma == 0U) && (hc->do_ping == 1U))
{
(void)USB_DoPing(USBx, hc->ch_num);
return HAL_OK;
}
}
/* 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;
/* 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))
{
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(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(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;
if (((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == USB_OTG_GAHBCFG_DMAEN) &&
(ChannelEna == 0U))
{
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_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(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 = 0xFFFFFFFFU;
USBx->GINTSTS = 0xFFFFFFFFU;
(void)USB_EnableGlobalInt(USBx);
return ret;
}
/**
* @brief USB_ActivateRemoteWakeup active remote wakeup signalling
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateRemoteWakeup(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(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) */
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_usb.c
|
C
|
apache-2.0
| 60,993
|
/**
******************************************************************************
* @file stm32u5xx_ll_utils.c
* @author MCD Application Team
* @brief UTILS LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2021 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 "stm32u5xx_ll_utils.h"
#include "stm32u5xx_ll_rcc.h"
#include "stm32u5xx_ll_system.h"
#include "stm32u5xx_ll_pwr.h"
#include <math.h>
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32U5xx_LL_Driver
* @{
*/
/** @addtogroup UTILS_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup UTILS_LL_Private_Constants
* @{
*/
#define UTILS_MAX_FREQUENCY_SCALE0 160000000U /*!< Maximum frequency for system clock at power scale0, in Hz */
#define UTILS_MAX_FREQUENCY_SCALE1 100000000U /*!< Maximum frequency for system clock at power scale1, in Hz */
#define UTILS_MAX_FREQUENCY_SCALE2 50000000U /*!< Maximum frequency for system clock at power scale2, in Hz */
#define UTILS_MAX_FREQUENCY_SCALE3 24000000U /*!< Maximum frequency for system clock at power scale3, in Hz */
/* Defines used for PLL range */
#define UTILS_PLLVCO_INPUT_MIN 4000000U /*!< Frequency min for PLLVCO input, in Hz */
#define UTILS_PLLVCO_INPUT_MAX 16000000U /*!< Frequency max for PLLVCO input, in Hz */
#define UTILS_PLLVCO_OUTPUT_MIN 64000000U /*!< Frequency min for PLLVCO output, in Hz */
#define UTILS_PLLVCO_OUTPUT_MAX 344000000U /*!< Frequency max for 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 */
#define UTILS_SCALE1_LATENCY0_FREQ (32000000U) /*!< HCLK frequency to set FLASH latency 0 in power scale 1 */
#define UTILS_SCALE1_LATENCY1_FREQ (64000000U) /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */
#define UTILS_SCALE1_LATENCY2_FREQ (96000000U) /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */
#define UTILS_SCALE1_LATENCY3_FREQ (128000000U) /*!< HCLK frequency to set FLASH latency 3 in power scale 1 */
#define UTILS_SCALE1_LATENCY4_FREQ (160000000U) /*!< HCLK frequency to set FLASH latency 4 in power scale 1 */
#define UTILS_SCALE2_LATENCY0_FREQ (25000000U) /*!< HCLK frequency to set FLASH latency 0 in power scale 2 */
#define UTILS_SCALE2_LATENCY1_FREQ (50000000U) /*!< HCLK frequency to set FLASH latency 1 in power scale 2 */
#define UTILS_SCALE2_LATENCY2_FREQ (75000000U) /*!< HCLK frequency to set FLASH latency 2 in power scale 2 */
#define UTILS_SCALE2_LATENCY3_FREQ (100000000U) /*!< HCLK frequency to set FLASH latency 3 in power scale 2 */
#define UTILS_SCALE3_LATENCY0_FREQ (12500000U) /*!< HCLK frequency to set FLASH latency 0 in power scale 3 */
#define UTILS_SCALE3_LATENCY1_FREQ (25000000U) /*!< HCLK frequency to set FLASH latency 1 in power scale 3 */
#define UTILS_SCALE3_LATENCY2_FREQ (37500000U) /*!< HCLK frequency to set FLASH latency 2 in power scale 3 */
#define UTILS_SCALE3_LATENCY3_FREQ (50000000U) /*!< HCLK frequency to set FLASH latency 3 in power scale 3 */
#define UTILS_SCALE4_LATENCY0_FREQ (8000000U) /*!< HCLK frequency to set FLASH latency 0 in power scale 4 */
#define UTILS_SCALE4_LATENCY1_FREQ (16000000U) /*!< HCLK frequency to set FLASH latency 1 in power scale 4 */
#define UTILS_SCALE4_LATENCY2_FREQ (24000000U) /*!< HCLK frequency to set FLASH latency 2 in power scale 4 */
/**
* @}
*/
/* 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_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_APB3_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB3_DIV_1) \
|| ((__VALUE__) == LL_RCC_APB3_DIV_2) \
|| ((__VALUE__) == LL_RCC_APB3_DIV_4) \
|| ((__VALUE__) == LL_RCC_APB3_DIV_8) \
|| ((__VALUE__) == LL_RCC_APB3_DIV_16))
#define IS_LL_UTILS_PLLM_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 16U))
#define IS_LL_UTILS_PLLN_VALUE(__VALUE__) ((4U <= (__VALUE__)) && ((__VALUE__) <= 512U))
#define IS_LL_UTILS_PLLR_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 128U))
#define IS_LL_UTILS_PLLVCO_INPUT(__VALUE__) ((UTILS_PLLVCO_INPUT_MIN <= (__VALUE__))\
&& ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX))
#define IS_LL_UTILS_PLLVCO_OUTPUT(__VALUE__) ((UTILS_PLLVCO_OUTPUT_MIN <= (__VALUE__))\
&& ((__VALUE__) <= UTILS_PLLVCO_OUTPUT_MAX))
#define IS_LL_UTILS_PLL_FREQUENCY(__VALUE__) ((LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE4) ? \
((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE0) : \
(LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE1) ? \
((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1) : \
(LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE2) ? \
((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE2) : \
((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE3))
#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,
LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct);
static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency,
LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct);
static ErrorStatus UTILS_PLL_IsBusy(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 HCLKFrequency HCLK frequency in Hz
* @note HCLK frequency can be calculated thanks to RCC helper macro or function @ref LL_RCC_GetSystemClocksFreq
* @retval None
*/
void LL_Init1msTick(uint32_t HCLKFrequency)
{
/* Use frequency provided in argument */
LL_InitTick(HCLKFrequency, 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)
{
__IO uint32_t tmp = SysTick->CTRL; /* Clear the COUNTFLAG first */
uint32_t tmpDelay = Delay;
/* Add this code to indicate that local variable is not used */
((void)tmp);
/* Add a period to guaranty minimum wait */
if (tmpDelay < LL_MAX_DELAY)
{
tmpDelay++;
}
while (tmpDelay != 0U)
{
if ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0U)
{
tmpDelay--;
}
}
}
/**
* @}
*/
/** @addtogroup UTILS_EF_SYSTEM
* @brief System Configuration functions
*
@verbatim
===============================================================================
##### System Configuration functions #####
===============================================================================
[..]
System, AHB and APB buses clocks configuration
(+) The maximum frequency of the SYSCLK, HCLK, PCLK1 and PCLK2, PCLK3 is
160000000 Hz.
@endverbatim
@internal
Depending on the device voltage range, the maximum frequency should be
adapted accordingly:
(++) Table 1. HCLK clock frequency for STM32U5 devices
(++) +-----------------------------------------------------------------------------------------------+
(++) | Latency | HCLK clock frequency (MHz) |
(++) | |-----------------------------------------------------------------------------|
(++) | | voltage range 1 | voltage range 2 | voltage range 3 | voltage range 4 |
(++) | | 1.2 V | 1.1 V | 1.0 V | 0.9 V |
(++) |-----------------|-------------------|------------------|------------------|-------------------|
(++) |0WS(1 CPU cycles)| 0 < HCLK <= 32 | 0 < HCLK <= 25 | 0 < HCLK <= 12.5| 0 < HCLK <= 8 |
(++) |-----------------|-------------------|------------------|------------------|-------------------|
(++) |1WS(2 CPU cycles)| 32 < HCLK <= 64 | 25 < HCLK <= 50 | 12.5 < HCLK <= 25| 0 < HCLK <= 16 |
(++) |-----------------|-------------------|------------------|------------------|-------------------|
(++) |2WS(3 CPU cycles)| 64 < HCLK <= 96 | 50 < HCLK <= 75 | 25 < HCLK <= 37.5| 0 < HCLK <= 24 |
(++) |-----------------|-------------------|------------------|------------------|-------------------|
(++) |3WS(4 CPU cycles)| 96 < HCLK <= 128 | 75 < HCLK <= 100| 37.5 < HCLK <= 50| |
(++) |-----------------|-------------------|------------------|------------------| |
(++) |4WS(5 CPU cycles)| 128 < HCLK <= 160| | | |
(++) +-----------------+-------------------+------------------+------------------+-------------------+
@endinternal
* @{
*/
/**
* @brief This function sets directly SystemCoreClock CMSIS variable.
* @note Variable can be calculated also through SystemCoreClockUpdate function.
* @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro)
* @retval None
*/
void LL_SetSystemCoreClock(uint32_t HCLKFrequency)
{
/* HCLK clock frequency */
SystemCoreClock = HCLKFrequency;
}
/**
* @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 = LL_FLASH_LATENCY_0; /* default value 0WS */
/* Frequency cannot be equal to 0 */
if (HCLK_Frequency == 0U)
{
status = ERROR;
}
else
{
if (LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE1)
{
if (HCLK_Frequency <= UTILS_SCALE1_LATENCY0_FREQ)
{
/* 0 < HCLK <= 32 => 0WS (1 CPU cycles) : Do nothing, keep latency to default LL_FLASH_LATENCY_0 */
}
else if ((HCLK_Frequency <= UTILS_SCALE1_LATENCY1_FREQ))
{
/* 32 < HCLK <=64 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
else if (HCLK_Frequency <= UTILS_SCALE1_LATENCY2_FREQ)
{
/* 64 < HCLK <= 96 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else if (HCLK_Frequency <= UTILS_SCALE1_LATENCY3_FREQ)
{
/* 96 < HCLK <= 128 => 3WS (4 CPU cycles) */
latency = LL_FLASH_LATENCY_3;
}
else if (HCLK_Frequency <= UTILS_SCALE1_LATENCY4_FREQ)
{
/* 128 < HCLK <= 160 => 4WS (5 CPU cycles) */
latency = LL_FLASH_LATENCY_4;
}
else
{
status = ERROR;
}
/* else HCLK_Frequency <= 10MHz default LL_FLASH_LATENCY_0 0WS */
}
else if (LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE2)
{
if (HCLK_Frequency <= UTILS_SCALE2_LATENCY0_FREQ)
{
/* 0 < HCLK <= 25 => 0WS (1 CPU cycles) : Do nothing, keep latency to default LL_FLASH_LATENCY_0 */
}
else if (HCLK_Frequency <= UTILS_SCALE2_LATENCY1_FREQ)
{
/* 25 < HCLK <= 50 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
else if (HCLK_Frequency <= UTILS_SCALE2_LATENCY2_FREQ)
{
/* 50 < HCLK <= 75 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else if (HCLK_Frequency <= UTILS_SCALE2_LATENCY3_FREQ)
{
/* 75 < HCLK <= 100 => 3WS (4 CPU cycles) */
latency = LL_FLASH_LATENCY_3;
}
else
{
status = ERROR;
}
/* else HCLK_Frequency <= 10MHz default LL_FLASH_LATENCY_0 0WS */
}
else if (LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE3)
{
if (HCLK_Frequency <= UTILS_SCALE3_LATENCY0_FREQ)
{
/* 0 < HCLK <= 12.5 => 0WS (1 CPU cycles) : Do nothing, keep latency to default LL_FLASH_LATENCY_0 */
}
else if (HCLK_Frequency <= UTILS_SCALE3_LATENCY1_FREQ)
{
/* 12.5 < HCLK <= 25 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
else if (HCLK_Frequency <= UTILS_SCALE3_LATENCY2_FREQ)
{
/* 25 < HCLK <= 37.5 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else if (HCLK_Frequency <= UTILS_SCALE3_LATENCY3_FREQ)
{
/* 37.5 < HCLK <= 50 => 3WS (4 CPU cycles) */
latency = LL_FLASH_LATENCY_3;
}
else
{
status = ERROR;
}
/* else HCLK_Frequency <= 10MHz default LL_FLASH_LATENCY_0 0WS */
}
else
{
if (HCLK_Frequency <= UTILS_SCALE4_LATENCY0_FREQ)
{
/* 0 < HCLK <= 8 => 0WS (1 CPU cycles) : Do nothing, keep latency to default LL_FLASH_LATENCY_0 */
}
else if (HCLK_Frequency <= UTILS_SCALE4_LATENCY1_FREQ)
{
/* 8 < HCLK <= 16 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
else if (HCLK_Frequency <= UTILS_SCALE4_LATENCY2_FREQ)
{
/* 16 < HCLK <= 24 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else
{
status = ERROR;
}
/* else HCLK_Frequency <= 10MHz default LL_FLASH_LATENCY_0 0WS */
}
}
if (status == SUCCESS)
{
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;
}
/**
* @brief This function configures system clock with MSI as clock source of the PLL
* @note The application needs to ensure that PLL1, PLL2 and/or PLL3 are disabled.
* @note Function is based on the following formula:
* - PLL1 output frequency = (((MSI frequency / PLL1M) * PLL1N) / PLL1R)
* - PLL1M: ensure that the VCO input frequency ranges from 1 to 16 MHz (PLL1VCO_input = MSI frequency / PLL1M)
* - PLL1N: ensure that the VCO output frequency is between 4 and 512 MHz
(PLL1VCO_output = PLL1VCO_input * PLL1N)
* - PLL1R: ensure that max frequency at 160 MHz is reached (PLL1VCO_output / PLL1R)
* @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains
* the configuration information for the PLL1.
* @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_MSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct,
LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct)
{
ErrorStatus status = SUCCESS;
uint32_t pllfreq;
uint32_t msi_range;
/* Check if one of the PLL is enabled */
if (UTILS_PLL_IsBusy() == SUCCESS)
{
/* Get the current MSI range */
if (LL_RCC_MSI_IsEnabledRangeSelect() != 0U)
{
msi_range = LL_RCC_MSIS_GetRange();
switch (msi_range)
{
case LL_RCC_MSISRANGE_15: /* MSI = 100 kHz */
case LL_RCC_MSISRANGE_14: /* MSI = 150 kHz */
case LL_RCC_MSISRANGE_13: /* MSI = 200 kHz */
case LL_RCC_MSISRANGE_12: /* MSI = 400 kHz */
case LL_RCC_MSISRANGE_11: /* MSI = 768 kHz */
case LL_RCC_MSISRANGE_10: /* MSI = 1.024 MHz*/
case LL_RCC_MSISRANGE_9: /* MSI = 1.536 MHz*/
case LL_RCC_MSISRANGE_8: /* MSI = 3.072 MHz*/
case LL_RCC_MSISRANGE_7: /* MSI = 1 MHz */
case LL_RCC_MSISRANGE_6: /* MSI = 1.5 MHz */
case LL_RCC_MSISRANGE_5: /* MSI = 2 MHz */
/* PLLVCO input frequency is less then 4 MHz*/
status = ERROR;
break;
case LL_RCC_MSISRANGE_0: /* MSI = 48 MHz */
case LL_RCC_MSISRANGE_1: /* MSI = 24 MHz */
case LL_RCC_MSISRANGE_2: /* MSI = 16 MHz */
case LL_RCC_MSISRANGE_3: /* MSI = 12 MHz */
case LL_RCC_MSISRANGE_4: /* MSI = 4 MHz */
default:
break;
}
}
else
{
msi_range = LL_RCC_MSIS_GetRangeAfterStandby();
switch (msi_range)
{
case LL_RCC_MSISSRANGE_5: /* MSI = 2 MHz */
case LL_RCC_MSISSRANGE_6: /* MSI = 1.5 MHz */
case LL_RCC_MSISSRANGE_7: /* MSI = 1 MHz */
case LL_RCC_MSISSRANGE_8: /* MSI = 3.072 MHz*/
/* PLLVCO input frequency is less then 4 MHz */
status = ERROR;
break;
case LL_RCC_MSISSRANGE_4: /* MSI = 4 MHz */
default:
break;
}
}
/* Main PLL configuration and activation */
if (status != ERROR)
{
/* Calculate the new PLL output frequency */
pllfreq = UTILS_GetPLLOutputFrequency(__LL_RCC_CALC_MSIS_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(), msi_range),
UTILS_PLLInitStruct);
/* Enable MSI if not enabled */
if (LL_RCC_MSIS_IsReady() != 1U)
{
LL_RCC_MSIS_Enable();
while ((LL_RCC_MSIS_IsReady() != 1U))
{
/* Wait for MSI ready */
}
}
/* Configure PLL1 */
LL_RCC_PLL1_ConfigDomain_SYS(LL_RCC_PLL1SOURCE_MSIS, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN,
UTILS_PLLInitStruct->PLLR);
/* 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 HSI as clock source of the PLL
* @note The application need to ensure that PLL1, PLL2 and/or PLL3 are disabled.
* @note Function is based on the following formula:
* - PLL output frequency = (((HSI frequency / PLLM) * PLLN) / PLLR)
* - PLL1M: ensure that the VCO input frequency ranges from 1 to 16 MHz (PLL1VCO_input = MSI frequency / PLL1M)
* - PLL1N: ensure that the VCO output frequency is between 4 and 512 MHz
(PLL1VCO_output = PLL1VCO_input * PLL1N)
* - PLL1R: ensure that max frequency at 160 MHz is reached (PLL1VCO_output / PLL1R)
* @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;
uint32_t pllfreq;
/* Check if one of the PLL is enabled */
if (UTILS_PLL_IsBusy() == SUCCESS)
{
/* Calculate the new PLL output frequency */
pllfreq = UTILS_GetPLLOutputFrequency(HSI_VALUE, 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_PLL1_ConfigDomain_SYS(LL_RCC_PLL1SOURCE_HSI, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN,
UTILS_PLLInitStruct->PLLR);
/* 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, PLLSAI1 and/or PLLSAI2 are disabled.
* @note Function is based on the following formula:
* - PLL output frequency = (((HSE frequency / PLLM) * PLLN) / PLLR)
* - PLL1M: ensure that the VCO input frequency ranges from 1 to 16 MHz (PLL1VCO_input = MSI frequency / PLL1M)
* - PLL1N: ensure that the VCO output frequency is between 4 and 512 MHz
(PLL1VCO_output = PLL1VCO_input * PLL1N)
* - PLL1R: ensure that max frequency at 160 MHz is reached (PLL1VCO_output / PLL1R)
* @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;
uint32_t pllfreq;
/* Check the parameters */
assert_param(IS_LL_UTILS_HSE_FREQUENCY(HSEFrequency));
assert_param(IS_LL_UTILS_HSE_BYPASS(HSEBypass));
/* Check if one of the PLL is enabled */
if (UTILS_PLL_IsBusy() == 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_PLL1_ConfigDomain_SYS(LL_RCC_PLL1SOURCE_HSE, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN,
UTILS_PLLInitStruct->PLLR);
/* 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;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup UTILS_LL_Private_Functions
* @{
*/
/**
* @brief Function to check that PLL can be modified
* @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, 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_PLLR_VALUE(UTILS_PLLInitStruct->PLLR));
/* Check different PLL parameters according to RM */
/* - PLLM: ensure that the VCO input frequency ranges from 1 to 16 MHz. */
pllfreq = PLL_InputFrequency / (UTILS_PLLInitStruct->PLLM);
assert_param(IS_LL_UTILS_PLLVCO_INPUT(pllfreq));
/* - PLLN: ensure that the VCO output frequency is between 4 and 512 MHz.*/
pllfreq = pllfreq * (UTILS_PLLInitStruct->PLLN);
assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(pllfreq));
/* - PLLR: ensure that max frequency at 160 MHz is reached */
pllfreq = pllfreq / (UTILS_PLLInitStruct->PLLR);
assert_param(IS_LL_UTILS_PLL_FREQUENCY(pllfreq));
return pllfreq;
}
/**
* @brief Function to check that PLL can be modified
* @retval An ErrorStatus enumeration value:
* - SUCCESS: PLL modification can be done
* - ERROR: PLL is busy
*/
static ErrorStatus UTILS_PLL_IsBusy(void)
{
ErrorStatus status = SUCCESS;
/* Check if PLL1 is busy*/
if (LL_RCC_PLL1_IsReady() != 0U)
{
/* PLL configuration cannot be modified */
status = ERROR;
}
/* Check if PLL2 is busy*/
if (LL_RCC_PLL2_IsReady() != 0U)
{
/* PLL2 configuration cannot be modified */
status = ERROR;
}
/* Check if PLL3 is busy*/
if (LL_RCC_PLL3_IsReady() != 0U)
{
/* PLL3 configuration cannot be modified */
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 hclk_frequency;
assert_param(IS_LL_UTILS_SYSCLK_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_APB3_DIV(UTILS_ClkInitStruct->APB3CLKDivider));
/* Calculate HCLK frequency */
hclk_frequency = __LL_RCC_CALC_HCLK_FREQ(SYSCLK_Frequency, UTILS_ClkInitStruct->AHBCLKDivider);
/* Increasing the number of wait states because of higher CPU frequency */
if (SystemCoreClock < hclk_frequency)
{
/* Set FLASH latency to highest latency */
status = LL_SetFlashLatency(hclk_frequency);
}
/* Update system clock configuration */
if (status == SUCCESS)
{
/* Enable PLL1 */
LL_RCC_PLL1_Enable();
LL_RCC_PLL1_EnableDomain_SYS();
while (LL_RCC_PLL1_IsReady() != 1U)
{
/* Wait for PLL ready */
}
/* Sysclk activation on the main PLL */
LL_RCC_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider);
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 APB1, APB2 & APB3 prescaler*/
LL_RCC_SetAPB1Prescaler(UTILS_ClkInitStruct->APB1CLKDivider);
LL_RCC_SetAPB2Prescaler(UTILS_ClkInitStruct->APB2CLKDivider);
LL_RCC_SetAPB3Prescaler(UTILS_ClkInitStruct->APB3CLKDivider);
}
/* Decreasing the number of wait states because of lower CPU frequency */
if (SystemCoreClock > hclk_frequency)
{
/* Set FLASH latency to lowest latency */
status = LL_SetFlashLatency(hclk_frequency);
}
/* Update SystemCoreClock variable */
if (status == SUCCESS)
{
LL_SetSystemCoreClock(hclk_frequency);
}
return status;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/Src/stm32u5xx_ll_utils.c
|
C
|
apache-2.0
| 32,517
|
@charset "UTF-8";
/*
Flavor name: Custom (mini-custom)
Generated online - https://minicss.org/flavors
mini.css version: v3.0.1
*/
/*
Browsers resets and base typography.
*/
/* Core module CSS variable definitions */
:root {
--fore-color: #03234b;
--secondary-fore-color: #03234b;
--back-color: #ffffff;
--secondary-back-color: #ffffff;
--blockquote-color: #e6007e;
--pre-color: #e6007e;
--border-color: #3cb4e6;
--secondary-border-color: #3cb4e6;
--heading-ratio: 1.2;
--universal-margin: 0.5rem;
--universal-padding: 0.25rem;
--universal-border-radius: 0.075rem;
--background-margin: 1.5%;
--a-link-color: #3cb4e6;
--a-visited-color: #8c0078; }
html {
font-size: 13.5px; }
a, b, del, em, i, ins, q, span, strong, u {
font-size: 1em; }
html, * {
font-family: -apple-system, BlinkMacSystemFont, Helvetica, arial, sans-serif;
line-height: 1.25;
-webkit-text-size-adjust: 100%; }
* {
font-size: 1rem; }
body {
margin: 0;
color: var(--fore-color);
@background: var(--back-color);
background: var(--back-color) linear-gradient(#ffd200, #ffd200) repeat-y left top;
background-size: var(--background-margin);
}
details {
display: block; }
summary {
display: list-item; }
abbr[title] {
border-bottom: none;
text-decoration: underline dotted; }
input {
overflow: visible; }
img {
max-width: 100%;
height: auto; }
h1, h2, h3, h4, h5, h6 {
line-height: 1.25;
margin: calc(1.5 * var(--universal-margin)) var(--universal-margin);
font-weight: 400; }
h1 small, h2 small, h3 small, h4 small, h5 small, h6 small {
color: var(--secondary-fore-color);
display: block;
margin-top: -0.25rem; }
h1 {
font-size: calc(1rem * var(--heading-ratio) * var(--heading-ratio) * var(--heading-ratio)); }
h2 {
font-size: calc(1rem * var(--heading-ratio) * var(--heading-ratio) );
border-style: none none solid none ;
border-width: thin;
border-color: var(--border-color); }
h3 {
font-size: calc(1rem * var(--heading-ratio) ); }
h4 {
font-size: calc(1rem * var(--heading-ratio)); }
h5 {
font-size: 1rem; }
h6 {
font-size: calc(1rem / var(--heading-ratio)); }
p {
margin: var(--universal-margin); }
ol, ul {
margin: var(--universal-margin);
padding-left: calc(3 * var(--universal-margin)); }
b, strong {
font-weight: 700; }
hr {
box-sizing: content-box;
border: 0;
line-height: 1.25em;
margin: var(--universal-margin);
height: 0.0714285714rem;
background: linear-gradient(to right, transparent, var(--border-color) 20%, var(--border-color) 80%, transparent); }
blockquote {
display: block;
position: relative;
font-style: italic;
color: var(--secondary-fore-color);
margin: var(--universal-margin);
padding: calc(3 * var(--universal-padding));
border: 0.0714285714rem solid var(--secondary-border-color);
border-left: 0.3rem solid var(--blockquote-color);
border-radius: 0 var(--universal-border-radius) var(--universal-border-radius) 0; }
blockquote:before {
position: absolute;
top: calc(0rem - var(--universal-padding));
left: 0;
font-family: sans-serif;
font-size: 2rem;
font-weight: 800;
content: "\201c";
color: var(--blockquote-color); }
blockquote[cite]:after {
font-style: normal;
font-size: 0.75em;
font-weight: 700;
content: "\a— " attr(cite);
white-space: pre; }
code, kbd, pre, samp {
font-family: Menlo, Consolas, monospace;
font-size: 0.85em; }
code {
background: var(--secondary-back-color);
border-radius: var(--universal-border-radius);
padding: calc(var(--universal-padding) / 4) calc(var(--universal-padding) / 2); }
kbd {
background: var(--fore-color);
color: var(--back-color);
border-radius: var(--universal-border-radius);
padding: calc(var(--universal-padding) / 4) calc(var(--universal-padding) / 2); }
pre {
overflow: auto;
background: var(--secondary-back-color);
padding: calc(1.5 * var(--universal-padding));
margin: var(--universal-margin);
border: 0.0714285714rem solid var(--secondary-border-color);
border-left: 0.2857142857rem solid var(--pre-color);
border-radius: 0 var(--universal-border-radius) var(--universal-border-radius) 0; }
sup, sub, code, kbd {
line-height: 0;
position: relative;
vertical-align: baseline; }
small, sup, sub, figcaption {
font-size: 0.75em; }
sup {
top: -0.5em; }
sub {
bottom: -0.25em; }
figure {
margin: var(--universal-margin); }
figcaption {
color: var(--secondary-fore-color); }
a {
text-decoration: none; }
a:link {
color: var(--a-link-color); }
a:visited {
color: var(--a-visited-color); }
a:hover, a:focus {
text-decoration: underline; }
/*
Definitions for the grid system, cards and containers.
*/
.container {
margin: 0 auto;
padding: 0 calc(1.5 * var(--universal-padding)); }
.row {
box-sizing: border-box;
display: flex;
flex: 0 1 auto;
flex-flow: row wrap;
margin: 0 0 0 var(--background-margin); }
.col-sm,
[class^='col-sm-'],
[class^='col-sm-offset-'],
.row[class*='cols-sm-'] > * {
box-sizing: border-box;
flex: 0 0 auto;
padding: 0 calc(var(--universal-padding) / 2); }
.col-sm,
.row.cols-sm > * {
max-width: 100%;
flex-grow: 1;
flex-basis: 0; }
.col-sm-1,
.row.cols-sm-1 > * {
max-width: 8.3333333333%;
flex-basis: 8.3333333333%; }
.col-sm-offset-0 {
margin-left: 0; }
.col-sm-2,
.row.cols-sm-2 > * {
max-width: 16.6666666667%;
flex-basis: 16.6666666667%; }
.col-sm-offset-1 {
margin-left: 8.3333333333%; }
.col-sm-3,
.row.cols-sm-3 > * {
max-width: 25%;
flex-basis: 25%; }
.col-sm-offset-2 {
margin-left: 16.6666666667%; }
.col-sm-4,
.row.cols-sm-4 > * {
max-width: 33.3333333333%;
flex-basis: 33.3333333333%; }
.col-sm-offset-3 {
margin-left: 25%; }
.col-sm-5,
.row.cols-sm-5 > * {
max-width: 41.6666666667%;
flex-basis: 41.6666666667%; }
.col-sm-offset-4 {
margin-left: 33.3333333333%; }
.col-sm-6,
.row.cols-sm-6 > * {
max-width: 50%;
flex-basis: 50%; }
.col-sm-offset-5 {
margin-left: 41.6666666667%; }
.col-sm-7,
.row.cols-sm-7 > * {
max-width: 58.3333333333%;
flex-basis: 58.3333333333%; }
.col-sm-offset-6 {
margin-left: 50%; }
.col-sm-8,
.row.cols-sm-8 > * {
max-width: 66.6666666667%;
flex-basis: 66.6666666667%; }
.col-sm-offset-7 {
margin-left: 58.3333333333%; }
.col-sm-9,
.row.cols-sm-9 > * {
max-width: 75%;
flex-basis: 75%; }
.col-sm-offset-8 {
margin-left: 66.6666666667%; }
.col-sm-10,
.row.cols-sm-10 > * {
max-width: 83.3333333333%;
flex-basis: 83.3333333333%; }
.col-sm-offset-9 {
margin-left: 75%; }
.col-sm-11,
.row.cols-sm-11 > * {
max-width: 91.6666666667%;
flex-basis: 91.6666666667%; }
.col-sm-offset-10 {
margin-left: 83.3333333333%; }
.col-sm-12,
.row.cols-sm-12 > * {
max-width: 100%;
flex-basis: 100%; }
.col-sm-offset-11 {
margin-left: 91.6666666667%; }
.col-sm-normal {
order: initial; }
.col-sm-first {
order: -999; }
.col-sm-last {
order: 999; }
@media screen and (min-width: 500px) {
.col-md,
[class^='col-md-'],
[class^='col-md-offset-'],
.row[class*='cols-md-'] > * {
box-sizing: border-box;
flex: 0 0 auto;
padding: 0 calc(var(--universal-padding) / 2); }
.col-md,
.row.cols-md > * {
max-width: 100%;
flex-grow: 1;
flex-basis: 0; }
.col-md-1,
.row.cols-md-1 > * {
max-width: 8.3333333333%;
flex-basis: 8.3333333333%; }
.col-md-offset-0 {
margin-left: 0; }
.col-md-2,
.row.cols-md-2 > * {
max-width: 16.6666666667%;
flex-basis: 16.6666666667%; }
.col-md-offset-1 {
margin-left: 8.3333333333%; }
.col-md-3,
.row.cols-md-3 > * {
max-width: 25%;
flex-basis: 25%; }
.col-md-offset-2 {
margin-left: 16.6666666667%; }
.col-md-4,
.row.cols-md-4 > * {
max-width: 33.3333333333%;
flex-basis: 33.3333333333%; }
.col-md-offset-3 {
margin-left: 25%; }
.col-md-5,
.row.cols-md-5 > * {
max-width: 41.6666666667%;
flex-basis: 41.6666666667%; }
.col-md-offset-4 {
margin-left: 33.3333333333%; }
.col-md-6,
.row.cols-md-6 > * {
max-width: 50%;
flex-basis: 50%; }
.col-md-offset-5 {
margin-left: 41.6666666667%; }
.col-md-7,
.row.cols-md-7 > * {
max-width: 58.3333333333%;
flex-basis: 58.3333333333%; }
.col-md-offset-6 {
margin-left: 50%; }
.col-md-8,
.row.cols-md-8 > * {
max-width: 66.6666666667%;
flex-basis: 66.6666666667%; }
.col-md-offset-7 {
margin-left: 58.3333333333%; }
.col-md-9,
.row.cols-md-9 > * {
max-width: 75%;
flex-basis: 75%; }
.col-md-offset-8 {
margin-left: 66.6666666667%; }
.col-md-10,
.row.cols-md-10 > * {
max-width: 83.3333333333%;
flex-basis: 83.3333333333%; }
.col-md-offset-9 {
margin-left: 75%; }
.col-md-11,
.row.cols-md-11 > * {
max-width: 91.6666666667%;
flex-basis: 91.6666666667%; }
.col-md-offset-10 {
margin-left: 83.3333333333%; }
.col-md-12,
.row.cols-md-12 > * {
max-width: 100%;
flex-basis: 100%; }
.col-md-offset-11 {
margin-left: 91.6666666667%; }
.col-md-normal {
order: initial; }
.col-md-first {
order: -999; }
.col-md-last {
order: 999; } }
@media screen and (min-width: 1280px) {
.col-lg,
[class^='col-lg-'],
[class^='col-lg-offset-'],
.row[class*='cols-lg-'] > * {
box-sizing: border-box;
flex: 0 0 auto;
padding: 0 calc(var(--universal-padding) / 2); }
.col-lg,
.row.cols-lg > * {
max-width: 100%;
flex-grow: 1;
flex-basis: 0; }
.col-lg-1,
.row.cols-lg-1 > * {
max-width: 8.3333333333%;
flex-basis: 8.3333333333%; }
.col-lg-offset-0 {
margin-left: 0; }
.col-lg-2,
.row.cols-lg-2 > * {
max-width: 16.6666666667%;
flex-basis: 16.6666666667%; }
.col-lg-offset-1 {
margin-left: 8.3333333333%; }
.col-lg-3,
.row.cols-lg-3 > * {
max-width: 25%;
flex-basis: 25%; }
.col-lg-offset-2 {
margin-left: 16.6666666667%; }
.col-lg-4,
.row.cols-lg-4 > * {
max-width: 33.3333333333%;
flex-basis: 33.3333333333%; }
.col-lg-offset-3 {
margin-left: 25%; }
.col-lg-5,
.row.cols-lg-5 > * {
max-width: 41.6666666667%;
flex-basis: 41.6666666667%; }
.col-lg-offset-4 {
margin-left: 33.3333333333%; }
.col-lg-6,
.row.cols-lg-6 > * {
max-width: 50%;
flex-basis: 50%; }
.col-lg-offset-5 {
margin-left: 41.6666666667%; }
.col-lg-7,
.row.cols-lg-7 > * {
max-width: 58.3333333333%;
flex-basis: 58.3333333333%; }
.col-lg-offset-6 {
margin-left: 50%; }
.col-lg-8,
.row.cols-lg-8 > * {
max-width: 66.6666666667%;
flex-basis: 66.6666666667%; }
.col-lg-offset-7 {
margin-left: 58.3333333333%; }
.col-lg-9,
.row.cols-lg-9 > * {
max-width: 75%;
flex-basis: 75%; }
.col-lg-offset-8 {
margin-left: 66.6666666667%; }
.col-lg-10,
.row.cols-lg-10 > * {
max-width: 83.3333333333%;
flex-basis: 83.3333333333%; }
.col-lg-offset-9 {
margin-left: 75%; }
.col-lg-11,
.row.cols-lg-11 > * {
max-width: 91.6666666667%;
flex-basis: 91.6666666667%; }
.col-lg-offset-10 {
margin-left: 83.3333333333%; }
.col-lg-12,
.row.cols-lg-12 > * {
max-width: 100%;
flex-basis: 100%; }
.col-lg-offset-11 {
margin-left: 91.6666666667%; }
.col-lg-normal {
order: initial; }
.col-lg-first {
order: -999; }
.col-lg-last {
order: 999; } }
/* Card component CSS variable definitions */
:root {
--card-back-color: #3cb4e6;
--card-fore-color: #03234b;
--card-border-color: #03234b; }
.card {
display: flex;
flex-direction: column;
justify-content: space-between;
align-self: center;
position: relative;
width: 100%;
background: var(--card-back-color);
color: var(--card-fore-color);
border: 0.0714285714rem solid var(--card-border-color);
border-radius: var(--universal-border-radius);
margin: var(--universal-margin);
overflow: hidden; }
@media screen and (min-width: 320px) {
.card {
max-width: 320px; } }
.card > .sectione {
background: var(--card-back-color);
color: var(--card-fore-color);
box-sizing: border-box;
margin: 0;
border: 0;
border-radius: 0;
border-bottom: 0.0714285714rem solid var(--card-border-color);
padding: var(--universal-padding);
width: 100%; }
.card > .sectione.media {
height: 200px;
padding: 0;
-o-object-fit: cover;
object-fit: cover; }
.card > .sectione:last-child {
border-bottom: 0; }
/*
Custom elements for card elements.
*/
@media screen and (min-width: 240px) {
.card.small {
max-width: 240px; } }
@media screen and (min-width: 480px) {
.card.large {
max-width: 480px; } }
.card.fluid {
max-width: 100%;
width: auto; }
.card.warning {
--card-back-color: #e5b8b7;
--card-fore-color: #3b234b;
--card-border-color: #8c0078; }
.card.error {
--card-back-color: #464650;
--card-fore-color: #ffffff;
--card-border-color: #8c0078; }
.card > .sectione.dark {
--card-back-color: #3b234b;
--card-fore-color: #ffffff; }
.card > .sectione.double-padded {
padding: calc(1.5 * var(--universal-padding)); }
/*
Definitions for forms and input elements.
*/
/* Input_control module CSS variable definitions */
:root {
--form-back-color: #ffe97f;
--form-fore-color: #03234b;
--form-border-color: #3cb4e6;
--input-back-color: #ffffff;
--input-fore-color: #03234b;
--input-border-color: #3cb4e6;
--input-focus-color: #0288d1;
--input-invalid-color: #d32f2f;
--button-back-color: #e2e2e2;
--button-hover-back-color: #dcdcdc;
--button-fore-color: #212121;
--button-border-color: transparent;
--button-hover-border-color: transparent;
--button-group-border-color: rgba(124, 124, 124, 0.54); }
form {
background: var(--form-back-color);
color: var(--form-fore-color);
border: 0.0714285714rem solid var(--form-border-color);
border-radius: var(--universal-border-radius);
margin: var(--universal-margin);
padding: calc(2 * var(--universal-padding)) var(--universal-padding); }
fieldset {
border: 0.0714285714rem solid var(--form-border-color);
border-radius: var(--universal-border-radius);
margin: calc(var(--universal-margin) / 4);
padding: var(--universal-padding); }
legend {
box-sizing: border-box;
display: table;
max-width: 100%;
white-space: normal;
font-weight: 500;
padding: calc(var(--universal-padding) / 2); }
label {
padding: calc(var(--universal-padding) / 2) var(--universal-padding); }
.input-group {
display: inline-block; }
.input-group.fluid {
display: flex;
align-items: center;
justify-content: center; }
.input-group.fluid > input {
max-width: 100%;
flex-grow: 1;
flex-basis: 0px; }
@media screen and (max-width: 499px) {
.input-group.fluid {
align-items: stretch;
flex-direction: column; } }
.input-group.vertical {
display: flex;
align-items: stretch;
flex-direction: column; }
.input-group.vertical > input {
max-width: 100%;
flex-grow: 1;
flex-basis: 0px; }
[type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button {
height: auto; }
[type="search"] {
-webkit-appearance: textfield;
outline-offset: -2px; }
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none; }
input:not([type]), [type="text"], [type="email"], [type="number"], [type="search"],
[type="password"], [type="url"], [type="tel"], [type="checkbox"], [type="radio"], textarea, select {
box-sizing: border-box;
background: var(--input-back-color);
color: var(--input-fore-color);
border: 0.0714285714rem solid var(--input-border-color);
border-radius: var(--universal-border-radius);
margin: calc(var(--universal-margin) / 2);
padding: var(--universal-padding) calc(1.5 * var(--universal-padding)); }
input:not([type="button"]):not([type="submit"]):not([type="reset"]):hover, input:not([type="button"]):not([type="submit"]):not([type="reset"]):focus, textarea:hover, textarea:focus, select:hover, select:focus {
border-color: var(--input-focus-color);
box-shadow: none; }
input:not([type="button"]):not([type="submit"]):not([type="reset"]):invalid, input:not([type="button"]):not([type="submit"]):not([type="reset"]):focus:invalid, textarea:invalid, textarea:focus:invalid, select:invalid, select:focus:invalid {
border-color: var(--input-invalid-color);
box-shadow: none; }
input:not([type="button"]):not([type="submit"]):not([type="reset"])[readonly], textarea[readonly], select[readonly] {
background: var(--secondary-back-color); }
select {
max-width: 100%; }
option {
overflow: hidden;
text-overflow: ellipsis; }
[type="checkbox"], [type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
position: relative;
height: calc(1rem + var(--universal-padding) / 2);
width: calc(1rem + var(--universal-padding) / 2);
vertical-align: text-bottom;
padding: 0;
flex-basis: calc(1rem + var(--universal-padding) / 2) !important;
flex-grow: 0 !important; }
[type="checkbox"]:checked:before, [type="radio"]:checked:before {
position: absolute; }
[type="checkbox"]:checked:before {
content: '\2713';
font-family: sans-serif;
font-size: calc(1rem + var(--universal-padding) / 2);
top: calc(0rem - var(--universal-padding));
left: calc(var(--universal-padding) / 4); }
[type="radio"] {
border-radius: 100%; }
[type="radio"]:checked:before {
border-radius: 100%;
content: '';
top: calc(0.0714285714rem + var(--universal-padding) / 2);
left: calc(0.0714285714rem + var(--universal-padding) / 2);
background: var(--input-fore-color);
width: 0.5rem;
height: 0.5rem; }
:placeholder-shown {
color: var(--input-fore-color); }
::-ms-placeholder {
color: var(--input-fore-color);
opacity: 0.54; }
button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0; }
button, html [type="button"], [type="reset"], [type="submit"] {
-webkit-appearance: button; }
button {
overflow: visible;
text-transform: none; }
button, [type="button"], [type="submit"], [type="reset"],
a.button, label.button, .button,
a[role="button"], label[role="button"], [role="button"] {
display: inline-block;
background: var(--button-back-color);
color: var(--button-fore-color);
border: 0.0714285714rem solid var(--button-border-color);
border-radius: var(--universal-border-radius);
padding: var(--universal-padding) calc(1.5 * var(--universal-padding));
margin: var(--universal-margin);
text-decoration: none;
cursor: pointer;
transition: background 0.3s; }
button:hover, button:focus, [type="button"]:hover, [type="button"]:focus, [type="submit"]:hover, [type="submit"]:focus, [type="reset"]:hover, [type="reset"]:focus,
a.button:hover,
a.button:focus, label.button:hover, label.button:focus, .button:hover, .button:focus,
a[role="button"]:hover,
a[role="button"]:focus, label[role="button"]:hover, label[role="button"]:focus, [role="button"]:hover, [role="button"]:focus {
background: var(--button-hover-back-color);
border-color: var(--button-hover-border-color); }
input:disabled, input[disabled], textarea:disabled, textarea[disabled], select:disabled, select[disabled], button:disabled, button[disabled], .button:disabled, .button[disabled], [role="button"]:disabled, [role="button"][disabled] {
cursor: not-allowed;
opacity: 0.75; }
.button-group {
display: flex;
border: 0.0714285714rem solid var(--button-group-border-color);
border-radius: var(--universal-border-radius);
margin: var(--universal-margin); }
.button-group > button, .button-group [type="button"], .button-group > [type="submit"], .button-group > [type="reset"], .button-group > .button, .button-group > [role="button"] {
margin: 0;
max-width: 100%;
flex: 1 1 auto;
text-align: center;
border: 0;
border-radius: 0;
box-shadow: none; }
.button-group > :not(:first-child) {
border-left: 0.0714285714rem solid var(--button-group-border-color); }
@media screen and (max-width: 499px) {
.button-group {
flex-direction: column; }
.button-group > :not(:first-child) {
border: 0;
border-top: 0.0714285714rem solid var(--button-group-border-color); } }
/*
Custom elements for forms and input elements.
*/
button.primary, [type="button"].primary, [type="submit"].primary, [type="reset"].primary, .button.primary, [role="button"].primary {
--button-back-color: #1976d2;
--button-fore-color: #f8f8f8; }
button.primary:hover, button.primary:focus, [type="button"].primary:hover, [type="button"].primary:focus, [type="submit"].primary:hover, [type="submit"].primary:focus, [type="reset"].primary:hover, [type="reset"].primary:focus, .button.primary:hover, .button.primary:focus, [role="button"].primary:hover, [role="button"].primary:focus {
--button-hover-back-color: #1565c0; }
button.secondary, [type="button"].secondary, [type="submit"].secondary, [type="reset"].secondary, .button.secondary, [role="button"].secondary {
--button-back-color: #d32f2f;
--button-fore-color: #f8f8f8; }
button.secondary:hover, button.secondary:focus, [type="button"].secondary:hover, [type="button"].secondary:focus, [type="submit"].secondary:hover, [type="submit"].secondary:focus, [type="reset"].secondary:hover, [type="reset"].secondary:focus, .button.secondary:hover, .button.secondary:focus, [role="button"].secondary:hover, [role="button"].secondary:focus {
--button-hover-back-color: #c62828; }
button.tertiary, [type="button"].tertiary, [type="submit"].tertiary, [type="reset"].tertiary, .button.tertiary, [role="button"].tertiary {
--button-back-color: #308732;
--button-fore-color: #f8f8f8; }
button.tertiary:hover, button.tertiary:focus, [type="button"].tertiary:hover, [type="button"].tertiary:focus, [type="submit"].tertiary:hover, [type="submit"].tertiary:focus, [type="reset"].tertiary:hover, [type="reset"].tertiary:focus, .button.tertiary:hover, .button.tertiary:focus, [role="button"].tertiary:hover, [role="button"].tertiary:focus {
--button-hover-back-color: #277529; }
button.inverse, [type="button"].inverse, [type="submit"].inverse, [type="reset"].inverse, .button.inverse, [role="button"].inverse {
--button-back-color: #212121;
--button-fore-color: #f8f8f8; }
button.inverse:hover, button.inverse:focus, [type="button"].inverse:hover, [type="button"].inverse:focus, [type="submit"].inverse:hover, [type="submit"].inverse:focus, [type="reset"].inverse:hover, [type="reset"].inverse:focus, .button.inverse:hover, .button.inverse:focus, [role="button"].inverse:hover, [role="button"].inverse:focus {
--button-hover-back-color: #111; }
button.small, [type="button"].small, [type="submit"].small, [type="reset"].small, .button.small, [role="button"].small {
padding: calc(0.5 * var(--universal-padding)) calc(0.75 * var(--universal-padding));
margin: var(--universal-margin); }
button.large, [type="button"].large, [type="submit"].large, [type="reset"].large, .button.large, [role="button"].large {
padding: calc(1.5 * var(--universal-padding)) calc(2 * var(--universal-padding));
margin: var(--universal-margin); }
/*
Definitions for navigation elements.
*/
/* Navigation module CSS variable definitions */
:root {
--header-back-color: #03234b;
--header-hover-back-color: #ffd200;
--header-fore-color: #ffffff;
--header-border-color: #3cb4e6;
--nav-back-color: #ffffff;
--nav-hover-back-color: #ffe97f;
--nav-fore-color: #e6007e;
--nav-border-color: #3cb4e6;
--nav-link-color: #3cb4e6;
--footer-fore-color: #ffffff;
--footer-back-color: #03234b;
--footer-border-color: #3cb4e6;
--footer-link-color: #3cb4e6;
--drawer-back-color: #ffffff;
--drawer-hover-back-color: #ffe97f;
--drawer-border-color: #3cb4e6;
--drawer-close-color: #e6007e; }
header {
height: 2.75rem;
background: var(--header-back-color);
color: var(--header-fore-color);
border-bottom: 0.0714285714rem solid var(--header-border-color);
padding: calc(var(--universal-padding) / 4) 0;
white-space: nowrap;
overflow-x: auto;
overflow-y: hidden; }
header.row {
box-sizing: content-box; }
header .logo {
color: var(--header-fore-color);
font-size: 1.75rem;
padding: var(--universal-padding) calc(2 * var(--universal-padding));
text-decoration: none; }
header button, header [type="button"], header .button, header [role="button"] {
box-sizing: border-box;
position: relative;
top: calc(0rem - var(--universal-padding) / 4);
height: calc(3.1875rem + var(--universal-padding) / 2);
background: var(--header-back-color);
line-height: calc(3.1875rem - var(--universal-padding) * 1.5);
text-align: center;
color: var(--header-fore-color);
border: 0;
border-radius: 0;
margin: 0;
text-transform: uppercase; }
header button:hover, header button:focus, header [type="button"]:hover, header [type="button"]:focus, header .button:hover, header .button:focus, header [role="button"]:hover, header [role="button"]:focus {
background: var(--header-hover-back-color); }
nav {
background: var(--nav-back-color);
color: var(--nav-fore-color);
border: 0.0714285714rem solid var(--nav-border-color);
border-radius: var(--universal-border-radius);
margin: var(--universal-margin); }
nav * {
padding: var(--universal-padding) calc(1.5 * var(--universal-padding)); }
nav a, nav a:visited {
display: block;
color: var(--nav-link-color);
border-radius: var(--universal-border-radius);
transition: background 0.3s; }
nav a:hover, nav a:focus, nav a:visited:hover, nav a:visited:focus {
text-decoration: none;
background: var(--nav-hover-back-color); }
nav .sublink-1 {
position: relative;
margin-left: calc(2 * var(--universal-padding)); }
nav .sublink-1:before {
position: absolute;
left: calc(var(--universal-padding) - 1 * var(--universal-padding));
top: -0.0714285714rem;
content: '';
height: 100%;
border: 0.0714285714rem solid var(--nav-border-color);
border-left: 0; }
nav .sublink-2 {
position: relative;
margin-left: calc(4 * var(--universal-padding)); }
nav .sublink-2:before {
position: absolute;
left: calc(var(--universal-padding) - 3 * var(--universal-padding));
top: -0.0714285714rem;
content: '';
height: 100%;
border: 0.0714285714rem solid var(--nav-border-color);
border-left: 0; }
footer {
background: var(--footer-back-color);
color: var(--footer-fore-color);
border-top: 0.0714285714rem solid var(--footer-border-color);
padding: calc(2 * var(--universal-padding)) var(--universal-padding);
font-size: 0.875rem; }
footer a, footer a:visited {
color: var(--footer-link-color); }
header.sticky {
position: -webkit-sticky;
position: sticky;
z-index: 1101;
top: 0; }
footer.sticky {
position: -webkit-sticky;
position: sticky;
z-index: 1101;
bottom: 0; }
.drawer-toggle:before {
display: inline-block;
position: relative;
vertical-align: bottom;
content: '\00a0\2261\00a0';
font-family: sans-serif;
font-size: 1.5em; }
@media screen and (min-width: 500px) {
.drawer-toggle:not(.persistent) {
display: none; } }
[type="checkbox"].drawer {
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%); }
[type="checkbox"].drawer + * {
display: block;
box-sizing: border-box;
position: fixed;
top: 0;
width: 320px;
height: 100vh;
overflow-y: auto;
background: var(--drawer-back-color);
border: 0.0714285714rem solid var(--drawer-border-color);
border-radius: 0;
margin: 0;
z-index: 1110;
right: -320px;
transition: right 0.3s; }
[type="checkbox"].drawer + * .drawer-close {
position: absolute;
top: var(--universal-margin);
right: var(--universal-margin);
z-index: 1111;
width: 2rem;
height: 2rem;
border-radius: var(--universal-border-radius);
padding: var(--universal-padding);
margin: 0;
cursor: pointer;
transition: background 0.3s; }
[type="checkbox"].drawer + * .drawer-close:before {
display: block;
content: '\00D7';
color: var(--drawer-close-color);
position: relative;
font-family: sans-serif;
font-size: 2rem;
line-height: 1;
text-align: center; }
[type="checkbox"].drawer + * .drawer-close:hover, [type="checkbox"].drawer + * .drawer-close:focus {
background: var(--drawer-hover-back-color); }
@media screen and (max-width: 320px) {
[type="checkbox"].drawer + * {
width: 100%; } }
[type="checkbox"].drawer:checked + * {
right: 0; }
@media screen and (min-width: 500px) {
[type="checkbox"].drawer:not(.persistent) + * {
position: static;
height: 100%;
z-index: 1100; }
[type="checkbox"].drawer:not(.persistent) + * .drawer-close {
display: none; } }
/*
Definitions for the responsive table component.
*/
/* Table module CSS variable definitions. */
:root {
--table-border-color: #03234b;
--table-border-separator-color: #03234b;
--table-head-back-color: #03234b;
--table-head-fore-color: #ffffff;
--table-body-back-color: #ffffff;
--table-body-fore-color: #03234b;
--table-body-alt-back-color: #f4f4f4; }
table {
border-collapse: separate;
border-spacing: 0;
margin: 0;
display: flex;
flex: 0 1 auto;
flex-flow: row wrap;
padding: var(--universal-padding);
padding-top: 0; }
table caption {
font-size: 1rem;
margin: calc(2 * var(--universal-margin)) 0;
max-width: 100%;
flex: 0 0 100%; }
table thead, table tbody {
display: flex;
flex-flow: row wrap;
border: 0.0714285714rem solid var(--table-border-color); }
table thead {
z-index: 999;
border-radius: var(--universal-border-radius) var(--universal-border-radius) 0 0;
border-bottom: 0.0714285714rem solid var(--table-border-separator-color); }
table tbody {
border-top: 0;
margin-top: calc(0 - var(--universal-margin));
border-radius: 0 0 var(--universal-border-radius) var(--universal-border-radius); }
table tr {
display: flex;
padding: 0; }
table th, table td {
padding: calc(0.5 * var(--universal-padding));
font-size: 0.9rem; }
table th {
text-align: left;
background: var(--table-head-back-color);
color: var(--table-head-fore-color); }
table td {
background: var(--table-body-back-color);
color: var(--table-body-fore-color);
border-top: 0.0714285714rem solid var(--table-border-color); }
table:not(.horizontal) {
overflow: auto;
max-height: 100%; }
table:not(.horizontal) thead, table:not(.horizontal) tbody {
max-width: 100%;
flex: 0 0 100%; }
table:not(.horizontal) tr {
flex-flow: row wrap;
flex: 0 0 100%; }
table:not(.horizontal) th, table:not(.horizontal) td {
flex: 1 0 0%;
overflow: hidden;
text-overflow: ellipsis; }
table:not(.horizontal) thead {
position: sticky;
top: 0; }
table:not(.horizontal) tbody tr:first-child td {
border-top: 0; }
table.horizontal {
border: 0; }
table.horizontal thead, table.horizontal tbody {
border: 0;
flex: .2 0 0;
flex-flow: row nowrap; }
table.horizontal tbody {
overflow: auto;
justify-content: space-between;
flex: .8 0 0;
margin-left: 0;
padding-bottom: calc(var(--universal-padding) / 4); }
table.horizontal tr {
flex-direction: column;
flex: 1 0 auto; }
table.horizontal th, table.horizontal td {
width: auto;
border: 0;
border-bottom: 0.0714285714rem solid var(--table-border-color); }
table.horizontal th:not(:first-child), table.horizontal td:not(:first-child) {
border-top: 0; }
table.horizontal th {
text-align: right;
border-left: 0.0714285714rem solid var(--table-border-color);
border-right: 0.0714285714rem solid var(--table-border-separator-color); }
table.horizontal thead tr:first-child {
padding-left: 0; }
table.horizontal th:first-child, table.horizontal td:first-child {
border-top: 0.0714285714rem solid var(--table-border-color); }
table.horizontal tbody tr:last-child td {
border-right: 0.0714285714rem solid var(--table-border-color); }
table.horizontal tbody tr:last-child td:first-child {
border-top-right-radius: 0.25rem; }
table.horizontal tbody tr:last-child td:last-child {
border-bottom-right-radius: 0.25rem; }
table.horizontal thead tr:first-child th:first-child {
border-top-left-radius: 0.25rem; }
table.horizontal thead tr:first-child th:last-child {
border-bottom-left-radius: 0.25rem; }
@media screen and (max-width: 499px) {
table, table.horizontal {
border-collapse: collapse;
border: 0;
width: 100%;
display: table; }
table thead, table th, table.horizontal thead, table.horizontal th {
border: 0;
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%); }
table tbody, table.horizontal tbody {
border: 0;
display: table-row-group; }
table tr, table.horizontal tr {
display: block;
border: 0.0714285714rem solid var(--table-border-color);
border-radius: var(--universal-border-radius);
background: #ffffff;
padding: var(--universal-padding);
margin: var(--universal-margin);
margin-bottom: calc(1 * var(--universal-margin)); }
table th, table td, table.horizontal th, table.horizontal td {
width: auto; }
table td, table.horizontal td {
display: block;
border: 0;
text-align: right; }
table td:before, table.horizontal td:before {
content: attr(data-label);
float: left;
font-weight: 600; }
table th:first-child, table td:first-child, table.horizontal th:first-child, table.horizontal td:first-child {
border-top: 0; }
table tbody tr:last-child td, table.horizontal tbody tr:last-child td {
border-right: 0; } }
table tr:nth-of-type(2n) > td {
background: var(--table-body-alt-back-color); }
@media screen and (max-width: 500px) {
table tr:nth-of-type(2n) {
background: var(--table-body-alt-back-color); } }
:root {
--table-body-hover-back-color: #90caf9; }
table.hoverable tr:hover, table.hoverable tr:hover > td, table.hoverable tr:focus, table.hoverable tr:focus > td {
background: var(--table-body-hover-back-color); }
@media screen and (max-width: 500px) {
table.hoverable tr:hover, table.hoverable tr:hover > td, table.hoverable tr:focus, table.hoverable tr:focus > td {
background: var(--table-body-hover-back-color); } }
/*
Definitions for contextual background elements, toasts and tooltips.
*/
/* Contextual module CSS variable definitions */
:root {
--mark-back-color: #3cb4e6;
--mark-fore-color: #ffffff; }
mark {
background: var(--mark-back-color);
color: var(--mark-fore-color);
font-size: 0.95em;
line-height: 1em;
border-radius: var(--universal-border-radius);
padding: calc(var(--universal-padding) / 4) var(--universal-padding); }
mark.inline-block {
display: inline-block;
font-size: 1em;
line-height: 1.4;
padding: calc(var(--universal-padding) / 2) var(--universal-padding); }
:root {
--toast-back-color: #424242;
--toast-fore-color: #fafafa; }
.toast {
position: fixed;
bottom: calc(var(--universal-margin) * 3);
left: 50%;
transform: translate(-50%, -50%);
z-index: 1111;
color: var(--toast-fore-color);
background: var(--toast-back-color);
border-radius: calc(var(--universal-border-radius) * 16);
padding: var(--universal-padding) calc(var(--universal-padding) * 3); }
:root {
--tooltip-back-color: #212121;
--tooltip-fore-color: #fafafa; }
.tooltip {
position: relative;
display: inline-block; }
.tooltip:before, .tooltip:after {
position: absolute;
opacity: 0;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%);
transition: all 0.3s;
z-index: 1010;
left: 50%; }
.tooltip:not(.bottom):before, .tooltip:not(.bottom):after {
bottom: 75%; }
.tooltip.bottom:before, .tooltip.bottom:after {
top: 75%; }
.tooltip:hover:before, .tooltip:hover:after, .tooltip:focus:before, .tooltip:focus:after {
opacity: 1;
clip: auto;
-webkit-clip-path: inset(0%);
clip-path: inset(0%); }
.tooltip:before {
content: '';
background: transparent;
border: var(--universal-margin) solid transparent;
left: calc(50% - var(--universal-margin)); }
.tooltip:not(.bottom):before {
border-top-color: #212121; }
.tooltip.bottom:before {
border-bottom-color: #212121; }
.tooltip:after {
content: attr(aria-label);
color: var(--tooltip-fore-color);
background: var(--tooltip-back-color);
border-radius: var(--universal-border-radius);
padding: var(--universal-padding);
white-space: nowrap;
transform: translateX(-50%); }
.tooltip:not(.bottom):after {
margin-bottom: calc(2 * var(--universal-margin)); }
.tooltip.bottom:after {
margin-top: calc(2 * var(--universal-margin)); }
:root {
--modal-overlay-color: rgba(0, 0, 0, 0.45);
--modal-close-color: #e6007e;
--modal-close-hover-color: #ffe97f; }
[type="checkbox"].modal {
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%); }
[type="checkbox"].modal + div {
position: fixed;
top: 0;
left: 0;
display: none;
width: 100vw;
height: 100vh;
background: var(--modal-overlay-color); }
[type="checkbox"].modal + div .card {
margin: 0 auto;
max-height: 50vh;
overflow: auto; }
[type="checkbox"].modal + div .card .modal-close {
position: absolute;
top: 0;
right: 0;
width: 1.75rem;
height: 1.75rem;
border-radius: var(--universal-border-radius);
padding: var(--universal-padding);
margin: 0;
cursor: pointer;
transition: background 0.3s; }
[type="checkbox"].modal + div .card .modal-close:before {
display: block;
content: '\00D7';
color: var(--modal-close-color);
position: relative;
font-family: sans-serif;
font-size: 1.75rem;
line-height: 1;
text-align: center; }
[type="checkbox"].modal + div .card .modal-close:hover, [type="checkbox"].modal + div .card .modal-close:focus {
background: var(--modal-close-hover-color); }
[type="checkbox"].modal:checked + div {
display: flex;
flex: 0 1 auto;
z-index: 1200; }
[type="checkbox"].modal:checked + div .card .modal-close {
z-index: 1211; }
:root {
--collapse-label-back-color: #03234b;
--collapse-label-fore-color: #ffffff;
--collapse-label-hover-back-color: #3cb4e6;
--collapse-selected-label-back-color: #3cb4e6;
--collapse-border-color: var(--collapse-label-back-color);
--collapse-selected-border-color: #ceecf8;
--collapse-content-back-color: #ffffff;
--collapse-selected-label-border-color: #3cb4e6; }
.collapse {
width: calc(100% - 2 * var(--universal-margin));
opacity: 1;
display: flex;
flex-direction: column;
margin: var(--universal-margin);
border-radius: var(--universal-border-radius); }
.collapse > [type="radio"], .collapse > [type="checkbox"] {
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%); }
.collapse > label {
flex-grow: 1;
display: inline-block;
height: 1.25rem;
cursor: pointer;
transition: background 0.2s;
color: var(--collapse-label-fore-color);
background: var(--collapse-label-back-color);
border: 0.0714285714rem solid var(--collapse-selected-border-color);
padding: calc(1.25 * var(--universal-padding)); }
.collapse > label:hover, .collapse > label:focus {
background: var(--collapse-label-hover-back-color); }
.collapse > label + div {
flex-basis: auto;
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
clip: rect(0 0 0 0);
-webkit-clip-path: inset(100%);
clip-path: inset(100%);
transition: max-height 0.3s;
max-height: 1px; }
.collapse > :checked + label {
background: var(--collapse-selected-label-back-color);
border-color: var(--collapse-selected-label-border-color); }
.collapse > :checked + label + div {
box-sizing: border-box;
position: relative;
width: 100%;
height: auto;
overflow: auto;
margin: 0;
background: var(--collapse-content-back-color);
border: 0.0714285714rem solid var(--collapse-selected-border-color);
border-top: 0;
padding: var(--universal-padding);
clip: auto;
-webkit-clip-path: inset(0%);
clip-path: inset(0%);
max-height: 100%; }
.collapse > label:not(:first-of-type) {
border-top: 0; }
.collapse > label:first-of-type {
border-radius: var(--universal-border-radius) var(--universal-border-radius) 0 0; }
.collapse > label:last-of-type:not(:first-of-type) {
border-radius: 0 0 var(--universal-border-radius) var(--universal-border-radius); }
.collapse > label:last-of-type:first-of-type {
border-radius: var(--universal-border-radius); }
.collapse > :checked:last-of-type:not(:first-of-type) + label {
border-radius: 0; }
.collapse > :checked:last-of-type + label + div {
border-radius: 0 0 var(--universal-border-radius) var(--universal-border-radius); }
/*
Custom elements for contextual background elements, toasts and tooltips.
*/
mark.tertiary {
--mark-back-color: #3cb4e6; }
mark.tag {
padding: calc(var(--universal-padding)/2) var(--universal-padding);
border-radius: 1em; }
/*
Definitions for progress elements and spinners.
*/
/* Progress module CSS variable definitions */
:root {
--progress-back-color: #3cb4e6;
--progress-fore-color: #555; }
progress {
display: block;
vertical-align: baseline;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
height: 0.75rem;
width: calc(100% - 2 * var(--universal-margin));
margin: var(--universal-margin);
border: 0;
border-radius: calc(2 * var(--universal-border-radius));
background: var(--progress-back-color);
color: var(--progress-fore-color); }
progress::-webkit-progress-value {
background: var(--progress-fore-color);
border-top-left-radius: calc(2 * var(--universal-border-radius));
border-bottom-left-radius: calc(2 * var(--universal-border-radius)); }
progress::-webkit-progress-bar {
background: var(--progress-back-color); }
progress::-moz-progress-bar {
background: var(--progress-fore-color);
border-top-left-radius: calc(2 * var(--universal-border-radius));
border-bottom-left-radius: calc(2 * var(--universal-border-radius)); }
progress[value="1000"]::-webkit-progress-value {
border-radius: calc(2 * var(--universal-border-radius)); }
progress[value="1000"]::-moz-progress-bar {
border-radius: calc(2 * var(--universal-border-radius)); }
progress.inline {
display: inline-block;
vertical-align: middle;
width: 60%; }
:root {
--spinner-back-color: #ddd;
--spinner-fore-color: #555; }
@keyframes spinner-donut-anim {
0% {
transform: rotate(0deg); }
100% {
transform: rotate(360deg); } }
.spinner {
display: inline-block;
margin: var(--universal-margin);
border: 0.25rem solid var(--spinner-back-color);
border-left: 0.25rem solid var(--spinner-fore-color);
border-radius: 50%;
width: 1.25rem;
height: 1.25rem;
animation: spinner-donut-anim 1.2s linear infinite; }
/*
Custom elements for progress bars and spinners.
*/
progress.primary {
--progress-fore-color: #1976d2; }
progress.secondary {
--progress-fore-color: #d32f2f; }
progress.tertiary {
--progress-fore-color: #308732; }
.spinner.primary {
--spinner-fore-color: #1976d2; }
.spinner.secondary {
--spinner-fore-color: #d32f2f; }
.spinner.tertiary {
--spinner-fore-color: #308732; }
/*
Definitions for icons - powered by Feather (https://feathericons.com/).
*/
span[class^='icon-'] {
display: inline-block;
height: 1em;
width: 1em;
vertical-align: -0.125em;
background-size: contain;
margin: 0 calc(var(--universal-margin) / 4); }
span[class^='icon-'].secondary {
-webkit-filter: invert(25%);
filter: invert(25%); }
span[class^='icon-'].inverse {
-webkit-filter: invert(100%);
filter: invert(100%); }
span.icon-alert {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12' y2='16'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-bookmark {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z'%3E%3C/path%3E%3C/svg%3E"); }
span.icon-calendar {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-credit {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='1' y='4' width='22' height='16' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='1' y1='10' x2='23' y2='10'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-edit {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 14.66V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5.34'%3E%3C/path%3E%3Cpolygon points='18 2 22 6 12 16 8 16 8 12 18 2'%3E%3C/polygon%3E%3C/svg%3E"); }
span.icon-link {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6'%3E%3C/path%3E%3Cpolyline points='15 3 21 3 21 9'%3E%3C/polyline%3E%3Cline x1='10' y1='14' x2='21' y2='3'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-help {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3'%3E%3C/path%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='17' x2='12' y2='17'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-home {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z'%3E%3C/path%3E%3Cpolyline points='9 22 9 12 15 12 15 22'%3E%3C/polyline%3E%3C/svg%3E"); }
span.icon-info {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='16' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='8' x2='12' y2='8'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-lock {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='11' width='18' height='11' rx='2' ry='2'%3E%3C/rect%3E%3Cpath d='M7 11V7a5 5 0 0 1 10 0v4'%3E%3C/path%3E%3C/svg%3E"); }
span.icon-mail {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z'%3E%3C/path%3E%3Cpolyline points='22,6 12,13 2,6'%3E%3C/polyline%3E%3C/svg%3E"); }
span.icon-location {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z'%3E%3C/path%3E%3Ccircle cx='12' cy='10' r='3'%3E%3C/circle%3E%3C/svg%3E"); }
span.icon-phone {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z'%3E%3C/path%3E%3C/svg%3E"); }
span.icon-rss {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 11a9 9 0 0 1 9 9'%3E%3C/path%3E%3Cpath d='M4 4a16 16 0 0 1 16 16'%3E%3C/path%3E%3Ccircle cx='5' cy='19' r='1'%3E%3C/circle%3E%3C/svg%3E"); }
span.icon-search {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-settings {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='3'%3E%3C/circle%3E%3Cpath d='M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z'%3E%3C/path%3E%3C/svg%3E"); }
span.icon-share {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='18' cy='5' r='3'%3E%3C/circle%3E%3Ccircle cx='6' cy='12' r='3'%3E%3C/circle%3E%3Ccircle cx='18' cy='19' r='3'%3E%3C/circle%3E%3Cline x1='8.59' y1='13.51' x2='15.42' y2='17.49'%3E%3C/line%3E%3Cline x1='15.41' y1='6.51' x2='8.59' y2='10.49'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-cart {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='9' cy='21' r='1'%3E%3C/circle%3E%3Ccircle cx='20' cy='21' r='1'%3E%3C/circle%3E%3Cpath d='M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6'%3E%3C/path%3E%3C/svg%3E"); }
span.icon-upload {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4'%3E%3C/path%3E%3Cpolyline points='17 8 12 3 7 8'%3E%3C/polyline%3E%3Cline x1='12' y1='3' x2='12' y2='15'%3E%3C/line%3E%3C/svg%3E"); }
span.icon-user {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%2303234b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2'%3E%3C/path%3E%3Ccircle cx='12' cy='7' r='4'%3E%3C/circle%3E%3C/svg%3E"); }
/*
Definitions for STMicroelectronics icons (https://brandportal.st.com/document/26).
*/
span.icon-st-update {
background-image: url("Update.svg"); }
span.icon-st-add {
background-image: url("Add button.svg"); }
/*
Definitions for utilities and helper classes.
*/
/* Utility module CSS variable definitions */
:root {
--generic-border-color: rgba(0, 0, 0, 0.3);
--generic-box-shadow: 0 0.2857142857rem 0.2857142857rem 0 rgba(0, 0, 0, 0.125), 0 0.1428571429rem 0.1428571429rem -0.1428571429rem rgba(0, 0, 0, 0.125); }
.hidden {
display: none !important; }
.visually-hidden {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: -1px !important;
border: 0 !important;
padding: 0 !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(100%) !important;
clip-path: inset(100%) !important;
overflow: hidden !important; }
.bordered {
border: 0.0714285714rem solid var(--generic-border-color) !important; }
.rounded {
border-radius: var(--universal-border-radius) !important; }
.circular {
border-radius: 50% !important; }
.shadowed {
box-shadow: var(--generic-box-shadow) !important; }
.responsive-margin {
margin: calc(var(--universal-margin) / 4) !important; }
@media screen and (min-width: 500px) {
.responsive-margin {
margin: calc(var(--universal-margin) / 2) !important; } }
@media screen and (min-width: 1280px) {
.responsive-margin {
margin: var(--universal-margin) !important; } }
.responsive-padding {
padding: calc(var(--universal-padding) / 4) !important; }
@media screen and (min-width: 500px) {
.responsive-padding {
padding: calc(var(--universal-padding) / 2) !important; } }
@media screen and (min-width: 1280px) {
.responsive-padding {
padding: var(--universal-padding) !important; } }
@media screen and (max-width: 499px) {
.hidden-sm {
display: none !important; } }
@media screen and (min-width: 500px) and (max-width: 1279px) {
.hidden-md {
display: none !important; } }
@media screen and (min-width: 1280px) {
.hidden-lg {
display: none !important; } }
@media screen and (max-width: 499px) {
.visually-hidden-sm {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: -1px !important;
border: 0 !important;
padding: 0 !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(100%) !important;
clip-path: inset(100%) !important;
overflow: hidden !important; } }
@media screen and (min-width: 500px) and (max-width: 1279px) {
.visually-hidden-md {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: -1px !important;
border: 0 !important;
padding: 0 !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(100%) !important;
clip-path: inset(100%) !important;
overflow: hidden !important; } }
@media screen and (min-width: 1280px) {
.visually-hidden-lg {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: -1px !important;
border: 0 !important;
padding: 0 !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(100%) !important;
clip-path: inset(100%) !important;
overflow: hidden !important; } }
/*# sourceMappingURL=mini-custom.css.map */
img[alt="ST logo"] { display: block; margin: auto; width: 75%; max-width: 250px; min-width: 71px; }
img[alt="Cube logo"] { float: right; width: 30%; max-width: 10rem; min-width: 8rem; padding-right: 1rem;}
.figure {
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/drivers/STM32U5xx_HAL_Driver/_htmresc/mini-st_2020.css
|
CSS
|
apache-2.0
| 57,898
|
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include "k_api.h"
#include "aos/hal/uart.h"
#include "k_config.h"
#include "board.h"
#include "stm32u5xx_hal.h"
extern UART_HandleTypeDef huart1;
#define MAX_BUF_UART_BYTES 128
kbuf_queue_t g_buf_queue_uart;
char g_buf_uart[MAX_BUF_UART_BYTES];
int32_t hal_uart_init(uart_dev_t *uart)
{
kstat_t err_code;
uart->priv = &huart1;
err_code = krhino_buf_queue_create(&g_buf_queue_uart, "buf_queue_uart",
g_buf_uart, MAX_BUF_UART_BYTES, 1);
return 0;
}
int32_t hal_uart_send(uart_dev_t *uart, const void *data, uint32_t size, uint32_t timeout)
{
uint32_t i;
uint8_t byte;
uint32_t ret = 0;
for(i=0;i<size;i++)
{
byte = *((uint8_t *)data + i);
HAL_UART_Transmit(&huart1, (uint8_t *)&byte, 1, 0xFFFF);
}
return ret;
}
int32_t hal_uart_recv_II(uart_dev_t *uart, void *data, uint32_t expect_size,
uint32_t *recv_size, uint32_t timeout)
{
// int32_t ret = -1;
// if((uart != NULL) && (data != NULL)) {
// ret = HAL_UART_Receive_IT((UART_HandleTypeDef *)uart->priv,
// (uint8_t *)data, *recv_size);
// }
// return ret;
}
int32_t hal_uart_finalize(uart_dev_t *uart)
{
}
|
YifuLiu/AliOS-Things
|
hardware/chip/stm32u5/hal/uart.c
|
C
|
apache-2.0
| 1,258
|
##
# Copyright (C) 2017 C-SKY Microsystems Co., Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
INCDIR += -I$(KERNELDIR)/rhino/arch/include
INCDIR += -I$(KERNELDIR)/rhino/core/include
ifeq ($(CONFIG_KERNEL_PWR_MGMT), y)
INCDIR += -I$(KERNELDIR)/rhino/common
INCDIR += -I$(KERNELDIR)/rhino/pwrmgmt
endif
INCDIR += -I$(LIBSDIR)/mm
INCDIR += -I$(LIBSDIR)/trace/include
KERNEL_CSRC += $(KERNELDIR)/rhino/driver/systick.c
KERNEL_CSRC += $(KERNELDIR)/rhino/driver/hook_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/driver/hook_weak.c
KERNEL_CSRC += $(KERNELDIR)/rhino/driver/yoc_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/adapter/csi_rhino.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_buf_queue.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_dyn_mem_proc.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_err.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_event.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_idle.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm_debug.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm_blk.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm_region.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm_firstfit.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mm_bestfit.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_ringbuf.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_mutex.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_obj.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_pend.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_queue.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_sem.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_stats.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_sys.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_task.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_task_sem.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_tick.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_time.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_timer.c
KERNEL_CSRC += $(KERNELDIR)/rhino/core/k_workqueue.c
KERNEL_CSRC += $(KERNELDIR)/rhino/common/k_atomic.c
KERNEL_CSRC += $(KERNELDIR)/rhino/common/k_ffs.c
ifeq ($(CONFIG_KERNEL_PWR_MGMT), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/board/board_cpu_pwr.c
KERNEL_CSRC += $(KERNELDIR)/rhino/board/board_cpu_pwr_systick.c
KERNEL_CSRC += $(KERNELDIR)/rhino/board/board_cpu_pwr_timer.c
KERNEL_CSRC += $(KERNELDIR)/rhino/pwrmgmt/cpu_pwr_hal_lib.c
KERNEL_CSRC += $(KERNELDIR)/rhino/pwrmgmt/cpu_pwr_lib.c
KERNEL_CSRC += $(KERNELDIR)/rhino/pwrmgmt/cpu_pwr_show.c
KERNEL_CSRC += $(KERNELDIR)/rhino/pwrmgmt/cpu_tickless.c
endif
ifeq ($(CONFIG_SUPPORT_TSPEND), y)
IS_TSPEND=tspend
else
IS_TSPEND=non_tspend
endif
ifeq ($(CONFIG_SYSTEM_SECURE), y)
IS_SECURE=security
else
IS_SECURE=non_security
endif
ifeq ($(CONFIG_CPU_E802)$(CONFIG_CPU_S802)$(CONFIG_CPU_E802T)$(CONFIG_CPU_S802T)$(CONFIG_CPU_CK802), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/802/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/802/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/802/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/802/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/802/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_E803)$(CONFIG_CPU_S803)$(CONFIG_CPU_E803T)$(CONFIG_CPU_S803T)$(CONFIG_CPU_CK803), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/803/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_E804D)$(CONFIG_CPU_E804DT)$(CONFIG_CPU_CK803ER1)$(CONFIG_CPU_CK803ER2)$(CONFIG_CPU_CK803ER3), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804d/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804d/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804d/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/804d/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804d/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_E804F)$(CONFIG_CPU_E804FT)$(CONFIG_CPU_CK803F), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804f/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804f/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804f/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/804f/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804f/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_CK803EF), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803ef_32gpr/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803ef_32gpr/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803ef_32gpr/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/803ef_32gpr/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/803ef_32gpr/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_E804DF)$(CONFIG_CPU_E804DFT)$(CONFIG_CPU_CK804EF)$(CONFIG_CPU_CK803EFR1)$(CONFIG_CPU_CK803EFR2)$(CONFIG_CPU_CK803EFR3), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804df/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804df/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804df/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/804df/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/804df/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_I805)$(CONFIG_CPU_I805F)$(CONFIG_CPU_CK805)$(CONFIG_CPU_CK805F), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/805/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/805/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/805/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/805/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/805/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_C807)$(CONFIG_CPU_R807), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/807/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_C807F)$(CONFIG_CPU_C807FV)$(CONFIG_CPU_R807F), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807f/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807f/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807f/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/807f/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/807f/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_C810)$(CONFIG_CPU_C810V)$(CONFIG_CPU_C810T)$(CONFIG_CPU_C810TV), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/810/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/810/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/810/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/810/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/810/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_CK610E), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/ck610/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_CK610EF), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610f/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610f/csky_sched.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610f/dump_backtrace.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/csky/ck610f/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/csky/ck610f/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_ARCH_RV32)$(CONFIG_ARCH_RV32EMC), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/riscv/rv32_16gpr/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/riscv/rv32_16gpr/csky_sched.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/riscv/rv32_16gpr/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/riscv/rv32_16gpr/$(IS_SECURE)/port_c.c
endif
ifeq ($(CONFIG_CPU_CM0), y)
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/arm/cm0/cpu_impl.c
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/arm/cm0/csky_sched.c
KERNEL_SSRC += $(KERNELDIR)/rhino/arch/arm/cm0/$(IS_TSPEND)/port_s.S
KERNEL_CSRC += $(KERNELDIR)/rhino/arch/arm/cm0/$(IS_SECURE)/port_c.c
endif
|
YifuLiu/AliOS-Things
|
kernel/rhino/csi.mk
|
Makefile
|
apache-2.0
| 8,836
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_API_H
#define K_API_H
/** @addtogroup rhino API
* All rhino header files.
*
* @{
*/
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <limits.h>
#include "k_config.h"
#include "k_default_config.h"
#include "k_types.h"
#include "k_err.h"
#include "k_sys.h"
#include "k_critical.h"
#include "k_spin_lock.h"
#include "k_list.h"
#if (RHINO_CONFIG_SCHED_CFS > 0)
#include "k_cfs.h"
#endif
#include "k_obj.h"
#include "k_sched.h"
#include "k_task.h"
#include "k_ringbuf.h"
#include "k_queue.h"
#include "k_buf_queue.h"
#include "k_sem.h"
#include "k_task_sem.h"
#include "k_mutex.h"
#include "k_timer.h"
#include "k_time.h"
#include "k_event.h"
#include "k_stats.h"
#if RHINO_CONFIG_MM_DEBUG
#include "k_mm_debug.h"
#endif
#include "k_mm_blk.h"
#include "k_mm_region.h"
#include "k_mm.h"
#include "k_workqueue.h"
#include "k_internal.h"
#include "k_trace.h"
#include "k_soc.h"
#include "k_hook.h"
#include "k_bitmap.h"
#include "port.h"
/** @} */
#endif /* K_API_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_api.h
|
C
|
apache-2.0
| 1,071
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_ATOMIC_H
#define K_ATOMIC_H
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned int atomic_t;
typedef atomic_t atomic_val_t;
extern atomic_val_t rhino_atomic_add(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_sub(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_inc(atomic_t *target);
extern atomic_val_t rhino_atomic_dec(atomic_t *target);
extern atomic_val_t rhino_atomic_set(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_get(const atomic_t *target);
extern atomic_val_t rhino_atomic_or(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_xor(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_and(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_nand(atomic_t *target, atomic_val_t value);
extern atomic_val_t rhino_atomic_clear(atomic_t *target);
extern int rhino_atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value);
#ifdef __cplusplus
}
#endif
#endif /* K_ATOMIC_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_atomic.h
|
C
|
apache-2.0
| 1,150
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_BITMAP_H
#define K_BITMAP_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino bitmap
* Bit operation.
*
* @{
*/
#define BITMAP_UNIT_SIZE 32U
#define BITMAP_UNIT_MASK (BITMAP_UNIT_SIZE - 1)
#define BITMAP_UNIT_BITS 5U
#define BITMAP_MASK(nr) (1UL << (BITMAP_UNIT_MASK - ((nr) & BITMAP_UNIT_MASK)))
#define BITMAP_WORD(nr) ((nr) >> BITMAP_UNIT_BITS)
/**
* Count Leading Zeros (clz).
* Counts the number of zero bits preceding the most significant one bit.
*
* @param[in] x input unsigned int
*
* @return 0~32
*/
RHINO_INLINE uint8_t krhino_clz32(uint32_t x)
{
uint8_t n = 0;
if (x == 0) {
return 32;
}
#ifdef RHINO_BIT_CLZ
n = RHINO_BIT_CLZ(x);
#else
if ((x & 0XFFFF0000) == 0) {
x <<= 16;
n += 16;
}
if ((x & 0XFF000000) == 0) {
x <<= 8;
n += 8;
}
if ((x & 0XF0000000) == 0) {
x <<= 4;
n += 4;
}
if ((x & 0XC0000000) == 0) {
x <<= 2;
n += 2;
}
if ((x & 0X80000000) == 0) {
n += 1;
}
#endif
return n;
}
/**
* Count Trailing Zeros (ctz).
* Counts the number of zero bits succeeding the least significant one bit.
*
* @param[in] x input unsigned int
*
* @return 0~32
*/
RHINO_INLINE uint8_t krhino_ctz32(uint32_t x)
{
uint8_t n = 0;
if (x == 0) {
return 32;
}
#ifdef RHINO_BIT_CTZ
n = RHINO_BIT_CTZ(x);
#else
if ((x & 0X0000FFFF) == 0) {
x >>= 16;
n += 16;
}
if ((x & 0X000000FF) == 0) {
x >>= 8;
n += 8;
}
if ((x & 0X0000000F) == 0) {
x >>= 4;
n += 4;
}
if ((x & 0X00000003) == 0) {
x >>= 2;
n += 2;
}
if ((x & 0X00000001) == 0) {
n += 1;
}
#endif
return n;
}
/**
* Set a bit of the bitmap for task priority.
*
* @param[in] bitmap pointer to the bitmap
* @param[in] nr position of the bitmap to set, from msb to lsb
*
* @return no return
*/
RHINO_INLINE void krhino_bitmap_set(uint32_t *bitmap, int32_t nr)
{
bitmap[BITMAP_WORD(nr)] |= BITMAP_MASK(nr);
}
/**
* Clear a bit of the bitmap for task priority.
*
* @param[in] bitmap pointer to the bitmap
* @param[in] nr position of the bitmap to clear
*
* @return no return
*/
RHINO_INLINE void krhino_bitmap_clear(uint32_t *bitmap, int32_t nr)
{
bitmap[BITMAP_WORD(nr)] &= ~BITMAP_MASK(nr);
}
/**
* Find the first bit(1) of the bitmap.
*
* @param[in] bitmap pointer to the bitmap
*
* @return the first bit position
*/
RHINO_INLINE int32_t krhino_bitmap_first(uint32_t *bitmap)
{
int32_t nr = 0;
while (*bitmap == 0UL) {
nr += BITMAP_UNIT_SIZE;
bitmap++;
}
nr += krhino_clz32(*bitmap);
return nr;
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_BITMAP_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_bitmap.h
|
C
|
apache-2.0
| 2,926
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_BUF_QUEUE_H
#define K_BUF_QUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino bitmap
* buf_queue passes the specified length information.
* When receiving a message, it can cause task blocking.
* When sending a messages, it can't cause task blocking.
* may discard the messages when the buffer is full.
*
* @{
*/
/**
* buf_que object
*/
typedef struct {
blk_obj_t blk_obj; /**< Manage blocked tasks */
void *buf; /**< ringbuf address */
k_ringbuf_t ringbuf; /**< ringbuf management */
size_t max_msg_size; /**< limited message length */
size_t cur_num; /**< msgs used */
size_t peak_num; /**< maximum msgs used */
size_t min_free_buf_size; /**< minimum free size */
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t buf_queue_item; /**< kobj list for statistics */
#endif
#if (RHINO_CONFIG_USER_SPACE > 0)
uint32_t key;
#endif
uint8_t mm_alloc_flag; /**< buffer from internal malloc or caller input */
} kbuf_queue_t;
/**
* buf_queue infomation
*/
typedef struct {
size_t buf_size; /**< whole queue size */
size_t max_msg_size;
size_t cur_num;
size_t peak_num;
size_t free_buf_size;
size_t min_free_buf_size;
} kbuf_queue_info_t;
/**
* Create a buf_queue.
*
* @param[in] queue pointer to the queue (the space is provided outside, by user)
* @param[in] name name of the queue
* @param[in] buf pointer to the buf
* @param[in] size size of the buf
* @param[in] max_msg max size of one msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_create(kbuf_queue_t *queue, const name_t *name,
void *buf, size_t size, size_t max_msg);
/**
* Create a fix-msg-len buf_queue.
*
* @param[in] queue pointer to the queue (the space is provided outside, by user)
* @param[in] name name of the queue
* @param[in] buf pointer to the buf
* @param[in] msg_size fix size of the msg
* @param[in] msg_num number of msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_fix_buf_queue_create(kbuf_queue_t *queue, const name_t *name,
void *buf, size_t msg_size, size_t msg_num);
/**
* Delete a buf_queue.
*
* @param[in] queue pointer to the buf_queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_del(kbuf_queue_t *queue);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Malloc and create a variable-msg-len buf_queue.
* Each message consumes extra 4 bytes to save length.
*
* @param[out] queue pointer to the queue (the space is provided inside, from heap)
* @param[in] name pointer to the nam
* @param[in] size size of the buf
* @param[in] max_msg max size of one msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_dyn_create(kbuf_queue_t **queue, const name_t *name,
size_t size, size_t max_msg);
/**
* Malloc and create a fix-msg-len buf_queue.
*
* @param[out] queue pointer to the queue (the space is provided inside, from heap)
* @param[in] name name of the queue
* @param[in] buf pointer to the buf
* @param[in] msg_size size of the msg
* @param[in] msg_num number of msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_fix_buf_queue_dyn_create(kbuf_queue_t **queue, const name_t *name,
size_t msg_size, size_t msg_num);
/**
* Delete and free a buf_queue.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_dyn_del(kbuf_queue_t *queue);
#endif
/**
* This function will send a msg at the end of queue.
* If queue is full, task is non-blocking, return fail.
*
* @param[in] queue pointer to the queue
* @param[in] msg pointer to msg to be send
* @param[in] size size of the msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_send(kbuf_queue_t *queue, void *msg, size_t size);
/**
* This function will receive msg form aqueue.
* If queue is empty, task is blocking.
*
* @param[in] queue pointer to the queue
* @param[in] ticks ticks to wait before receiving msg
* @param[out] msg pointer to the buf to save msg
* @param[out] size size of received msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_recv(kbuf_queue_t *queue, tick_t ticks, void *msg, size_t *size);
/**
* Reset queue, abondon the msg.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_flush(kbuf_queue_t *queue);
/**
* Get information of a queue.
*
* @param[in] queue pointer to the queue
* @param[out] info info msg of the queue buf
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_buf_queue_info_get(kbuf_queue_t *queue, kbuf_queue_info_t *info);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_BUF_QUEUE_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_buf_queue.h
|
C
|
apache-2.0
| 5,483
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_CFS_H
#define K_CFS_H
#include "k_rbtree.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino cfs
* Completely Fair Scheduler.
*
* @{
*/
typedef struct cfs_node_s {
struct k_rbtree_node_t rbt_node; /* rbttree node */
lr_timer_t key; /* key */
} cfs_node;
void cfs_node_insert(cfs_node *node, lr_timer_t key);
void cfs_node_del(cfs_node *node);
lr_timer_t cfs_node_min_get(void);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_CFS_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_cfs.h
|
C
|
apache-2.0
| 563
|
/*
* Copyright (C) 2018 Alibaba Group Holding Limited
*/
/*
modification history
--------------------
21jan2018,WangMin writen.
*/
/*
DESCRIPTION
This file provides base type of cpu set and method for cpu set.
*/
#ifndef __cpuset_h__
#define __cpuset_h__
#include "k_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif
/* typedefs */
typedef unsigned int cpuset_t;
#define CPUSET_ATOMIC_SET(cpuset, n) \
(void) rhino_atomic_or ((atomic_t *) &(cpuset), 1 << (n))
#define CPUSET_ATOMIC_CLR(cpuset, n) \
(void) rhino_atomic_and ((atomic_t *) &(cpuset), ~((1 << (n))))
#define CPUSET_ATOMIC_COPY(cpusetDst, cpusetSrc) \
(void) rhino_atomic_set ((atomic_t *) &(cpusetDst), (atomic_t) (cpusetSrc))
#define CPUSET_CLR(cpuset, n) ((cpuset) &= ~(1 << (n)))
#define CPUSET_ZERO(cpuset) ((cpuset) = 0)
#define CPUSET_IS_ZERO(cpuset) ((cpuset) == 0)
#define CPUSET_SET(cpuset, n) ((cpuset) |= (1 << (n)))
#define CPUSET_ISSET(cpuset, n) ((cpuset) & (1 << (n)))
#ifdef __cplusplus
}
#endif
#endif /* __cpuset_h__ */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_cpuset.h
|
C
|
apache-2.0
| 1,095
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_CRITICAL_H
#define K_CRITICAL_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino critical
* Critical zone protection, os use internally.
*
* @{
*/
#if (RHINO_CONFIG_SYS_STATS > 0)
/* For measure max int disable count */
#define RHINO_INTDIS_MEAS_START() intrpt_disable_measure_start()
#define RHINO_INTDIS_MEAS_STOP() intrpt_disable_measure_stop()
#else
#define RHINO_INTDIS_MEAS_START()
#define RHINO_INTDIS_MEAS_STOP()
#endif
/**
* Critical zone begin.
*
* @return none
*/
#define RHINO_CRITICAL_ENTER() \
do { \
RHINO_CPU_INTRPT_DISABLE(); \
RHINO_INTDIS_MEAS_START(); \
} while (0)
/**
* Critical zone end.
*
* @return none
*/
#define RHINO_CRITICAL_EXIT() \
do { \
RHINO_INTDIS_MEAS_STOP(); \
RHINO_CPU_INTRPT_ENABLE(); \
} while (0)
/**
* Critical zone end and trigger scheduling.
*
* @return none
*/
#if (RHINO_CONFIG_CPU_NUM > 1)
#define RHINO_CRITICAL_EXIT_SCHED() \
do { \
RHINO_INTDIS_MEAS_STOP(); \
core_sched(); \
cpu_intrpt_restore(cpsr); \
} while (0)
#else
#define RHINO_CRITICAL_EXIT_SCHED() \
do { \
RHINO_INTDIS_MEAS_STOP(); \
core_sched(); \
RHINO_CPU_INTRPT_ENABLE(); \
} while (0)
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_CRITICAL_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_critical.h
|
C
|
apache-2.0
| 1,564
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_DEFAULT_CONFIG_H
#define K_DEFAULT_CONFIG_H
#ifndef RHINO_CONFIG_USER_SPACE
#define RHINO_CONFIG_USER_SPACE 0
#endif
#ifndef RHINO_SCHED_NONE_PREEMPT
#define RHINO_SCHED_NONE_PREEMPT 0
#endif
#ifndef RHINO_CONFIG_STK_CHK_WORDS
#define RHINO_CONFIG_STK_CHK_WORDS 1
#endif
#ifndef RHINO_CONFIG_CPU_STACK_DOWN
#define RHINO_CONFIG_CPU_STACK_DOWN 1
#endif
/* kernel feature config */
#ifndef RHINO_CONFIG_SEM
#define RHINO_CONFIG_SEM 1
#endif
#ifndef RHINO_CONFIG_TASK_SEM
#define RHINO_CONFIG_TASK_SEM 1
#endif
#ifndef RHINO_CONFIG_QUEUE
#define RHINO_CONFIG_QUEUE 1
#endif
#ifndef RHINO_CONFIG_BUF_QUEUE
#define RHINO_CONFIG_BUF_QUEUE 1
#endif
#ifndef RHINO_CONFIG_EVENT_FLAG
#define RHINO_CONFIG_EVENT_FLAG 1
#endif
#ifndef RHINO_CONFIG_TIMER
#define RHINO_CONFIG_TIMER 1
#endif
#if (RHINO_CONFIG_TIMER > 0)
#ifndef RHINO_CONFIG_TIMER_TASK_STACK_SIZE
#define RHINO_CONFIG_TIMER_TASK_STACK_SIZE 200
#endif
#ifndef RHINO_CONFIG_TIMER_TASK_PRI
#define RHINO_CONFIG_TIMER_TASK_PRI 5
#endif
#ifndef RHINO_CONFIG_TIMER_MSG_NUM
#define RHINO_CONFIG_TIMER_MSG_NUM 20
#endif
#endif /* RHINO_CONFIG_TIMER */
#ifndef RHINO_CONFIG_WORKQUEUE
#define RHINO_CONFIG_WORKQUEUE 0
#endif
#ifndef RHINO_CONFIG_MUTEX_INHERIT
#define RHINO_CONFIG_MUTEX_INHERIT 0
#endif
#if (RHINO_CONFIG_WORKQUEUE > 0)
#ifndef RHINO_CONFIG_WORKQUEUE_STACK_SIZE
#define RHINO_CONFIG_WORKQUEUE_STACK_SIZE 512
#endif
#ifndef RHINO_CONFIG_WORKQUEUE_TASK_PRIO
#define RHINO_CONFIG_WORKQUEUE_TASK_PRIO 20
#endif
#endif /* RHINO_CONFIG_WORKQUEUE */
/* kernel task config */
#ifndef RHINO_CONFIG_TASK_INFO
#define RHINO_CONFIG_TASK_INFO 0
#endif
#ifndef RHINO_CONFIG_TASK_INFO_NUM
#define RHINO_CONFIG_TASK_INFO_NUM 2
#endif
#ifndef RHINO_CONFIG_TASK_DEL
#define RHINO_CONFIG_TASK_DEL 1
#endif
#ifndef RHINO_CONFIG_SCHED_RR
#define RHINO_CONFIG_SCHED_RR 1
#endif
#ifndef RHINO_CONFIG_SCHED_CFS
#define RHINO_CONFIG_SCHED_CFS 0
#endif
#if (RHINO_CONFIG_SCHED_RR > 0)
#ifndef RHINO_CONFIG_TIME_SLICE_DEFAULT
#define RHINO_CONFIG_TIME_SLICE_DEFAULT 50
#endif
#endif /* RHINO_CONFIG_SCHED_RR */
#ifndef RHINO_CONFIG_PRI_MAX
#define RHINO_CONFIG_PRI_MAX 62
#endif
#ifndef RHINO_CONFIG_USER_PRI_MAX
#define RHINO_CONFIG_USER_PRI_MAX (RHINO_CONFIG_PRI_MAX - 2)
#endif
/* kernel timer&tick config */
#ifndef RHINO_CONFIG_HW_COUNT
#define RHINO_CONFIG_HW_COUNT 0
#endif
#ifndef RHINO_CONFIG_TICKS_PER_SECOND
#define RHINO_CONFIG_TICKS_PER_SECOND 1000
#endif
/* kernel intrpt config */
/* kernel stack ovf check */
#ifndef RHINO_CONFIG_INTRPT_STACK_OVF_CHECK
#define RHINO_CONFIG_INTRPT_STACK_OVF_CHECK 0
#endif
#if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0)
#ifndef RHINO_CONFIG_INTRPT_STACK_TOP
#define RHINO_CONFIG_INTRPT_STACK_TOP 0
#endif
#endif /* RHINO_CONFIG_SCHED_RR */
#ifndef RHINO_CONFIG_TASK_STACK_OVF_CHECK
#define RHINO_CONFIG_TASK_STACK_OVF_CHECK 0
#endif
/* kernel dyn alloc config */
#ifndef RHINO_CONFIG_KOBJ_DYN_ALLOC
#define RHINO_CONFIG_KOBJ_DYN_ALLOC 1
#endif
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
#ifndef RHINO_CONFIG_K_DYN_TASK_STACK
#define RHINO_CONFIG_K_DYN_TASK_STACK 256
#endif
#ifndef RHINO_CONFIG_K_DYN_MEM_TASK_PRI
#define RHINO_CONFIG_K_DYN_MEM_TASK_PRI 6
#endif
#endif /* RHINO_CONFIG_KOBJ_DYN_ALLOC */
/* kernel idle config */
#ifndef RHINO_CONFIG_IDLE_TASK_STACK_SIZE
#define RHINO_CONFIG_IDLE_TASK_STACK_SIZE 100
#endif
/* kernel hook conf */
#ifndef RHINO_CONFIG_USER_HOOK
#define RHINO_CONFIG_USER_HOOK 1
#endif
/* kernel stats config */
#ifndef RHINO_CONFIG_KOBJ_LIST
#define RHINO_CONFIG_KOBJ_LIST 1
#endif
#ifndef RHINO_CONFIG_SYS_STATS
#define RHINO_CONFIG_SYS_STATS 0
#endif
#ifndef RHINO_CONFIG_CPU_NUM
#define RHINO_CONFIG_CPU_NUM 1
#endif
#ifndef RHINO_CONFIG_PWRMGMT
#define RHINO_CONFIG_PWRMGMT 0
#endif
#ifndef RHINO_CONFIG_CPU_USAGE_STATS
#define RHINO_CONFIG_CPU_USAGE_STATS 0
#endif
#ifndef RHINO_CONFIG_NEWLIBC_REENT
#define RHINO_CONFIG_NEWLIBC_REENT 1
#endif
#if (RHINO_CONFIG_SCHED_CFS >= 1)
#if (RHINO_CONFIG_PRI_MAX != 141)
#error "RHINO_CONFIG_SCHED_CFS priority set error"
#endif
#endif
#if ((RHINO_CONFIG_TIMER >= 1) && (RHINO_CONFIG_BUF_QUEUE == 0))
#error "RHINO_CONFIG_BUF_QUEUE should be 1 when RHINO_CONFIG_TIMER is enabled."
#endif
#if (RHINO_CONFIG_PRI_MAX >= 256)
#error "RHINO_CONFIG_PRI_MAX must be <= 255."
#endif
#if ((RHINO_CONFIG_SEM == 0) && (RHINO_CONFIG_TASK_SEM >= 1))
#error "you need enable RHINO_CONFIG_SEM as well."
#endif
#if ((RHINO_CONFIG_HW_COUNT == 0) && (RHINO_CONFIG_SYS_STATS >= 1))
#error "you need enable RHINO_CONFIG_HW_COUNT as well."
#endif
#endif /* K_DEFAULT_CONFIG_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_default_config.h
|
C
|
apache-2.0
| 5,090
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_ERR_H
#define K_ERR_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino err
* System error code, and error hook.
*
* @{
*/
/* Define basic errno for rhino modules */
typedef enum
{
RHINO_SUCCESS = 0u,
RHINO_SYS_FATAL_ERR,
RHINO_SYS_SP_ERR,
RHINO_RUNNING,
RHINO_STOPPED,
RHINO_INV_PARAM,
RHINO_NULL_PTR,
RHINO_INV_ALIGN,
RHINO_KOBJ_TYPE_ERR,
RHINO_KOBJ_DEL_ERR,
RHINO_KOBJ_DOCKER_EXIST,
RHINO_KOBJ_BLK,
RHINO_KOBJ_SET_FULL,
RHINO_NOTIFY_FUNC_EXIST,
RHINO_MM_POOL_SIZE_ERR = 100u,
RHINO_MM_ALLOC_SIZE_ERR,
RHINO_MM_FREE_ADDR_ERR,
RHINO_MM_CORRUPT_ERR,
RHINO_DYN_MEM_PROC_ERR,
RHINO_NO_MEM,
RHINO_RINGBUF_FULL,
RHINO_RINGBUF_EMPTY,
RHINO_SCHED_DISABLE = 200u,
RHINO_SCHED_ALREADY_ENABLED,
RHINO_SCHED_LOCK_COUNT_OVF,
RHINO_INV_SCHED_WAY,
RHINO_TASK_INV_STACK_SIZE = 300u,
RHINO_TASK_NOT_SUSPENDED,
RHINO_TASK_DEL_NOT_ALLOWED,
RHINO_TASK_SUSPEND_NOT_ALLOWED,
RHINO_TASK_CANCELED,
RHINO_SUSPENDED_COUNT_OVF,
RHINO_BEYOND_MAX_PRI,
RHINO_PRI_CHG_NOT_ALLOWED,
RHINO_INV_TASK_STATE,
RHINO_IDLE_TASK_EXIST,
RHINO_NO_PEND_WAIT = 400u,
RHINO_BLK_ABORT,
RHINO_BLK_TIMEOUT,
RHINO_BLK_DEL,
RHINO_BLK_INV_STATE,
RHINO_BLK_POOL_SIZE_ERR,
RHINO_TIMER_STATE_INV = 500u,
RHINO_NO_THIS_EVENT_OPT = 600u,
RHINO_BUF_QUEUE_INV_SIZE = 700u,
RHINO_BUF_QUEUE_SIZE_ZERO,
RHINO_BUF_QUEUE_FULL,
RHINO_BUF_QUEUE_MSG_SIZE_OVERFLOW,
RHINO_QUEUE_FULL,
RHINO_QUEUE_NOT_FULL,
RHINO_SEM_OVF = 800u,
RHINO_SEM_TASK_WAITING,
RHINO_MUTEX_NOT_RELEASED_BY_OWNER = 900u,
RHINO_MUTEX_OWNER_NESTED,
RHINO_MUTEX_NESTED_OVF,
RHINO_NOT_CALLED_BY_INTRPT = 1000u,
RHINO_TRY_AGAIN,
RHINO_WORKQUEUE_EXIST = 1100u,
RHINO_WORKQUEUE_NOT_EXIST,
RHINO_WORKQUEUE_WORK_EXIST,
RHINO_WORKQUEUE_BUSY,
RHINO_WORKQUEUE_WORK_RUNNING,
RHINO_TASK_STACK_OVF = 1200u,
RHINO_INTRPT_STACK_OVF,
RHINO_STATE_ALIGN = INT_MAX /* keep enum 4 bytes at 32bit machine */
} kstat_t;
/**
* Critical error callback.
*
* @param[in] err error code
*
* @return none
*/
typedef void (*krhino_err_proc_t)(kstat_t err);
/**
* Callback register, e.g. 'g_err_proc = app_error_handler();'
*/
extern krhino_err_proc_t g_err_proc;
/**
* Error process entry.
*/
extern void k_err_proc_debug(kstat_t err, char *file, int line);
/**
* Error proc for rhino module.
*/
#define k_err_proc(err) k_err_proc_debug(err, __FILE__, __LINE__)
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_ERR_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_err.h
|
C
|
apache-2.0
| 2,693
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_EVENT_H
#define K_EVENT_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino event
* Event can be used for tasks synchronize.
*
* @{
*/
/**
* event object
*/
typedef struct {
/**<
* Manage blocked tasks
* List head is this event, list node is task, which are blocked in this event
*/
blk_obj_t blk_obj;
uint32_t flags; /**< 32bit mapping 32 synchronization events */
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t event_item; /**< kobj list for statistics */
#endif
uint8_t mm_alloc_flag; /**< buffer from internal malloc or caller input */
} kevent_t;
/**
* event operation bit1 - AND / OR
* AND, Synchronization success only for all flag bits matching
* OR, Synchronization success only for 1 flag bits matching
*/
#define RHINO_FLAGS_AND_MASK 0x2u
/**
* event operation bit0 - clear / not clear
*/
#define RHINO_FLAGS_CLEAR_MASK 0x1u
/**
* event operation, explanation in APIs
*/
#define RHINO_AND 0x02u
#define RHINO_AND_CLEAR 0x03u
#define RHINO_OR 0x00u
#define RHINO_OR_CLEAR 0x01u
/**
* Create a event.
*
* @param[in] event pointer to the event (the space is provided outside, by user)
* @param[in] name name of the event
* @param[in] flags flags to be init
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_create(kevent_t *event, const name_t *name, uint32_t flags);
/**
* Delete a event.
*
* @param[in] event pointer to a event
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_del(kevent_t *event);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Malloc and create a event.
*
* @param[out] event pointer to the event (the space is provided inside, from heap)
* @param[in] name name of the semaphore
* @param[in] flags flags to be init
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_dyn_create(kevent_t **event, const name_t *name, uint32_t flags);
/**
* Delete and free a event.
*
* @param[in] event pointer to a event
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_dyn_del(kevent_t *event);
#endif
/**
* Get event, task may be blocked.
* opt = RHINO_AND: Waiting for 'event->flags' & 'flags' == 'flags', do not clear 'event->flags' after success.
* opt = RHINO_AND_CLEAR: Waiting for 'event->flags' & 'flags' == 'flags', clear 'event->flags' after success.
* opt = RHINO_OR: Waiting for 'event->flags' & 'flags' != 0, do not clear 'event->flags' after success.
* opt = RHINO_OR_CLEAR: Waiting for 'event->flags' & 'flags' != 0, clear 'event->flags' after success.
*
* @param[in] event pointer to the event
* @param[in] flags which is provided by users
* @param[in] opt could be RHINO_AND, RHINO_AND_CLEAR, RHINO_OR, RHINO_OR_CLEAR
* @param[out] actl_flags the actually flag where flags is satisfied
* @param[in] ticks ticks to wait before getting success
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_get(kevent_t *event, uint32_t flags, uint8_t opt,
uint32_t *actl_flags, tick_t ticks);
/**
* Set a event
* opt = RHINO_AND: Clear some bit in 'event->flags', 'event->flags' &= 'flags'.
* opt = RHINO_OR: Set some bit in 'event->flags', 'event->flags' |= 'flags', may invoke other waiting task
*
* @param[in] event pointer to a event
* @param[in] flags which users want to be set
* @param[in] opt could be RHINO_AND, RHINO_OR
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_event_set(kevent_t *event, uint32_t flags, uint8_t opt);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_EVENT_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_event.h
|
C
|
apache-2.0
| 3,950
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_HOOK_H
#define K_HOOK_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino hook
* OS hook, called when specific OS operations
*
* @{
*/
#if (RHINO_CONFIG_USER_HOOK > 0)
/**
* Called in 'krhino_init' - initialization process
*
* @return none
*/
void krhino_init_hook(void);
/**
* Called in 'krhino_start' - just before the first task runs
*
* @return none
*/
void krhino_start_hook(void);
/**
* Called in 'krhino_task_create' and 'krhino_task_dyn_create'
*
* @param[in] task pointer to the created task
*
* @return none
*/
void krhino_task_create_hook(ktask_t *task);
/**
* Called in 'krhino_task_del_hook' and 'krhino_task_dyn_del'
*
* @param[in] task pointer to the deleted task
* @param[in] arg useless now
*
* @return none
*/
void krhino_task_del_hook(ktask_t *task, res_free_t *arg);
/**
* Called in 'krhino_task_wait_abort' and 'krhino_task_cancel'
*
* @param[in] task pointer to the canceled and abort task
*
* @return none
*/
void krhino_task_abort_hook(ktask_t *task);
/**
* Called when task switching
*
* @param[in] orgin pointer to the switch out task
* @param[in] dest pointer to the switch in task
*
* @return none
*/
void krhino_task_switch_hook(ktask_t *orgin, ktask_t *dest);
/**
* Called in every system tick process
*
* @return none
*/
void krhino_tick_hook(void);
/**
* Called in idle task loop
*
* @return none
*/
void krhino_idle_hook(void);
/**
* Called before idle task loop
*
* @return none
*/
void krhino_idle_pre_hook(void);
/**
* Called in 'krhino_mm_alloc'
*
* @param[in] mem alloced memory block
* @param[in] size alloced size
*
* @return none
*/
void krhino_mm_alloc_hook(void *mem, size_t size);
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_HOOK_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_hook.h
|
C
|
apache-2.0
| 1,883
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_INTERNAL_H
#define K_INTERNAL_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino internal
* OS internal funtions
*
* @{
*/
extern kstat_t g_sys_stat;
extern uint8_t g_idle_task_spawned[RHINO_CONFIG_CPU_NUM];
extern runqueue_t g_ready_queue;
/* System lock */
extern uint8_t g_sched_lock[RHINO_CONFIG_CPU_NUM];
extern uint8_t g_intrpt_nested_level[RHINO_CONFIG_CPU_NUM];
/* highest pri ready task object */
extern ktask_t *g_preferred_ready_task[RHINO_CONFIG_CPU_NUM];
/* current active task */
extern ktask_t *g_active_task[RHINO_CONFIG_CPU_NUM];
/* global task ID */
extern uint32_t g_task_id;
/* idle attribute */
extern ktask_t g_idle_task[RHINO_CONFIG_CPU_NUM];
extern idle_count_t g_idle_count[RHINO_CONFIG_CPU_NUM];
extern cpu_stack_t g_idle_task_stack[RHINO_CONFIG_CPU_NUM][RHINO_CONFIG_IDLE_TASK_STACK_SIZE];
extern per_cpu_t g_per_cpu[RHINO_CONFIG_CPU_NUM];
/* tick attribute */
extern tick_t g_tick_count;
extern klist_t g_tick_head;
#if (RHINO_CONFIG_KOBJ_LIST > 0)
extern kobj_list_t g_kobj_list;
#endif
#if (RHINO_CONFIG_TIMER > 0)
extern klist_t g_timer_head;
extern tick_t g_timer_count;
extern ktask_t g_timer_task;
extern cpu_stack_t g_timer_task_stack[RHINO_CONFIG_TIMER_TASK_STACK_SIZE];
extern kbuf_queue_t g_timer_queue;
extern k_timer_queue_cb timer_queue_cb[RHINO_CONFIG_TIMER_MSG_NUM];
#endif
#if (RHINO_CONFIG_SYS_STATS > 0)
extern hr_timer_t g_sched_disable_time_start;
extern hr_timer_t g_sched_disable_max_time;
extern hr_timer_t g_cur_sched_disable_max_time;
extern uint16_t g_intrpt_disable_times;
extern hr_timer_t g_intrpt_disable_time_start;
extern hr_timer_t g_intrpt_disable_max_time;
extern hr_timer_t g_cur_intrpt_disable_max_time;
extern ctx_switch_t g_sys_ctx_switch_times;
#endif
#if (RHINO_CONFIG_HW_COUNT > 0)
extern hr_timer_t g_sys_measure_waste;
#endif
#if (RHINO_CONFIG_CPU_USAGE_STATS > 0)
extern ktask_t g_cpu_usage_task;
extern cpu_stack_t g_cpu_task_stack[RHINO_CONFIG_CPU_USAGE_TASK_STACK];
extern idle_count_t g_idle_count_max;
extern uint32_t g_cpu_usage;
#endif
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
extern ksem_t g_res_sem;
extern klist_t g_res_list;
extern ktask_t g_dyn_task;
extern cpu_stack_t g_dyn_task_stack[RHINO_CONFIG_K_DYN_TASK_STACK];
#endif
#if (RHINO_CONFIG_WORKQUEUE > 0)
extern klist_t g_workqueue_list_head;
extern kmutex_t g_workqueue_mutex;
extern kworkqueue_t g_workqueue_default;
extern cpu_stack_t g_workqueue_stack[RHINO_CONFIG_WORKQUEUE_STACK_SIZE];
#endif
#if (RHINO_CONFIG_MM_TLF > 0)
extern k_mm_head *g_kmm_head;
#endif
#if (RHINO_CONFIG_CPU_NUM > 1)
extern kspinlock_t g_sys_lock;
extern klist_t g_task_del_head;
#endif
#define K_OBJ_STATIC_ALLOC 1u
#define K_OBJ_DYN_ALLOC 2u
#define NULL_PARA_CHK(para) \
do { \
if (para == NULL) { \
return RHINO_NULL_PTR; \
} \
} while (0)
#define INTRPT_NESTED_LEVEL_CHK() \
do { \
if (g_intrpt_nested_level[cpu_cur_get()] > 0u) { \
RHINO_CRITICAL_EXIT(); \
return RHINO_NOT_CALLED_BY_INTRPT; \
} \
} while (0)
RHINO_INLINE uint8_t is_task_exec(ktask_t *task)
{
#if (RHINO_CONFIG_CPU_NUM > 1)
if (task->cur_exc > 0u) {
return RHINO_TRUE;
}
else {
return RHINO_FALSE;
}
#else
if (g_active_task[0] == task) {
return RHINO_TRUE;
}
else {
return RHINO_FALSE;
}
#endif
}
#define RT_MAX_PRI 99u
#define RT_MIN_PRI 0u
#if (RHINO_CONFIG_TASK_DEL > 0)
#define TASK_CANCEL_CHK(obj) \
do { \
if ((g_active_task[cur_cpu_num]->cancel == 1u) && (obj->blk_obj.cancel == 1u)) {\
RHINO_CRITICAL_EXIT(); \
return RHINO_TASK_CANCELED; \
} \
} while (0)
#else
#define TASK_CANCEL_CHK(obj)
#endif
#define RES_FREE_NUM 4
typedef struct
{
size_t cnt;
void *res[RES_FREE_NUM];
klist_t res_list;
} res_free_t;
ktask_t *preferred_cpu_ready_task_get(runqueue_t *rq, uint8_t cpu_num);
ktask_t *cfs_preferred_task_get(void);
void core_sched(void);
void runqueue_init(runqueue_t *rq);
void ready_list_add(runqueue_t *rq, ktask_t *task);
void ready_list_add_head(runqueue_t *rq, ktask_t *task);
void ready_list_add_tail(runqueue_t *rq, ktask_t *task);
void ready_list_rm(runqueue_t *rq, ktask_t *task);
void ready_list_head_to_tail(runqueue_t *rq, ktask_t *task);
void time_slice_update(void);
void timer_task_sched(void);
void pend_list_reorder(ktask_t *task);
void pend_task_wakeup(ktask_t *task);
void pend_to_blk_obj(blk_obj_t *blk_obj, ktask_t *task, tick_t timeout);
void pend_task_rm(ktask_t *task);
kstat_t pend_state_end_proc(ktask_t *task, blk_obj_t *blk_obj);
void idle_task(void *p_arg);
void idle_count_set(idle_count_t value);
idle_count_t idle_count_get(void);
void tick_list_init(void);
void tick_task_start(void);
void tick_list_rm(ktask_t *task);
void tick_list_insert(ktask_t *task, tick_t time);
void tick_list_update(tick_i_t ticks);
uint8_t mutex_pri_limit(ktask_t *tcb, uint8_t pri);
void mutex_task_pri_reset(ktask_t *tcb);
uint8_t mutex_pri_look(ktask_t *tcb, kmutex_t *mutex_rel);
kstat_t task_pri_change(ktask_t *task, uint8_t new_pri);
void ktimer_init(void);
void intrpt_disable_measure_start(void);
void intrpt_disable_measure_stop(void);
__attribute__((weak)) void dyn_mem_proc_task_start(void);
void cpu_usage_stats_start(void);
kstat_t ringbuf_init(k_ringbuf_t *p_ringbuf, void *buf, size_t len, size_t type,size_t block_size);
kstat_t ringbuf_reset(k_ringbuf_t *p_ringbuf);
kstat_t ringbuf_push(k_ringbuf_t *p_ringbuf, void *data, size_t len);
kstat_t ringbuf_head_push(k_ringbuf_t *p_ringbuf, void *data, size_t len);
kstat_t ringbuf_pop(k_ringbuf_t *p_ringbuf, void *pdata, size_t *plen);
uint8_t ringbuf_is_full(k_ringbuf_t *p_ringbuf);
uint8_t ringbuf_is_empty(k_ringbuf_t *p_ringbuf);
void workqueue_init(void);
void k_mm_init(void);
#if (RHINO_CONFIG_PWRMGMT > 0)
void cpu_pwr_down(void);
void cpu_pwr_up(void);
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_INTERNAL_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_internal.h
|
C
|
apache-2.0
| 6,603
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_LIST_H
#define K_LIST_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino list
* List operations
*
* @{
*/
/**
* As a member of other structures, 'klist_t' can form a doubly linked list.
*/
typedef struct klist_s {
struct klist_s *next;
struct klist_s *prev;
} klist_t;
/**
* Get the struct for this entry.
*
* @param[in] node the list head to take the element from.
* @param[in] type the type of the struct this is embedded in.
* @param[in] member the name of the klist_t within the struct.
*
* @return the pointer to struct
*/
#define krhino_list_entry(node, type, member) ((type *)((uint8_t *)(node) - (size_t)(&((type *)0)->member)))
/**
* Double linked list initialization: a single Node forms a ring
*
* @param[in] list_head the list_head node to be initialized.
*
* @return none
*/
RHINO_INLINE void klist_init(klist_t *list_head)
{
list_head->next = list_head;
list_head->prev = list_head;
}
/**
* Judge whether 'klist' is empty.
*
* @param[in] list the list node.
*
* @return 1 on empty, 0 FALSE.
*/
RHINO_INLINE uint8_t is_klist_empty(klist_t *list)
{
return (list->next == list);
}
/**
* Double linked list insertion: 'element' before 'head'
* When 'head' is the head of the linked list, insert 'element' in the list end
*
* @param[in] head the specified head node.
* @param[in] element the data node to be inserted.
*
* @return none
*/
RHINO_INLINE void klist_insert(klist_t *head, klist_t *element)
{
element->prev = head->prev;
element->next = head;
head->prev->next = element;
head->prev = element;
}
/**
* Double linked list insertion: 'element' after 'head'
* When 'head' is the head of the linked list, insert 'element' in the list front
*
* @param[in] head the specified head node.
* @param[in] element the data node to be inserted.
*/
RHINO_INLINE void klist_add(klist_t *head, klist_t *element)
{
element->prev = head;
element->next = head->next;
head->next->prev = element;
head->next = element;
}
/**
* Double linked list deletion: 'element' is deleted from the linked list
*
* @param[in] element the list node to be deleted.
*/
RHINO_INLINE void klist_rm(klist_t *element)
{
element->prev->next = element->next;
element->next->prev = element->prev;
}
/**
* Double linked list deletion: 'element' is deleted from the linked list and 'element' is initialized
*
* @param[in] element the list node to be deleted and reinited.
*/
RHINO_INLINE void klist_rm_init(klist_t *element)
{
element->prev->next = element->next;
element->next->prev = element->prev;
element->next = element->prev = element;
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_LIST_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_list.h
|
C
|
apache-2.0
| 2,865
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MM_H
#define K_MM_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino mm
* Heap memory management.
*
* @{
*/
#if (RHINO_CONFIG_MM_TLF > 0)
#define KMM_ERROR_LOCKED 1
#define KMM_ERROR_UNLOCKED 0
#if (RHINO_CONFIG_MM_DEBUG && (RHINO_CONFIG_MM_TRACE_LVL > 0))
#define KMM_BT_SET_BY_KV 1
#endif
/**
* Heap useage size statistic
*/
#define K_MM_STATISTIC 1
/**
* Memory buffer align to MM_ALIGN_SIZE
*/
#define MM_ALIGN_BIT 3
#define MM_ALIGN_SIZE (1 << MM_ALIGN_BIT)
#define MM_ALIGN_MASK (MM_ALIGN_SIZE - 1)
#define MM_ALIGN_UP(a) (((a) + MM_ALIGN_MASK) & ~MM_ALIGN_MASK)
#define MM_ALIGN_DOWN(a) ((a) & ~MM_ALIGN_MASK)
/**
* Max size of memory buffer
*/
#define MM_MAX_BIT RHINO_CONFIG_MM_MAXMSIZEBIT
#define MM_MAX_SIZE (1 << MM_MAX_BIT)
/**
* Min size of memory buffer
*/
#define MM_MIN_BIT RHINO_CONFIG_MM_MINISIZEBIT
#define MM_MIN_SIZE (1 << (MM_MIN_BIT - 1))
/**
* Size level of memory buffer
*/
#define MM_BIT_LEVEL (MM_MAX_BIT - MM_MIN_BIT + 2)
/**
* Min size of memory heap
*/
#define MM_MIN_HEAP_SIZE 1024
/* magic word for check overwrite or corrupt */
#define MM_DYE_USED 0xFEFE
#define MM_DYE_FREE 0xABAB
#define MM_OWNER_ID_SELF 0xFF
#define MM_CURSTAT_MASK 0x1
#define MM_PRESTAT_MASK 0x2
/* bit 0 */
#define MM_BUFF_FREE 1
#define MM_BUFF_USED 0
/* bit 1 */
#define MM_BUFF_PREV_FREE 2
#define MM_BUFF_PREV_USED 0
/**
* Buffer head size
*/
#define MMLIST_HEAD_SIZE (MM_ALIGN_UP(sizeof(k_mm_list_t) - sizeof(free_ptr_t)))
/**
* Buffer payload size
*/
#define MM_GET_BUF_SIZE(blk) ((blk)->buf_size & (~MM_ALIGN_MASK))
/**
* Buffer head + payload size
*/
#define MM_GET_BLK_SIZE(blk) (MM_GET_BUF_SIZE(blk) + MMLIST_HEAD_SIZE)
/**
* Get next buffer head addr
*/
#define MM_GET_NEXT_BLK(blk) ((k_mm_list_t *)((blk)->mbinfo.buffer + MM_GET_BUF_SIZE(blk)))
/**
* Get this buffer head addr
*/
#define MM_GET_THIS_BLK(buf) ((k_mm_list_t *)((char *)(buf)-MMLIST_HEAD_SIZE))
#define MM_LAST_BLK_MAGIC 0x11224433
#if (RHINO_CONFIG_MM_REGION_MUTEX == 0)
/**
* MM critical section strategy:
* Interrupt mask for single core, and busy-waiting spinlock for multi-core
*/
#define MM_CRITICAL_ENTER(pmmhead,flags_cpsr) krhino_spin_lock_irq_save(&(pmmhead->mm_lock),flags_cpsr);
#define MM_CRITICAL_EXIT(pmmhead,flags_cpsr) krhino_spin_unlock_irq_restore(&(pmmhead->mm_lock),flags_cpsr);
#else /* (RHINO_CONFIG_MM_REGION_MUTEX != 0) */
/**
* MM critical section strategy:
* Task blocked
*/
#define MM_CRITICAL_ENTER(pmmhead,flags_cpsr) \
do { \
(void)flags_cpsr; \
CPSR_ALLOC(); \
RHINO_CRITICAL_ENTER(); \
if (g_intrpt_nested_level[cpu_cur_get()] > 0u) { \
k_err_proc(RHINO_NOT_CALLED_BY_INTRPT); \
} \
RHINO_CRITICAL_EXIT(); \
krhino_mutex_lock(&(pmmhead->mm_mutex), RHINO_WAIT_FOREVER); \
} while (0);
#define MM_CRITICAL_EXIT(pmmhead,flags_cpsr) \
do { \
(void)flags_cpsr; \
krhino_mutex_unlock(&(pmmhead->mm_mutex)); \
} while (0);
#endif
/**
* free buffer list
*/
typedef struct free_ptr_struct {
struct k_mm_list_struct *prev;
struct k_mm_list_struct *next;
} free_ptr_t;
/**
* memory buffer head
*/
#define ALIGN_UP_2(a) ((a % 2 == 0) ? a : (a + 1))
typedef struct k_mm_list_struct {
#if (RHINO_CONFIG_MM_DEBUG > 0)
uint16_t dye;
uint8_t owner_id;
uint8_t trace_id;
size_t owner;
#if (RHINO_CONFIG_MM_TRACE_LVL > 0)
void *trace[ALIGN_UP_2(RHINO_CONFIG_MM_TRACE_LVL)];
#endif
#endif
struct k_mm_list_struct *prev;
/**<
* buffer payload size, and:
* bit 0 indicates whether the block is used and
* bit 1 allows to know whether the previous block is free
*/
size_t buf_size;
union {
free_ptr_t free_ptr; /**< when buffer is free, add to free list */
uint8_t buffer[1]; /**< when buffer is alloced, payload start */
} mbinfo;
} k_mm_list_t;
/**
* memory region info
* Heap can contain multiple regoins
*/
typedef struct k_mm_region_info_struct {
k_mm_list_t *end;
struct k_mm_region_info_struct *next;
} k_mm_region_info_t;
/**
* memory heap info
* heap contains:
* ---------------------------------------------------------------------------
* | k_mm_head | k_mm_list_t | k_mm_region_info_t | free space | k_mm_list_t |
* ---------------------------------------------------------------------------
*/
typedef struct {
#if (RHINO_CONFIG_MM_REGION_MUTEX > 0)
kmutex_t mm_mutex;
#else
kspinlock_t mm_lock;
#endif
k_mm_region_info_t *regioninfo; /**< Heap can contain multiple regoins */
#if (RHINO_CONFIG_MM_BLK > 0)
void *fix_pool; /**< heap can contain one fix pool, deal with little buffer */
#endif
#if (K_MM_STATISTIC > 0)
size_t used_size;
size_t maxused_size;
size_t free_size;
size_t alloc_times[MM_BIT_LEVEL]; /* number of times for each TLF level */
#endif
/**< msb (MM_BIT_LEVEL-1) <-> lsb 0, one bit match one freelist */
uint32_t free_bitmap;
/**<
* freelist[N]: contain free blks at level N,
* 2^(N + MM_MIN_BIT) <= level N buffer size < 2^(1 + N + MM_MIN_BIT)
*/
k_mm_list_t *freelist[MM_BIT_LEVEL];
} k_mm_head;
/**
* internal funcs
*/
kstat_t krhino_init_mm_head(k_mm_head **ppmmhead, void *addr, size_t len);
kstat_t krhino_deinit_mm_head(k_mm_head *mmhead);
kstat_t krhino_add_mm_region(k_mm_head *mmhead, void *addr, size_t len);
void *k_mm_alloc(k_mm_head *mmhead, size_t size);
void k_mm_free(k_mm_head *mmhead, void *ptr);
void *k_mm_realloc(k_mm_head *mmhead, void *oldmem, size_t new_size);
/**
* Memory buffer allocation.
*
* @param[in] size size of the mem to malloc
*
* @return buffer address or NULL
*/
void *krhino_mm_alloc(size_t size);
/**
* Memory buffer free.
*
* @param[in] ptr buffer address
*
* @return none
*/
void krhino_mm_free(void *ptr);
/**
* Memory buffer realloc.
*
* @param[in] oldmem oldmem buffer address
* @param[in] newsize size of the mem to malloc
*
* @return buffer address or NULL
*/
void *krhino_mm_realloc(void *oldmem, size_t newsize);
/**
* Get the max free buffer size.
*
* @param[in] NULL
*
* @return the max free buffer size
*/
size_t krhino_mm_max_free_size_get(void);
#else
#include <stdlib.h>
/**
* do not use os heap management
*/
#define krhino_mm_alloc malloc
#define krhino_mm_free free
#define krhino_mm_realloc realloc
#endif /* RHINO_CONFIG_MM_TLF > 0 */
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_MM_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_mm.h
|
C
|
apache-2.0
| 7,341
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MM_BLK_H
#define K_MM_BLK_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino mm
* Pool memory management. Pool memory can be part of heap.
* Pool is used to manage the little fixed-size block
*
* @{
*/
#define MM_BLK_SLICE_BIT 10
#define MM_BLK_SLICE_SIZE (1<<MM_BLK_SLICE_BIT)
#define MM_BLK_SLICE_NUM (RHINO_CONFIG_MM_TLF_BLK_SIZE/MM_BLK_SLICE_SIZE)
#define MM_BLK_SIZE2TYPE(size) (32 - krhino_clz32((uint32_t)(size) - 1))
#define MM_BLK_TYPE2SIZE(type) (1 << (type))
/**
* memory pool info
*/
typedef struct {
size_t blk_size;
uint32_t fail_cnt; /* alloc fail */
uint32_t freelist_cnt;
uint32_t nofree_cnt; /* alloc but not free yet */
uintptr_t slice_cnt;
uintptr_t slice_addr;
size_t slice_offset;
uintptr_t free_head;
} mblk_list_t;
typedef struct {
kspinlock_t blk_lock;
const name_t *pool_name;
uintptr_t pool_start;
uintptr_t pool_end;
uint32_t slice_cnt; /* slice have bean used */
char slice_type[MM_BLK_SLICE_NUM];
mblk_list_t blk_list[MM_BLK_SLICE_BIT];
} mblk_pool_t;
typedef struct {
const name_t *pool_name;
size_t pool_size;
size_t used_size;
size_t max_used_size;
size_t max_blk_size;
} mblk_info_t;
/**
* Init a pool.
*
* @param[in] pool pointer to the pool
* @param[in] name name of the pool
* @param[in] pool_start start addr of the pool
* @param[in] pool_size size of the pool
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mblk_pool_init(mblk_pool_t *pool, const name_t *name,
void *pool_start, size_t pool_size);
/**
* Memory block alloc from the pool.
*
* @param[in] pool pointer to a pool
* @param[in] blk_size need size, and alloced size
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
void *krhino_mblk_alloc(mblk_pool_t *pool, uint32_t size);
void *krhino_mblk_alloc_nolock(mblk_pool_t *pool, uint32_t size);
/**
* Memory block free to the pool.
*
* @param[in] pool pointer to the pool
* @param[in] blk pointer to the blk
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mblk_free(mblk_pool_t *pool, void *blk);
kstat_t krhino_mblk_free_nolock(mblk_pool_t *pool, void *blk);
/**
* This function will get information of the pool
* @param[in] pool pointer to the pool
* @param[out] info info of pool
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mblk_info(mblk_pool_t *pool, mblk_info_t *info);
kstat_t krhino_mblk_info_nolock(mblk_pool_t *pool, mblk_info_t *info);
/**
* Check if this a pool block.
*
* @param[in] pool pointer to the pool
* @param[in] blk pointer to the blk
*
* @return yes return 1, no reture 0
*/
#define krhino_mblk_check(pool, blk) \
((pool) != NULL \
&& ((uintptr_t)(blk) >= ((mblk_pool_t*)(pool))->pool_start) \
&& ((uintptr_t)(blk) < ((mblk_pool_t*)(pool))->pool_end))
/**
* get blk size, should followed by krhino_mblk_check
* @param[in] pool pointer to the pool
* @param[in] blk pointer to the blk
* @return the len of blk
*/
RHINO_INLINE size_t krhino_mblk_get_size(mblk_pool_t *pool, void *blk)
{
uint32_t slice_idx;
uint32_t blk_type;
mblk_list_t *blk_list;
slice_idx = ((uintptr_t)blk - pool->pool_start) >> MM_BLK_SLICE_BIT;
blk_type = pool->slice_type[slice_idx];
blk_list = &(pool->blk_list[blk_type]);
return blk_list->blk_size;
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_MM_BLK_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_mm_blk.h
|
C
|
apache-2.0
| 3,899
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MM_DEBUG_H
#define K_MM_DEBUG_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino mm
* Memory debug includes buffer over flow check, memory usage statistics, etc.
*
* @{
*/
#if (RHINO_CONFIG_MM_DEBUG > 0)
#define AOS_UNSIGNED_INT_MSB (1u << (sizeof(unsigned int) * 8 - 1))
extern uint8_t g_mmlk_cnt;
/**
* Add owner info to the memory buffer.
*
* @param[in] addr pointer to the buffer
* @param[in] allocator address of the allocator
*
* @return NULL
*/
void krhino_owner_attach(void *addr, size_t allocator);
/**
* Set owner to return address of function.
*
*/
#define krhino_owner_return_addr(addr) \
krhino_owner_attach(addr, (size_t)__builtin_return_address(0))
/**
* Show heap information.
*
* @param[in] mm status
*
* @return RHINO_SUCCESS
*/
uint32_t dumpsys_mm_info_func(uint32_t mm_status);
#endif /* RHINO_CONFIG_MM_DEBUG */
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_MM_DEBUG_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_mm_debug.h
|
C
|
apache-2.0
| 1,038
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MM_REGION_H
#define K_MM_REGION_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino mm
*
* @{
*/
/**
* Heap regino parameter, for heap init.
*/
typedef struct {
uint8_t *start;
size_t len;
} k_mm_region_t;
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_MM_REGION_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_mm_region.h
|
C
|
apache-2.0
| 385
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MUTEX_H
#define K_MUTEX_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino mutex
* Mutex can be used for mutual exclusion between tasks.
*
* @{
*/
/**
* mutex object
*/
typedef struct mutex_s {
/**<
* Manage blocked tasks
* List head is this mutex, list node is task, which are blocked in this mutex
*/
blk_obj_t blk_obj;
ktask_t *mutex_task; /**< Pointer to the owner task */
/**<
* Manage mutexs owned by the task
* List head is task, list node is mutex, which are owned by the task
*/
struct mutex_s *mutex_list;
mutex_nested_t owner_nested;
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t mutex_item; /**< kobj list for statistics */
#endif
uint8_t mm_alloc_flag; /**< buffer from internal malloc or caller input */
} kmutex_t;
/**
* Create a mutex.
*
* @param[in] mutex pointer to the mutex (the space is provided outside, by user)
* @param[in] name name of the mutex
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_create(kmutex_t *mutex, const name_t *name);
/**
* Delete a mutex.
*
* @param[in] mutex pointer to the mutex
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_del(kmutex_t *mutex);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Malloc and create a mutex.
*
* @param[out] mutex pointer to the mutex (the space is provided inside, from heap)
* @param[in] name name of the mutex
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_dyn_create(kmutex_t **mutex, const name_t *name);
/**
* Delete and free a mutex.
*
* @param[in] mutex pointer to the mutex
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_dyn_del(kmutex_t *mutex);
#endif
/**
* Lock mutex, task may be blocked.
*
* @param[in] mutex pointer to the mutex
* @param[in] ticks ticks to be wait for before lock
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_lock(kmutex_t *mutex, tick_t ticks);
/**
* Unlock a mutex.
*
* @param[in] mutex pointer to the mutex
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_mutex_unlock(kmutex_t *mutex);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_MUTEX_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_mutex.h
|
C
|
apache-2.0
| 2,523
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_OBJ_H
#define K_OBJ_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino obj
* Internal object information
*
* @{
*/
/**
* Blocking strategy.
* It determines which task can go first when they are waiting for one resource.(from 'pend' to 'ready')
* BLK_POLICY_PRI is default.
*/
typedef enum {
/**
* High-priority tasks are easier to obtain resources, the same priority is in FIFO order.
*/
BLK_POLICY_PRI = 0u,
/**
* Just in FIFO order.
*/
BLK_POLICY_FIFO
} blk_policy_t;
/**
* Reasons for the end of the blocking state
*/
typedef enum {
BLK_FINISH = 0, /**< task blocking successfully */
BLK_ABORT, /**< task blocking is aborted */
BLK_TIMEOUT, /**< task blocking timeout */
BLK_DEL, /**< task blocking for a deleted 'obj' */
BLK_INVALID
} blk_state_t;
/**
* The objects types
*/
typedef enum {
RHINO_OBJ_TYPE_NONE = 0,
RHINO_SEM_OBJ_TYPE,
RHINO_MUTEX_OBJ_TYPE,
RHINO_QUEUE_OBJ_TYPE,
RHINO_BUF_QUEUE_OBJ_TYPE,
RHINO_TIMER_OBJ_TYPE,
RHINO_EVENT_OBJ_TYPE,
RHINO_MM_OBJ_TYPE
} kobj_type_t;
/**
* Abstract model of the 'obj':
* 'obj' is an abstraction of all types of objects that can cause task blocking
* (that is, tasks waiting for the resource to enter the PEND state).
*/
typedef struct blk_obj {
klist_t blk_list; /**< Manage blocked tasks */
const name_t *name;
blk_policy_t blk_policy;
kobj_type_t obj_type;
#if (RHINO_CONFIG_USER_SPACE > 0)
klist_t obj_list;
#endif
#if (RHINO_CONFIG_TASK_DEL > 0)
uint8_t cancel;
#endif
} blk_obj_t;
/**
* Records multiple types of objects created by the OS, each type forming a linked list
*/
typedef struct {
klist_t task_head;
klist_t mutex_head;
#if (RHINO_CONFIG_SEM > 0)
klist_t sem_head;
#endif
#if (RHINO_CONFIG_QUEUE > 0)
klist_t queue_head;
#endif
#if (RHINO_CONFIG_EVENT_FLAG > 0)
klist_t event_head;
#endif
#if (RHINO_CONFIG_BUF_QUEUE > 0)
klist_t buf_queue_head;
#endif
} kobj_list_t;
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_OBJ_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_obj.h
|
C
|
apache-2.0
| 2,195
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_QUEUE_H
#define K_QUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino queue
* Queue can be used for synchronous communication between tasks.
*
* @{
*/
#define WAKE_ONE_TASK 0u
#define WAKE_ALL_TASK 1u
/**
* queue statistcs
*/
typedef struct {
void **queue_start;
size_t size;
size_t cur_num;
size_t peak_num;
} msg_q_t;
/**
* queue information
*/
typedef struct {
msg_q_t msg_q;
klist_t *pend_entry; /**< first pending task which is waiting for msg */
} msg_info_t;
/**
* mutex object
*/
typedef struct queue_s {
blk_obj_t blk_obj; /**< Manage blocked tasks */
k_ringbuf_t ringbuf; /**< Msg passing by ringbuf */
msg_q_t msg_q;
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t queue_item; /**< kobj list for statistics */
#endif
uint8_t mm_alloc_flag; /**< buffer from internal malloc or caller input */
} kqueue_t;
/**
* Create a queue.
*
* @param[in] queue pointer to the queue (the space is provided outside, by user)
* @param[in] name name of the queue
* @param[in] start start address of the queue internal space
* @param[in] msg_num num of the msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_create(kqueue_t *queue, const name_t *name, void **start, size_t msg_num);
/**
* Delete a queue.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_del(kqueue_t *queue);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Malloc and create a queue.
*
* @param[out] queue pointer to the queue (the space is provided inside, from heap)
* @param[in] name name of the queue
* @param[in] msg_num num of the msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_dyn_create(kqueue_t **queue, const name_t *name, size_t msg_num);
/**
* Delete and free a queue.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_dyn_del(kqueue_t *queue);
#endif
/**
* Send a message to the tail of a queue.
*
* @param[in] queue pointer to the queue
* @param[in] msg msg to send
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_back_send(kqueue_t *queue, void *msg);
/**
* Send a message to the tail of a queue and wake all pending tasks.
*
* @param[in] queue pointer to the queue
* @param[in] msg msg to send
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_all_send(kqueue_t *queue, void *msg);
/**
* Receive message from a queue, task may be blocked.
*
* @param[in] queue pointer to the queue
* @param[in] ticks ticks to wait before receive
* @param[out] msg buf to save msg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_recv(kqueue_t *queue, tick_t ticks, void **msg);
/**
* Check a queue full or not.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_QUEUE_FULL/RHINO_QUEUE_NOT_FULL
*/
kstat_t krhino_queue_is_full(kqueue_t *queue);
/**
* Reset a queue and discard all unreceived messages.
*
* @param[in] queue pointer to the queue
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_flush(kqueue_t *queue);
/**
* Get information of a queue.
*
* @param[in] queue pointer to the queue
* @param[out] info buf to save msg-info
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_queue_info_get(kqueue_t *queue, msg_info_t *info);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_QUEUE_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_queue.h
|
C
|
apache-2.0
| 3,931
|
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#ifndef _K_RBTREE_H
#define _K_RBTREE_H
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <limits.h>
struct k_rbtree_node_t {
unsigned long rbt_parent_color;
struct k_rbtree_node_t *rbt_right;
struct k_rbtree_node_t *rbt_left;
} __attribute__((aligned(sizeof(long))));
struct k_rbtree_root_t {
struct k_rbtree_node_t *rbt_node;
};
struct k_rbtree_augment_callbacks {
void (*propagate)(struct k_rbtree_node_t *node, struct k_rbtree_node_t *stop);
void (*copy)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new_node);
void (*rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new_node);
};
#define K_RBTREE_RED 0
#define K_RBTREE_BLACK 1
#define RBT_ROOT (struct k_rbtree_root_t) { NULL, }
#define __rbtree_parent(pcolor) ((struct k_rbtree_node_t *)(pcolor & ~3))
#define __rbtree_color(pcolor) ((pcolor) & 1)
#define __rbtree_is_black(pcolor) __rbtree_color(pcolor)
#define __rbtree_is_red(pcolor) (!__rbtree_color(pcolor))
#define K_RBTREE_PARENT(rbt) ((struct k_rbtree_node_t *)((rbt)->rbt_parent_color & ~3))
#define K_RBTREE_COLOR(rbt) __rbtree_color((rbt)->rbt_parent_color)
#define K_RBTREE_IS_BLACK(rbt) __rbtree_is_black((rbt)->rbt_parent_color)
#define K_RBTREE_IS_RED(rbt) __rbtree_is_red((rbt)->rbt_parent_color)
#define K_RBTREE_EMPTY_ROOT(root) ((root)->rbt_node == NULL)
#define K_RBTREE_EMPTY_NODE(node) \
((node)->rbt_parent_color == (unsigned long)(node))
#define K_RBTREE_CLEAR_NODE(node) \
((node)->rbt_parent_color = (unsigned long)(node))
#define k_rbtree_entry(ptr, type, member) ((type *)((uint8_t *)(ptr) - (size_t)(&((type *)0)->member)))
#define k_rbtree_entry_safe(ptr, type, member) \
({ ptr ? k_rbtree_entry(ptr, type, member) : NULL; })
#define k_rbtree_postorder_for_each_entry_safe(pos, n, root, field) \
for (pos = k_rbtree_entry_safe(k_rbtree_first_postorder(root), typeof(*pos), field); \
pos && ({ n = k_rbtree_entry_safe(k_rbtree_next_postorder(&pos->field), \
typeof(*pos), field); 1; }); \
pos = n)
extern void rbtree_insert_augmented(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root,
void (*augment_rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new_node));
extern void rbtree_erase_color(struct k_rbtree_node_t *parent, struct k_rbtree_root_t *root,
void (*augment_rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new_node));
static inline void rbtree_set_parent(struct k_rbtree_node_t *rbt, struct k_rbtree_node_t *p)
{
rbt->rbt_parent_color = K_RBTREE_COLOR(rbt) | (unsigned long)p;
}
static inline void rbtree_set_parent_color(struct k_rbtree_node_t *rbt,
struct k_rbtree_node_t *p, int color)
{
rbt->rbt_parent_color = (unsigned long)p | color;
}
static inline void rbtree_change_child(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new_node,
struct k_rbtree_node_t *parent, struct k_rbtree_root_t *root)
{
if (parent) {
if (parent->rbt_left == old)
parent->rbt_left = new_node;
else
parent->rbt_right = new_node;
} else
root->rbt_node = new_node;
}
static inline struct k_rbtree_node_t *rbtree_erase_augmented(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root,
const struct k_rbtree_augment_callbacks *augment)
{
struct k_rbtree_node_t *child = node->rbt_right, *tmp = node->rbt_left;
struct k_rbtree_node_t *parent, *rebalance;
unsigned long pc;
if (!tmp) {
pc = node->rbt_parent_color;
parent = __rbtree_parent(pc);
rbtree_change_child(node, child, parent, root);
if (child) {
child->rbt_parent_color = pc;
rebalance = NULL;
} else
rebalance = __rbtree_is_black(pc) ? parent : NULL;
tmp = parent;
} else if (!child) {
tmp->rbt_parent_color = pc = node->rbt_parent_color;
parent = __rbtree_parent(pc);
rbtree_change_child(node, tmp, parent, root);
rebalance = NULL;
tmp = parent;
} else {
struct k_rbtree_node_t *successor = child, *child2;
tmp = child->rbt_left;
if (!tmp) {
parent = successor;
child2 = successor->rbt_right;
augment->copy(node, successor);
} else {
do {
parent = successor;
successor = tmp;
tmp = tmp->rbt_left;
} while (tmp);
parent->rbt_left = child2 = successor->rbt_right;
successor->rbt_right = child;
rbtree_set_parent(child, successor);
augment->copy(node, successor);
augment->propagate(parent, successor);
}
successor->rbt_left = tmp = node->rbt_left;
rbtree_set_parent(tmp, successor);
pc = node->rbt_parent_color;
tmp = __rbtree_parent(pc);
rbtree_change_child(node, successor, tmp, root);
if (child2) {
successor->rbt_parent_color = pc;
rbtree_set_parent_color(child2, parent, K_RBTREE_BLACK);
rebalance = NULL;
} else {
unsigned long pc2 = successor->rbt_parent_color;
successor->rbt_parent_color = pc;
rebalance = __rbtree_is_black(pc2) ? parent : NULL;
}
tmp = successor;
}
augment->propagate(tmp, NULL);
return rebalance;
}
static inline void k_rbtree_erase_augmented(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root,
const struct k_rbtree_augment_callbacks *augment)
{
struct k_rbtree_node_t *rebalance = rbtree_erase_augmented(node, root, augment);
if (rebalance){
rbtree_erase_color(rebalance, root, augment->rotate);
}
}
static inline void k_rbtree_insert_augmented(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root,
const struct k_rbtree_augment_callbacks *augment)
{
rbtree_insert_augmented(node, root, augment->rotate);
}
static inline void k_rbtree_link_node(struct k_rbtree_node_t * node, struct k_rbtree_node_t * parent,
struct k_rbtree_node_t ** rbt_link)
{
node->rbt_parent_color = (unsigned long)parent;
node->rbt_left = node->rbt_right = NULL;
*rbt_link = node;
}
extern void k_rbtree_insert_color(struct k_rbtree_node_t *, struct k_rbtree_root_t *);
extern void k_rbtree_erase(struct k_rbtree_node_t *, struct k_rbtree_root_t *);
extern struct k_rbtree_node_t *k_rbtree_next(const struct k_rbtree_node_t *);
extern struct k_rbtree_node_t *k_rbtree_prev(const struct k_rbtree_node_t *);
extern struct k_rbtree_node_t *k_rbtree_first(const struct k_rbtree_root_t *);
extern struct k_rbtree_node_t *k_rbtree_last(const struct k_rbtree_root_t *);
extern struct k_rbtree_node_t *k_rbtree_first_postorder(const struct k_rbtree_root_t *);
extern struct k_rbtree_node_t *k_rbtree_next_postorder(const struct k_rbtree_node_t *);
extern void k_rbtree_replace_node(struct k_rbtree_node_t *victim, struct k_rbtree_node_t *new_node, struct k_rbtree_root_t *root);
#endif /* _K_RBTREE_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_rbtree.h
|
C
|
apache-2.0
| 7,216
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_MM_RINGBUF_H
#define K_MM_RINGBUF_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino ringbuf
* Ringbuf is a FIFO communication mechanism.
*
* @{
*/
/**
* The msg size of each push and pop operation is fixed, and it is determined at initialization
*/
#define RINGBUF_TYPE_FIX 0
/**
* The msg size of each push and pop operation is not fixed
*/
#define RINGBUF_TYPE_DYN 1
/**
* ringbuf object
*/
typedef struct {
uint8_t *buf;
uint8_t *end;
uint8_t *head;
uint8_t *tail;
size_t freesize;
size_t type; /**< RINGBUF_TYPE_FIX or RINGBUF_TYPE_DYN */
size_t blk_size;
} k_ringbuf_t;
/**
* Push a msg to the ring.
*
* @param[in] p_ringbuf pointer to the ringbuf
* @param[in] data data address
* @param[in] len data length
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
RHINO_INLINE kstat_t ringbuf_queue_push(k_ringbuf_t *p_ringbuf, void *data, size_t len)
{
if (p_ringbuf->tail == p_ringbuf->end) {
p_ringbuf->tail = p_ringbuf->buf;
}
memcpy(p_ringbuf->tail, data, p_ringbuf->blk_size);
p_ringbuf->tail += p_ringbuf->blk_size;
return RHINO_SUCCESS;
}
/**
* Pop a msg from the ring.
*
* @param[in] p_ringbuf pointer to the ringbuf
* @param[in] pdata data address
* @param[out] plen data length
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
RHINO_INLINE kstat_t ringbuf_queue_pop(k_ringbuf_t *p_ringbuf, void *pdata, size_t *plen)
{
if (p_ringbuf->head == p_ringbuf->end) {
p_ringbuf->head = p_ringbuf->buf;
}
memcpy(pdata, p_ringbuf->head, p_ringbuf->blk_size);
p_ringbuf->head += p_ringbuf->blk_size;
if (plen != NULL) {
*plen = p_ringbuf->blk_size;
}
return RHINO_SUCCESS;
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_RINGBUF_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_ringbuf.h
|
C
|
apache-2.0
| 1,951
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_SCHED_H
#define K_SCHED_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino sched
* Task schedule.
*
* @{
*/
#define KSCHED_FIFO 0u
#define KSCHED_RR 1u
#define KSCHED_CFS 2u
#define SCHED_MAX_LOCK_COUNT 200u
#define NUM_WORDS ((RHINO_CONFIG_PRI_MAX + 31) / 32)
/**
* Ready tasks information
* 'cur_list_item' as task ready list per priority.
* When a task enters 'ready' from another state, it is put into the list;
* When a task leaves 'ready' to another state, it is get out of the list;
* The 'task_bit_map' is used to improve performance.
* The Nth bit in the bitmap starting from msb corresponds to the priority N-1.
*/
typedef struct {
klist_t *cur_list_item[RHINO_CONFIG_PRI_MAX];
uint32_t task_bit_map[NUM_WORDS];
uint8_t highest_pri;
} runqueue_t;
typedef struct {
/* to add */
uint8_t dis_sched;
} per_cpu_t;
/**
* Disable task schedule
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sched_disable(void);
/**
* Enable task schedule
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sched_enable(void);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_SCHED_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_sched.h
|
C
|
apache-2.0
| 1,344
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_SEM_H
#define K_SEM_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino sem
* Semaphore can be used for mutual exclusion between tasks, or tasks synchronize.
*
* @{
*/
#define WAKE_ONE_SEM 0u
#define WAKE_ALL_SEM 1u
/**
* Semaphore object
*/
typedef struct sem_s {
/**<
* Manage blocked tasks
* List head is this semaphore, list node is task, which are blocked in this semaphore
*/
blk_obj_t blk_obj;
sem_count_t count;
sem_count_t peak_count;
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_t sem_item; /**< kobj list for statistics */
#endif
uint8_t mm_alloc_flag; /**< buffer from internal malloc or caller input */
} ksem_t;
/**
* Create a semaphore.
*
* @param[in] sem pointer to the semaphore (the space is provided outside, by user)
* @param[in] name name of the semaphore
* @param[in] count the init count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_create(ksem_t *sem, const name_t *name, sem_count_t count);
/**
* Delete a semaphore.
*
* @param[in] sem pointer to the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_del(ksem_t *sem);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Create and malloc a semaphore.
*
* @param[out] sem pointer to the semaphore (the space is provided inside, from heap)
* @param[in] name name of the semaphore
* @param[in] count the init count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_dyn_create(ksem_t **sem, const name_t *name, sem_count_t count);
/**
* Delete and free a semaphore.
*
* @param[in] sem pointer to the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_dyn_del(ksem_t *sem);
#endif
/**
* Give a semaphore.
*
* @param[in] sem pointer to the semphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_give(ksem_t *sem);
/**
* Give a semaphore and wakeup all pending task.
*
* @param[in] sem pointer to the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_give_all(ksem_t *sem);
/**
* Take a semaphore, task may be blocked.
*
* @param[in] sem pointer to the semaphore
* @param[in] ticks ticks to wait before take
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_take(ksem_t *sem, tick_t ticks);
/**
* Set the count of a semaphore.
*
* @param[in] sem pointer to the semaphore
* @param[in] sem_count count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_count_set(ksem_t *sem, sem_count_t count);
/**
* Get count of a semaphore.
*
* @param[in] sem pointer to the semaphore
* @param[out] count count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sem_count_get(ksem_t *sem, sem_count_t *count);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_SEM_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_sem.h
|
C
|
apache-2.0
| 3,308
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_SOC_H
#define K_SOC_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino soc
* SOC hardware functions.
*
* @{
*/
#if (RHINO_CONFIG_HW_COUNT > 0)
/**
* Hardware timer init.
*
* @param[in] NULL
*
* @return NULL
*/
void soc_hw_timer_init(void);
/**
* Get the high resolution hardware timer.
*
* @param[in] NULL
*
* @return NULL
*/
hr_timer_t soc_hr_hw_cnt_get(void);
/**
* Get the high resolution hardware clock's frequency
*
* @param[in] NULL
*
* @return
*/
uint64_t soc_hr_hw_freq_get(void);
/**
* Get the low resolution hardware timer.
*
* @param[in] NULL
*
* @return NULL
*/
lr_timer_t soc_lr_hw_cnt_get(void);
#define HR_COUNT_GET() soc_hr_hw_cnt_get()
#define HR_FREQ_GET() soc_hr_hw_freq_get()
#define LR_COUNT_GET() soc_lr_hw_cnt_get()
#else
#define HR_COUNT_GET() ((hr_timer_t)0u)
#define HR_FREQ_GET() ((hr_timer_t)0u)
#define LR_COUNT_GET() ((lr_timer_t)0u)
#endif /* RHINO_CONFIG_HW_COUNT */
void soc_err_proc(kstat_t err);
size_t soc_get_cur_sp(void);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_SOC_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_soc.h
|
C
|
apache-2.0
| 1,167
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_SPIN_LOCK_H
#define K_SPIN_LOCK_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino spinlock
* Spinlock can be used for mutual exclusion between multi-cores.
*
* @{
*/
/**
* spinlock object
*/
typedef struct {
volatile uint32_t owner; /* cpu index of owner */
} kspinlock_t;
/* Be careful nested spin lock is not supported */
#if (RHINO_CONFIG_CPU_NUM > 1)
/**
* Waiting for all cores.
* Can only be used once for multi-core synchronization after initialization.
*
* @param[in] NULL
*
* @return NULL
*/
extern void k_wait_allcores(void);
#define KRHINO_SPINLOCK_FREE_VAL 0xB33FFFFFu
/**
* Lock a spinlock, recursive locking is allowed.
*
* @param[in] lock the spinlock
*
* @return NULL
*/
#define krhino_spin_lock(lock) do { \
cpu_spin_lock((lock)); \
} while (0) \
/**
* Unlock a spinlock, recursive locking is allowed.
*
* @param[in] lock the spinlock
*
* @return NULL
*/
#define krhino_spin_unlock(lock) do { \
cpu_spin_unlock((lock)); \
} while (0)
/**
* Lock a spinlock and mask interrupt, recursive locking is allowed.
*
* @param[in] lock the spinlock
* @param[out] flags the irq status before locking
*
* @return NULL
*/
#define krhino_spin_lock_irq_save(lock, flags) do { \
flags = cpu_intrpt_save(); \
cpu_spin_lock((lock)); \
} while (0)
/**
* Unlock a spinlock and restore interrupt masking status, recursive locking is allowed.
*
* @param[in] lock the spinlock
* @param[in] flags the irq status before locking
*
* @return NULL
*/
#define krhino_spin_unlock_irq_restore(lock, flags) do { \
cpu_spin_unlock((lock)); \
cpu_intrpt_restore(flags); \
} while (0)
/**
* Init a spinlock.
*
* @param[in] lock the spinlock
*
* @return NULL
*/
#define krhino_spin_lock_init(lock) do { \
kspinlock_t *s = (kspinlock_t *)(lock); \
s->owner = KRHINO_SPINLOCK_FREE_VAL; \
} while(0)
#else
/* single-core spinlock */
#define krhino_spin_lock(lock) krhino_sched_disable();
#define krhino_spin_unlock(lock) krhino_sched_enable();
#define krhino_spin_lock_irq_save(lock, flags) do { \
(void)lock; \
flags = cpu_intrpt_save(); \
} while (0)
#define krhino_spin_unlock_irq_restore(lock, flags) do { \
(void)lock; \
cpu_intrpt_restore(flags); \
} while (0)
#define krhino_spin_lock_init(lock)
#endif /* RHINO_CONFIG_CPU_NUM > 1 */
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_SPIN_LOCK_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_spin_lock.h
|
C
|
apache-2.0
| 4,326
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_STATS_H
#define K_STATS_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino stats
* OS statistic
*
* @{
*/
#if (RHINO_CONFIG_KOBJ_LIST > 0)
/**
* Init statistic list.
*
* @param[in] NULL
*
* @return NULL
*/
void kobj_list_init(void);
#endif
#if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0)
/**
* Check task stack overflow.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_stack_ovf_check(void);
#endif
#if (RHINO_CONFIG_SYS_STATS > 0)
/**
* Reset task schedule statistic data.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_task_sched_stats_reset(void);
/**
* Record task schedule statistic data.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_task_sched_stats_get(void);
#endif
#if (RHINO_CONFIG_HW_COUNT > 0)
/**
* Record measurement overhead.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_overhead_measure(void);
#endif
#if (RHINO_CONFIG_CPU_USAGE_STATS > 0)
uint32_t krhino_get_cpu_usage(void);
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_STATS_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_stats.h
|
C
|
apache-2.0
| 1,129
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_SYS_H
#define K_SYS_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino sys
* OS system functions
*
* @{
*/
#define RHINO_VERSION 12000
#define RHINO_IDLE_PRI (RHINO_CONFIG_PRI_MAX - 1)
#define RHINO_NO_WAIT 0u
#define RHINO_WAIT_FOREVER ((tick_t)-1)
#define RHINO_MAX_TICKS ((tick_t)-1 >> 1)
typedef enum
{
RHINO_FALSE = 0u,
RHINO_TRUE = 1u
} RHINO_BOOL;
typedef char name_t;
typedef uint8_t suspend_nested_t;
typedef uint32_t sem_count_t;
typedef uint32_t mutex_nested_t;
typedef uint64_t sys_time_t;
typedef uint64_t tick_t;
typedef int64_t tick_i_t;
typedef uint64_t idle_count_t;
typedef uint64_t ctx_switch_t;
#if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0)
#if (RHINO_CONFIG_CPU_STACK_DOWN > 0)
extern cpu_stack_t *g_intrpt_stack_bottom;
#else
extern cpu_stack_t *g_intrpt_stack_top;
#endif
#endif /* RHINO_CONFIG_INTRPT_STACK_OVF_CHECK */
/**
* Init krhino.
*
* @param[in] NULL
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*
*/
kstat_t krhino_init(void);
/**
* Start krhino.
*
* @param[in] NULL
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_start(void);
/**
* Interrupt handler starts, called when enter interrupt.
*
* @param[in] NULL
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_intrpt_enter(void);
/**
* Interrupt handler ends, called when exit interrupt.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_intrpt_exit(void);
/**
* Check system stack (used by interrupt) overflow.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_intrpt_stack_ovf_check(void);
/**
* Get the number of ticks before next os tick event.
*
* @param[in] NULL
*
* @return RHINO_WAIT_FOREVER or the number of ticks
*/
tick_t krhino_next_sleep_ticks_get(void);
/**
* Get the whole ram space used by krhino global variable.
*
* @param[in] NULL
*
* @return the whole ram space used by kernel
*/
size_t krhino_global_space_get(void);
/**
* Get kernel version.
*
* @param[in] NULL
*
* @return the kernel version
*/
uint32_t krhino_version_get(void);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_SYS_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_sys.h
|
C
|
apache-2.0
| 2,318
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_TASK_H
#define K_TASK_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino task
* Task management
*
* @{
*/
/**
* Task status
*/
typedef enum {
K_SEED,
K_RDY, /**< READY, task in ready list (g_ready_queue) */
K_PEND, /**< PEND, task in tick list (g_tick_head) and block list (sem/mutex/queue/...) */
K_SUSPENDED,
K_PEND_SUSPENDED,
K_SLEEP, /**< SLEEP, task tick list (g_tick_head) */
K_SLEEP_SUSPENDED,
K_DELETED,
} task_stat_t;
typedef void (*task_entry_t)(void *arg);
/**
* Task control information
*/
typedef struct {
/**<
* Task SP, update when task switching.
* Access by assemble code, so do not change position.
*/
void *task_stack;
/**< access by activation, so do not change position */
const name_t *task_name;
#if (RHINO_CONFIG_TASK_INFO > 0)
/**< access by assemble code, so do not change position */
void *user_info[RHINO_CONFIG_TASK_INFO_NUM];
#endif
#if (RHINO_CONFIG_USER_SPACE > 0)
void *task_ustack;
uint32_t ustack_size;
uint32_t pid;
uint8_t mode;
uint8_t is_proc;
cpu_stack_t *task_ustack_base;
klist_t task_user;
void *task_group;
#endif
/**<
* Task stack info
* start 'task_stack_base', len 'stack_size * sizeof(cpu_stack_t)'
*/
cpu_stack_t *task_stack_base;
size_t stack_size;
/**<
* Put task into different linked lists according to the status:
* 1. ready queue. The list hade is g_ready_queue->cur_list_item[prio]
* 2. The pending queue. The list hade is blk_obj in the blocking object (sem / mutex / queue, etc.).
* The final blocking result is recorded in blk_state
*/
klist_t task_list;
/**< Count of entering the K_SUSPENDED state */
suspend_nested_t suspend_count;
/**< Mutex owned by this task */
struct mutex_s *mutex_list;
#if (RHINO_CONFIG_KOBJ_LIST > 0)
/**< Link all task for statistics */
klist_t task_stats_item;
#endif
/**< Put task into the timeout list of the tick, list head is 'g_tick_head' */
klist_t tick_list;
/**< When 'g_tick_count' reaches tick_match, task's PEND or SLEEP state expires. */
tick_t tick_match;
/**< Countdown of the PEND state */
tick_t tick_remain;
/**< Passing massage, for 'queue' and 'buf_queue' */
void *msg;
#if (RHINO_CONFIG_BUF_QUEUE > 0)
/**< Record the msg length, for 'buf_queue'. */
size_t bq_msg_size;
#endif
/**< */
/**< Task status */
task_stat_t task_state;
/**< Reasons for the end of the blocking state */
blk_state_t blk_state;
/* Task block on mutex, queue, semphore, event */
blk_obj_t *blk_obj;
uint32_t task_id;
#if (RHINO_CONFIG_MM_DEBUG > 0)
uint32_t task_alloc_size;
#endif
#if (RHINO_CONFIG_TASK_SEM > 0)
/**< Task semaphore */
struct sem_s *task_sem_obj;
#endif
#if (RHINO_CONFIG_SYS_STATS > 0)
size_t task_free_stack_size;
ctx_switch_t task_ctx_switch_times;
uint64_t task_time_total_run;
uint64_t task_time_total_run_prev;
lr_timer_t task_time_this_run;
lr_timer_t task_exec_time;
lr_timer_t task_time_start;
hr_timer_t task_intrpt_disable_time_max;
hr_timer_t task_sched_disable_time_max;
#endif
#if (RHINO_CONFIG_SCHED_RR > 0)
/**< During this round of scheduling, tasks can execute 'time_slice' ticks */
uint32_t time_slice;
/**< Once RR scheduling, tasks can execute a total of 'time_total' ticks */
uint32_t time_total;
#endif
#if (RHINO_CONFIG_EVENT_FLAG > 0)
uint32_t pend_flags;
void *pend_info;
uint8_t pend_option;
#endif
/**< KSCHED_FIFO / KSCHED_RR / KSCHED_CFS */
uint8_t sched_policy;
#if (RHINO_CONFIG_SCHED_CFS > 0)
cfs_node node;
#endif
/**< On which CPU the task runs */
uint8_t cpu_num;
#if (RHINO_CONFIG_CPU_NUM > 1)
/**< Whether the task is binded to the cpu, 0 no, 1 yes */
uint8_t cpu_binded;
/**< Whether the task is ready to execute, 0 no, 1 yes */
uint8_t cur_exc;
klist_t task_del_item;
#endif
#if (RHINO_CONFIG_TASK_DEL > 0)
uint8_t cancel;
#endif
/**< current prio */
uint8_t prio;
/**< base prio */
uint8_t b_prio;
/**< buffer from internal malloc or caller input */
uint8_t mm_alloc_flag;
void *ptcb; /* pthread control block */
#if (RHINO_CONFIG_NEWLIBC_REENT > 0)
struct _reent *newlibc_reent; /* newlib libc reentrancy */
#endif
} ktask_t;
/**
* Create a task and provide the stack space.
*
* @param[in] task the task to be created (the space is provided outside, by user)
* @param[in] name the name of task, which shall be unique
* @param[in] arg the parameter of task enter function
* @param[in] pri the priority of task
* @param[in] ticks the time slice
* @param[in] stack_buf the start address of task stack
* @param[in] stack_size task stack size = stack_size * sizeof(cpu_stack_t)
* @param[in] entry the entry function of task
* @param[in] autorun the autorunning flag of task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_create(ktask_t *task, const name_t *name, void *arg,
uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf,
size_t stack_size, task_entry_t entry, uint8_t autorun);
kstat_t krhino_cfs_task_create(ktask_t *task, const name_t *name, void *arg,
uint8_t prio, cpu_stack_t *stack_buf, size_t stack_size,
task_entry_t entry, uint8_t autorun);
#if (RHINO_CONFIG_CPU_NUM > 1)
/**
* Create a task and provide the stack space, bind the task to specific cpu.
*
* @param[in] task the task to be created (the space is provided outside, by user)
* @param[in] name the name of task, which shall be unique
* @param[in] arg the parameter of task enter function
* @param[in] pri the priority of task
* @param[in] ticks the time slice
* @param[in] stack_buf the start address of task stack
* @param[in] stack_size task stack size = stack_size * sizeof(cpu_stack_t)
* @param[in] entry the entry function of task
* @param[in] cpu_num the cpu that task bind to
* @param[in] autorun the autorunning flag of task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_cpu_create(ktask_t *task, const name_t *name, void *arg,
uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf,
size_t stack_size, task_entry_t entry, uint8_t cpu_num,
uint8_t autorun);
kstat_t krhino_cfs_task_cpu_create(ktask_t *task, const name_t *name, void *arg,
uint8_t prio, cpu_stack_t *stack_buf, size_t stack_size,
task_entry_t entry, uint8_t cpu_num, uint8_t autorun);
/**
* Bind a task to specific cpu.
*
* @param[in] task the task to be binded
* @param[in] cpu_num the cpu that task bind to
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_cpu_bind(ktask_t *task, uint8_t cpu_num);
/**
* Unbind a task.
*
* @param[in] task the task to be binded
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_cpu_unbind(ktask_t *task);
#endif
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Create a task and malloc the stack space.
*
* @param[out] task the task to be created (the space is provided inside, from heap)
* @param[in] name the name of task
* @param[in] arg the parameter of task enter function
* @param[in] pri the priority of task
* @param[in] ticks the time slice
* @param[in] stack task stack size = stack * sizeof(cpu_stack_t)
* @param[in] entry the entry function of task
* @param[in] autorun the autorunning flag of task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_dyn_create(ktask_t **task, const name_t *name, void *arg,
uint8_t pri, tick_t ticks, size_t stack,
task_entry_t entry, uint8_t autorun);
kstat_t krhino_cfs_task_dyn_create(ktask_t **task, const name_t *name, void *arg,
uint8_t pri, size_t stack, task_entry_t entry,
uint8_t autorun);
#if (RHINO_CONFIG_CPU_NUM > 1)
/**
* Create a task and malloc the stack space, bind the task to specific cpu.
*
* @param[in] task the task to be created (the space is provided inside, from heap)
* @param[in] name the name of task, which shall be unique
* @param[in] arg the parameter of task enter function
* @param[in] pri the priority of task
* @param[in] ticks the time slice
* @param[in] stack task stack size = stack * sizeof(cpu_stack_t)
* @param[in] entry the entry function of task
* @param[in] cpu_num the cpu that task bind to
* @param[in] autorun the autorunning flag of task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_cpu_dyn_create(ktask_t **task, const name_t *name, void *arg,
uint8_t pri, tick_t ticks, size_t stack,
task_entry_t entry, uint8_t cpu_num, uint8_t autorun);
kstat_t krhino_cfs_task_cpu_dyn_create(ktask_t **task, const name_t *name, void *arg,
uint8_t pri, size_t stack, task_entry_t entry,
uint8_t cpu_num, uint8_t autorun);
#endif
#endif
#if (RHINO_CONFIG_TASK_DEL > 0)
/**
* Delete a task, free the task stack.
*
* @param[in] task the task to be deleted.
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_del(ktask_t *task);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Delete a task, free the task stack, free ktask_t.
*
* @param[in] task the task to be deleted.
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_dyn_del(ktask_t *task);
#endif
/**
* Cancel a task.
*
* @param[in] task the task to be killed.
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_cancel(ktask_t *task);
/**
* Check the task self whether is canceled or not.
*
* @param[in] NULL
*
* @return false or true
*/
RHINO_BOOL krhino_task_cancel_chk(void);
#endif
/**
* Task sleep for some ticks.
*
* @param[in] ticks the ticks to sleep
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sleep(tick_t ticks);
/**
* Yield a task.
*
* @param[in] NULL
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_yield(void);
/**
* Get the current task for this cpu.
*
* @param[in] NULL
*
* @return the current task
*/
ktask_t *krhino_cur_task_get(void);
/**
* Suspend a task.
*
* @param[in] task the task to be suspended
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_suspend(ktask_t *task);
/**
* Resume a task from SUSPEND.
*
* @param[in] task the task to be resumed
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_resume(ktask_t *task);
/**
* Get min free stack size in the total runtime.
*
* @param[in] task the task where get free stack size.
* @param[out] free the free task stack size
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_stack_min_free(ktask_t *task, size_t *free);
/**
* Change the priority of task.
*
* @param[in] task the task to be changed priority
* @param[in] pri the priority to be changed.
* @param[out] old_pri the old priority
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_pri_change(ktask_t *task, uint8_t pri, uint8_t *old_pri);
/**
* Wakup the task, SUSPENDED/SLEEP/PEND -> READY.
*
* @param[in] task the task to be Wakup
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_wait_abort(ktask_t *task);
#if (RHINO_CONFIG_SCHED_RR > 0)
/**
* Set task timeslice when KSCHED_RR.
*
* @param[in] task the task to be set timeslice
* @param[in] slice the task time slice
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_time_slice_set(ktask_t *task, size_t slice);
/**
* Set task sched policy.
*
* @param[in] task the task to be set
* @param[in] policy KSCHED_FIFO / KSCHED_RR / KSCHED_CFS
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sched_policy_set(ktask_t *task, uint8_t policy);
/**
* Set task sched policy and priority.
*
* @param[in] task the task to be set timeslice
* @param[in] policy KSCHED_FIFO / KSCHED_RR / KSCHED_CFS
* @param[in] pri the prio of task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sched_param_set(ktask_t *task, uint8_t policy, uint8_t pri);
/**
* Get task sched policy.
*
* @param[in] task the task to be get timeslice
* @param[out] policy KSCHED_FIFO / KSCHED_RR / KSCHED_CFS
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_sched_policy_get(ktask_t *task, uint8_t *policy);
#endif
#if (RHINO_CONFIG_TASK_INFO > 0)
/**
* Set task private infomation.
*
* @param[in] task the task to be set private infomation
* @param[in] idx set the info[idx], < RHINO_CONFIG_TASK_INFO_NUM
* @param[in] info the private information
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_info_set(ktask_t *task, size_t idx, void *info);
/**
* Get task private infomation.
*
* @param[in] task the task to be get private infomation
* @param[in] idx get the info[idx], < RHINO_CONFIG_TASK_INFO_NUM
* @param[out] info to save private infomation
*
* @return the task private information
*/
kstat_t krhino_task_info_get(ktask_t *task, size_t idx, void **info);
#endif
/**
* Task self delete, run when task ends.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_task_deathbed(void);
/**
* Get the task by name.
*
* @param[in] name task name
*
* @return the task
*/
ktask_t *krhino_task_find(name_t *name);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_TASK_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_task.h
|
C
|
apache-2.0
| 15,200
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_TASK_SEM_H
#define K_TASK_SEM_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino task_sem
* Task-semaphore can be used for tasks synchronize.
*
* @{
*/
/**
* Create a semaphore and attach it to the task.
*
* @param[in] task pointer to the task
* @param[in] sem pointer to the semaphore
* @param[in] name name of the task-semaphore
* @param[in] count count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_create(ktask_t *task, ksem_t *sem, const name_t *name, size_t count);
/**
* Delete a task-semaphore.
*
* @param[in] task pointer to the task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_del(ktask_t *task);
/**
* Give a task-semaphore.
*
* @param[in] task pointer to the task
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_give(ktask_t *task);
/**
* Take a task-semaphore, task may be blocked.
*
* @param[in] ticks ticks to wait before take
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_take(tick_t ticks);
/**
* Set the count of a task-semaphore.
*
* @param[in] task pointer to the task
* @param[in] count count of the semaphre to set
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_count_set(ktask_t *task, sem_count_t count);
/**
* Get task-semaphore count.
*
* @param[in] task pointer to the semphore
* @param[out] count count of the semaphore
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_task_sem_count_get(ktask_t *task, sem_count_t *count);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_TASK_SEM_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_task_sem.h
|
C
|
apache-2.0
| 1,917
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_TIME_H
#define K_TIME_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino time
* Time management
*
* @{
*/
/**
* Systick routine handler.
*
* @param[in] NULL
*
* @return NULL
*/
void krhino_tick_proc(void);
/**
* Get the current time from system startup, in ms.
*
* @param[in] NULL
*
* @return system time
*/
sys_time_t krhino_sys_time_get(void);
/**
* Get the current time from system startup, in ticks.
*
* @param[in] NULL
*
* @return system ticks
*/
tick_t krhino_sys_tick_get(void);
/**
* Convert ms to ticks.
*
* @param[in] ms ms which will be converted to ticks
*
* @return the ticks of the ms
*/
tick_t krhino_ms_to_ticks(sys_time_t ms);
/**
* Convert ticks to ms.
*
* @param[in] ticks ticks which will be converted to ms
*
* @return the ms of the ticks
*/
sys_time_t krhino_ticks_to_ms(tick_t ticks);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_TIME_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_time.h
|
C
|
apache-2.0
| 1,018
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_TIMER_H
#define K_TIMER_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino timer
* Timer management
*
* @{
*/
/**
* Timer operation
*/
enum {
TIMER_CMD_CB = 0u,
TIMER_CMD_START,
TIMER_CMD_STOP,
TIMER_CMD_CHG,
TIMER_ARG_CHG,
TIMER_ARG_CHG_AUTO,
TIMER_CMD_DEL,
TIMER_CMD_DYN_DEL
};
/**
* Timer callback
*/
typedef void (*timer_cb_t)(void *timer, void *arg);
/**
* Timer object
*/
typedef struct {
/**<
* When the timer is active, timer_list is linked from g_timer_head,
* and sort by 'match'(timeout time).
*/
klist_t timer_list;
klist_t *to_head;
const name_t *name;
timer_cb_t cb;
void *timer_cb_arg;
tick_t match; /**< Expected timeout point */
tick_t remain;
tick_t init_count;
tick_t round_ticks; /**< Timer period */
void *priv;
kobj_type_t obj_type;
uint8_t timer_state; /**< TIMER_DEACTIVE or TIMER_ACTIVE */
uint8_t mm_alloc_flag;
} ktimer_t;
/**
* Describe a timer operation
*/
typedef struct {
ktimer_t *timer;
uint8_t cb_num; /**< TIMER_CMD_START/STOP/... */
tick_t first;
union {
tick_t round;
void *arg;
} u;
} k_timer_queue_cb;
typedef enum {
TIMER_DEACTIVE = 0u,
TIMER_ACTIVE
} k_timer_state_t;
/**
* Create a timer.
*
* @param[in] timer pointer to the timer (the space is provided outside, by user)
* @param[in] name name of the timer
* @param[in] cb callbak of the timer
* @param[in] first ticks of the first timer triger
* @param[in] round ticks of the timer period, 0 means one-shot timer
* @param[in] arg the argument of the callback
* @param[in] auto_run auto run or not when the timer is created
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_create(ktimer_t *timer, const name_t *name, timer_cb_t cb,
tick_t first, tick_t round, void *arg, uint8_t auto_run);
/**
* Delete a timer.
*
* @param[in] timer pointer to a timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_del(ktimer_t *timer);
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
/**
* Create and malloc a timer.
*
* @param[out] timer pointer to the timer (the space is provided inside, from heap)
* @param[in] name name of the timer
* @param[in] cb callbak of the timer
* @param[in] first ticks of the first timer triger
* @param[in] round ticks of the timer period, 0 means one-shot timer
* @param[in] arg the argument of the callback
* @param[in] auto_run auto run or not when the timer is created
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_dyn_create(ktimer_t **timer, const name_t *name, timer_cb_t cb,
tick_t first, tick_t round, void *arg, uint8_t auto_run);
/**
* Delete and free a timer.
*
* @param[in] timer pointer to a timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_dyn_del(ktimer_t *timer);
#endif
/**
* This function will start a timer.
*
* @param[in] timer pointer to the timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_start(ktimer_t *timer);
/**
* This function will stop a timer.
*
* @param[in] timer pointer to the timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_stop(ktimer_t *timer);
/**
* Change attributes of a timer.
* @note this func should follow the sequence as timer_stop -> timer_change -> timer_start
*
* @param[in] timer pointer to the timer
* @param[in] first ticks of the first timer triger
* @param[in] round ticks of the timer period, 0 means one-shot timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_change(ktimer_t *timer, tick_t first, tick_t round);
/**
* Change attributes of a timer without timer_stop and timer_start.
*
* @param[in] timer pointer to the timer
* @param[in] first ticks of the first timer triger
* @param[in] round ticks of the timer period, 0 means one-shot timer
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_arg_change_auto(ktimer_t *timer, void *arg);
/**
* Change callback arg attributes of a timer.
*
* @param[in] timer pointer to the timer
* @param[in] arg timer callback arg
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_timer_arg_change(ktimer_t *timer, void *arg);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_TIMER_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_timer.h
|
C
|
apache-2.0
| 4,958
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_TRACE_H
#define K_TRACE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino trace
* Trace
*
* @{
*/
#ifdef AOS_COMP_TRACE
#define SYSVIEW_TRACE_ID_SEM_BASE (40u)
#define SYSVIEW_TRACE_ID_SEM_CREATE ( 1u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_OVERFLOW ( 2u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_CNT_INCREASE ( 3u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_GET_SUCCESS ( 4u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_GET_BLK ( 5u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_TASK_WAKE ( 6u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_DEL ( 7u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_SEM_GIVE ( 8u + SYSVIEW_TRACE_ID_SEM_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_BASE (50u)
#define SYSVIEW_TRACE_ID_MUTEX_CREATE ( 1u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_RELEASE ( 2u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_GET ( 3u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_TASK_PRI_INV ( 4u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_GET_BLK ( 5u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_RELEASE_SUCCESS ( 6u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_TASK_WAKE ( 7u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_MUTEX_DEL ( 8u + SYSVIEW_TRACE_ID_MUTEX_BASE)
#define SYSVIEW_TRACE_ID_EVENT_BASE (60u)
#define SYSVIEW_TRACE_ID_EVENT_CREATE ( 1u + SYSVIEW_TRACE_ID_EVENT_BASE)
#define SYSVIEW_TRACE_ID_EVENT_GET ( 2u + SYSVIEW_TRACE_ID_EVENT_BASE)
#define SYSVIEW_TRACE_ID_EVENT_GET_BLK ( 3u + SYSVIEW_TRACE_ID_EVENT_BASE)
#define SYSVIEW_TRACE_ID_EVENT_TASK_WAKE ( 4u + SYSVIEW_TRACE_ID_EVENT_BASE)
#define SYSVIEW_TRACE_ID_EVENT_DEL ( 5u + SYSVIEW_TRACE_ID_EVENT_BASE)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_BASE (70u)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_CREATE ( 1u + SYSVIEW_TRACE_ID_BUF_QUEUE_BASE)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_MAX ( 2u + SYSVIEW_TRACE_ID_BUF_QUEUE_BASE)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_POST ( 3u + SYSVIEW_TRACE_ID_BUF_QUEUE_BASE)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_TASK_WAKE ( 4u + SYSVIEW_TRACE_ID_BUF_QUEUE_BASE)
#define SYSVIEW_TRACE_ID_BUF_QUEUE_GET_BLK ( 5u + SYSVIEW_TRACE_ID_BUF_QUEUE_BASE)
#define SYSVIEW_TRACE_ID_WORKQUEUE_BASE (80u)
#define SYSVIEW_TRACE_ID_WORKQUEUE_INIT ( 1u + SYSVIEW_TRACE_ID_WORKQUEUE_BASE)
#define SYSVIEW_TRACE_ID_WORKQUEUE_CREATE ( 2u + SYSVIEW_TRACE_ID_WORKQUEUE_BASE)
#define SYSVIEW_TRACE_ID_WORKQUEUE_DEL ( 3u + SYSVIEW_TRACE_ID_WORKQUEUE_BASE)
/* interrupt trace */
void trace_intrpt_exit(void);
void trace_intrpt_enter(void);
#if 0
#define TRACE_INTRPT_ENTETR() trace_intrpt_enter()
#define TRACE_INTRPT_EXIT() trace_intrpt_exit()
#else
#define TRACE_INTRPT_ENTETR()
#define TRACE_INTRPT_EXIT()
#endif
/* task trace */
void trace_task_switch(ktask_t *from, ktask_t *to);
void trace_intrpt_task_switch(ktask_t *from, ktask_t *to);
void trace_init(void);
void trace_task_idel(void);
void trace_task_create(ktask_t *task);
void trace_task_wait_abort(ktask_t *task, ktask_t *task_abort);
void trace_task_resume(ktask_t *task, ktask_t *task_resumed);
void trace_task_suspend(ktask_t *task, ktask_t *task_suspended);
void trace_task_start_ready(ktask_t *task);
void trace_task_stop_ready(ktask_t *task);
#define TRACE_INIT() trace_init()
#define TRACE_TASK_SWITCH(from, to) trace_task_switch(from, to)
#define TRACE_TASK_CREATE(task) trace_task_create(task)
#define TRACE_TASK_SLEEP(task, ticks)
#define TRACE_INTRPT_TASK_SWITCH(from, to) trace_intrpt_task_switch(from, to)
#define TRACE_TASK_PRI_CHANGE(task, task_pri_chg, pri)
#define TRACE_TASK_SUSPEND(task, task_suspended) trace_task_suspend(task, task_suspended)
#define TRACE_TASK_RESUME(task, task_resumed) trace_task_resume(task, task_resumed)
#define TRACE_TASK_DEL(task, task_del)
#define TRACE_TASK_WAIT_ABORT(task, task_abort) trace_task_wait_abort(task, task_abort)
#define TRACE_TASK_START_READY(task) trace_task_start_ready(task)
#define TRACE_TASK_STOP_READY(task) trace_task_stop_ready(task)
/* semaphore trace */
void trace_sem_create(ktask_t *task, ksem_t *sem);
void trace_sem_overflow(ktask_t *task, ksem_t *sem);
void trace_sem_cnt_increase(ktask_t *task, ksem_t *sem);
void trace_sem_get_success(ktask_t *task, ksem_t *sem);
void trace_sem_get_blk(ktask_t *task, ksem_t *sem);
void trace_sem_task_wake(ktask_t *task, ktask_t *task_waked_up, ksem_t *sem, uint8_t opt_wake_all);
void trace_sem_del(ktask_t *task, ksem_t *sem);
void trace_sem_give(ksem_t *sem, uint8_t opt_wake_all);
#define TRACE_SEM_CREATE(task, sem) trace_sem_create(task, sem)
#define TRACE_SEM_OVERFLOW(task, sem) trace_sem_overflow(task, sem)
#define TRACE_SEM_CNT_INCREASE(task, sem) trace_sem_cnt_increase(task, sem)
#define TRACE_SEM_GET_SUCCESS(task, sem) trace_sem_get_success(task, sem)
#define TRACE_SEM_GET_BLK(task, sem, wait_option) trace_sem_get_blk(task, sem)
#define TRACE_SEM_TASK_WAKE(task, task_waked_up, sem, opt_wake_all) trace_sem_task_wake(task, task_waked_up, sem, opt_wake_all)
#define TRACE_SEM_DEL(task, sem) trace_sem_del(task, sem)
#define TRACE_SEM_GIVE(sem, opt_wake_all) trace_sem_give(sem, opt_wake_all)
/* mutex trace */
void trace_mutex_create(ktask_t *task, kmutex_t *mutex, const name_t *name);
void trace_mutex_release(ktask_t *task, ktask_t *task_release, uint8_t new_pri);
void trace_mutex_get(ktask_t *task, kmutex_t *mutex, tick_t wait_option);
void trace_task_pri_inv(ktask_t *task, ktask_t *mtxtsk);
void trace_mutex_get_blk(ktask_t *task, kmutex_t *mutex, tick_t wait_option);
void trace_mutex_release_success(ktask_t *task, kmutex_t *mutex);
void trace_mutex_task_wake(ktask_t *task, ktask_t *task_waked_up, kmutex_t *mutex);
void trace_mutex_del(ktask_t *task, kmutex_t *mutex);
#define TRACE_MUTEX_CREATE(task, mutex, name) trace_mutex_create(task, mutex, name)
#define TRACE_MUTEX_RELEASE(task, task_release, new_pri) trace_mutex_release(task, task_release, new_pri)
#define TRACE_MUTEX_GET(task, mutex, wait_option) trace_mutex_get(task, mutex, wait_option)
#define TRACE_TASK_PRI_INV(task, mtxtsk) trace_task_pri_inv(task, mtxtsk)
#define TRACE_MUTEX_GET_BLK(task, mutex, wait_option) trace_mutex_get_blk(task, mutex, wait_option)
#define TRACE_MUTEX_RELEASE_SUCCESS(task, mutex) trace_mutex_release_success(task, mutex)
#define TRACE_MUTEX_TASK_WAKE(task, task_waked_up, mutex) trace_mutex_task_wake(task, task_waked_up, mutex)
#define TRACE_MUTEX_DEL(task, mutex) trace_mutex_del(task, mutex)
/* event trace */
void trace_event_create(ktask_t *task, kevent_t *event, const name_t *name, uint32_t flags_init);
void trace_event_get(ktask_t *task, kevent_t *event);
void trace_event_get_blk(ktask_t *task, kevent_t *event, tick_t wait_option);
void trace_event_task_wake(ktask_t *task, ktask_t *task_waked_up, kevent_t *event);
void trace_event_del(ktask_t *task, kevent_t *event);
#define TRACE_EVENT_CREATE(task, event, name, flags_init) trace_event_create(task, event, name, flags_init)
#define TRACE_EVENT_GET(task, event) trace_event_get(task, event)
#define TRACE_EVENT_GET_BLK(task, event, wait_option) trace_event_get_blk(task, event, wait_option)
#define TRACE_EVENT_TASK_WAKE(task, task_waked_up, event) trace_event_task_wake(task, task_waked_up, event)
#define TRACE_EVENT_DEL(task, event) trace_event_del(task, event)
/* buf_queue trace */
void trace_buf_queue_create(ktask_t *task, kbuf_queue_t *buf_queue);
void trace_buf_queue_max(ktask_t *task, kbuf_queue_t *buf_queue, void *msg, size_t msg_size);
void trace_buf_queue_post(ktask_t *task, kbuf_queue_t *buf_queue, void *msg, size_t msg_size);
void trace_buf_queue_task_wake(ktask_t *task, ktask_t *task_waked_up, kbuf_queue_t *buf_queue);
void trace_buf_queue_get_blk(ktask_t *task, kbuf_queue_t *buf_queue, tick_t wait_option);
#define TRACE_BUF_QUEUE_CREATE(task, buf_queue) trace_buf_queue_create(task, buf_queue)
#define TRACE_BUF_QUEUE_MAX(task, buf_queue, msg, msg_size) trace_buf_queue_max(task, buf_queue, msg, msg_size)
#define TRACE_BUF_QUEUE_POST(task, buf_queue, msg, msg_size) trace_buf_queue_post(task, buf_queue, msg, msg_size)
#define TRACE_BUF_QUEUE_TASK_WAKE(task, task_waked_up, queue) trace_buf_queue_task_wake(task, task_waked_up, queue)
#define TRACE_BUF_QUEUE_GET_BLK(task, buf_queue, wait_option) trace_buf_queue_get_blk(task, buf_queue, wait_option)
/* timer trace */
#define TRACE_TIMER_CREATE(task, timer)
#define TRACE_TIMER_DEL(task, timer)
/* MBLK trace */
#define TRACE_MBLK_POOL_CREATE(task, pool)
/* MM trace */
#define TRACE_MM_POOL_CREATE(task, pool)
/* MM region trace*/
#define TRACE_MM_REGION_CREATE(task, regions)
/* work queue trace */
void trace_workqueue_init(ktask_t *task, kwork_t *work);
void trace_workqueue_create(ktask_t *task, kworkqueue_t *workqueue);
void trace_workqueue_del(ktask_t *task, kworkqueue_t *workqueue);
#define TRACE_WORK_INIT(task, work) trace_workqueue_init(task, work)
#define TRACE_WORKQUEUE_CREATE(task, workqueue) trace_workqueue_create(task, workqueue)
#define TRACE_WORKQUEUE_DEL(task, workqueue) trace_workqueue_del(task, workqueue)
int uart_port_init(void);
#else
/* task trace */
#define TRACE_INIT()
#define TRACE_TASK_SWITCH(from, to)
#define TRACE_TASK_CREATE(task)
#define TRACE_TASK_SLEEP(task, ticks)
#define TRACE_INTRPT_TASK_SWITCH(from, to)
#define TRACE_TASK_PRI_CHANGE(task, task_pri_chg, pri)
#define TRACE_TASK_SUSPEND(task, task_suspended)
#define TRACE_TASK_RESUME(task, task_resumed)
#define TRACE_TASK_DEL(task, task_del)
#define TRACE_TASK_WAIT_ABORT(task, task_abort)
#define TRACE_TASK_START_READY(task)
#define TRACE_TASK_STOP_READY(task)
/* interuppt trace */
#define TRACE_INTRPT_ENTETR()
#define TRACE_INTRPT_EXIT()
/* semaphore trace */
#define TRACE_SEM_CREATE(task, sem)
#define TRACE_SEM_OVERFLOW(task, sem)
#define TRACE_SEM_CNT_INCREASE(task, sem)
#define TRACE_SEM_GET_SUCCESS(task, sem)
#define TRACE_SEM_GET_BLK(task, sem, wait_option)
#define TRACE_SEM_TASK_WAKE(task, task_waked_up, sem, opt_wake_all)
#define TRACE_SEM_DEL(task, sem)
#define TRACE_SEM_GIVE(sem, opt_wake_all)
/* mutex trace */
#define TRACE_MUTEX_CREATE(task, mutex, name)
#define TRACE_MUTEX_RELEASE(task, task_release, new_pri)
#define TRACE_MUTEX_GET(task, mutex, wait_option)
#define TRACE_TASK_PRI_INV(task, mtxtsk)
#define TRACE_MUTEX_GET_BLK(task, mutex, wait_option)
#define TRACE_MUTEX_RELEASE_SUCCESS(task, mutex)
#define TRACE_MUTEX_TASK_WAKE(task, task_waked_up, mutex)
#define TRACE_MUTEX_DEL(task, mutex)
/* event trace */
#define TRACE_EVENT_CREATE(task, event, name, flags_init)
#define TRACE_EVENT_GET(task, event)
#define TRACE_EVENT_GET_BLK(task, event, wait_option)
#define TRACE_EVENT_TASK_WAKE(task, task_waked_up, event)
#define TRACE_EVENT_DEL(task, event)
/* buf_queue trace */
#define TRACE_BUF_QUEUE_CREATE(task, buf_queue)
#define TRACE_BUF_QUEUE_MAX(task, buf_queue, msg, msg_size)
#define TRACE_BUF_QUEUE_POST(task, buf_queue, msg, msg_size)
#define TRACE_BUF_QUEUE_TASK_WAKE(task, task_waked_up, queue)
#define TRACE_BUF_QUEUE_GET_BLK(task, buf_queue, wait_option)
/* timer trace */
#define TRACE_TIMER_CREATE(task, timer)
#define TRACE_TIMER_DEL(task, timer)
/* MBLK trace */
#define TRACE_MBLK_POOL_CREATE(task, pool)
/* MM trace */
#define TRACE_MM_POOL_CREATE(task, pool)
/* MM region trace*/
#define TRACE_MM_REGION_CREATE(task, regions)
/* work queue trace */
#define TRACE_WORK_INIT(task, work)
#define TRACE_WORKQUEUE_CREATE(task, workqueue)
#define TRACE_WORKQUEUE_DEL(task, workqueue)
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_trace.h
|
C
|
apache-2.0
| 11,802
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_WORKQUEUE_H
#define K_WORKQUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_rhino workqueue
* workqueue
*
* @{
*/
#if (RHINO_CONFIG_WORKQUEUE > 0)
#define WORKQUEUE_WORK_MAX 32
typedef void (*work_handle_t)(void *arg);
typedef struct {
klist_t work_node;
work_handle_t handle;
void *arg;
tick_t dly;
ktimer_t *timer;
void *wq;
uint8_t work_exit;
} kwork_t;
typedef struct {
klist_t workqueue_node;
klist_t work_list;
kwork_t *work_current; /* current work */
const name_t *name;
ktask_t worker;
ksem_t sem;
} kworkqueue_t;
/**
* Creat a workqueue.
*
* @param[in] workqueue the workqueue to be created
* @param[in] name the name of workqueue/worker, which should be unique
* @param[in] pri the priority of the worker
* @param[in] stack_buf the stack of the worker(task)
* @param[in] stack_size the size of the worker-stack
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_workqueue_create(kworkqueue_t *workqueue, const name_t *name,
uint8_t pri, cpu_stack_t *stack_buf, size_t stack_size);
/**
* This function will delete a workqueue
* @param[in] workqueue the workqueue to be deleted
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_workqueue_del(kworkqueue_t *workqueue);
/**
* Initialize a work.
*
* @param[in] work the work to be initialized
* @param[in] handle the call back function to run
* @param[in] arg the paraments of the function
* @param[in] dly the ticks to delay before run
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_work_init(kwork_t *work, work_handle_t handle, void *arg, tick_t dly);
/**
* Run a work on a workqueue.
*
* @param[in] workqueue the workqueue to run work
* @param[in] work the work to run
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_work_run(kworkqueue_t *workqueue, kwork_t *work);
/**
* Run a work on the default workqueue.
*
* @param[in] work the work to run
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_work_sched(kwork_t *work);
/**
* Cancel a work.
*
* @param[in] work the work to cancel
*
* @return the operation status, RHINO_SUCCESS is OK, others is error
*/
kstat_t krhino_work_cancel(kwork_t *work);
#endif
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* K_WORKQUEUE_H */
|
YifuLiu/AliOS-Things
|
kernel/rhino/include/k_workqueue.h
|
C
|
apache-2.0
| 2,707
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
/*
* DESCRIPTION
* This library is used to provide the atomic operators for CPU
* which do not support native atomic operations.
*
* The design principle is disable the interrupt when execute the
* atomic operations and enable the interrupt after finish the
* operation.
*/
#include "k_api.h"
#include "k_atomic.h"
/**
* This routine atomically adds <*target> and <value>, placing the result in
* <*target>. The operation is done using unsigned integer arithmetic.
*
* This routine can be used from both task and interrupt context.
*
* @param target memory location to add to
* @param value the value to add
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_add(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target += value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically subtracts <value> from <*target>, result is placed
* in <*target>. The operation is done using unsigned integer arithmetic.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to subtract from
* @param value the value to subtract
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_sub(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target -= value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically increments the value in <*target>. The operation is
* done using unsigned integer arithmetic.
*
* This routine can be used from both task and interrupt context.
*
* @return The value from <target> before the increment
*/
atomic_val_t rhino_atomic_inc(atomic_t *target)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
(*target)++;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically decrement the value in <*target>. The operation is
* done using unsigned integer arithmetic.
*
* This routine can be used from both task and interrupt context.
*
* @return The value from <target> before the increment
*/
atomic_val_t rhino_atomic_dec(atomic_t *target)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
(*target)--;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically sets <*target> to <value> and returns the old value
* that was in <*target>. Normally all CPU architectures can atomically write
* to a variable of size atomic_t without the help of this routine.
* This routine is intended for software that needs to atomically fetch and
* replace the value of a memory location.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to write to
* @param value the value to write
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_set(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target = value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically read a value from <target>.
* This routine can be used from both task and interrupt context.
*
* @return The value read from <target>
*/
atomic_val_t rhino_atomic_get(const atomic_t *target)
{
return *target;
}
/**
* This routine atomically performs a bitwise OR operation of <*target>
* and <value>, placing the result in <*target>.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to be modified
* @param value the value to OR
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_or(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target |= value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically performs a bitwise XOR operation of <*target> and
* <value>, placing the result in <*target>.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to be modified
* @param value the value to XOR
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_xor(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target ^= value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically performs a bitwise AND operation of <*target> and
* <value>, placing the result in <*target>.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to be modified
* @param value the value to AND
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_and(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target &= value;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine atomically performs a bitwise NAND operation of <*target> and
* <value>, placing the result in <*target>.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to be modified
* @param value the value to NAND
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_nand(atomic_t *target, atomic_val_t value)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target = ~(*target & value);
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine provides the atomic clear operator. The value of 0 is atomically
* written at <target> and the previous value at <target> is returned.
*
* This routine can be used from both task and interrupt context.
*
* @param target the memory location to write
*
* @return The previous value from <target>
*/
atomic_val_t rhino_atomic_clear(atomic_t *target)
{
CPSR_ALLOC();
atomic_val_t old_value;
RHINO_CPU_INTRPT_DISABLE();
old_value = *target;
*target = 0;
RHINO_CPU_INTRPT_ENABLE();
return old_value;
}
/**
* This routine performs an atomic compare-and-swap, it test that whether
* <*target> equal to <oldValue>, and if TRUE, setting the value of <*target>
* to <newValue> and return 1.
*
* If the original value at <target> does not equal <oldValue>, then the target
* will not be updated and return 0.
*
* @param target address to be tested
* @param old_value value to compare against
* @param new_value value to compare against
* @return Returns 1 if <new_value> is written, 0 otherwise.
*/
int rhino_atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value)
{
CPSR_ALLOC();
int ret = 0;
RHINO_CPU_INTRPT_DISABLE();
if (*target == old_value){
*target = new_value;
ret = 1;
}
RHINO_CPU_INTRPT_ENABLE();
return ret;
}
|
YifuLiu/AliOS-Things
|
kernel/rhino/k_atomic.c
|
C
|
apache-2.0
| 7,416
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include "k_api.h"
#if (RHINO_CONFIG_BUF_QUEUE > 0)
static kstat_t buf_queue_create(kbuf_queue_t *queue, const name_t *name, void *buf, size_t size,
size_t max_msg, uint8_t mm_alloc_flag, size_t type)
{
#if (RHINO_CONFIG_KOBJ_LIST > 0)
CPSR_ALLOC();
#endif
NULL_PARA_CHK(queue);
NULL_PARA_CHK(buf);
NULL_PARA_CHK(name);
if (max_msg == 0u) {
return RHINO_INV_PARAM;
}
if (size == 0u) {
return RHINO_BUF_QUEUE_SIZE_ZERO;
}
memset(queue, 0, sizeof(kbuf_queue_t));
/* init the queue blocked list */
klist_init(&queue->blk_obj.blk_list);
queue->buf = buf;
queue->cur_num = 0u;
queue->peak_num = 0u;
queue->max_msg_size = max_msg;
queue->blk_obj.name = name;
queue->blk_obj.blk_policy = BLK_POLICY_PRI;
queue->mm_alloc_flag = mm_alloc_flag;
#if (RHINO_CONFIG_TASK_DEL > 0)
queue->blk_obj.cancel = 1u;
#endif
#if (RHINO_CONFIG_KOBJ_LIST > 0)
RHINO_CRITICAL_ENTER();
klist_insert(&(g_kobj_list.buf_queue_head), &queue->buf_queue_item);
RHINO_CRITICAL_EXIT();
#endif
queue->blk_obj.obj_type = RHINO_BUF_QUEUE_OBJ_TYPE;
ringbuf_init(&(queue->ringbuf), buf, size, type, max_msg);
queue->min_free_buf_size = queue->ringbuf.freesize;
TRACE_BUF_QUEUE_CREATE(krhino_cur_task_get(), queue);
return RHINO_SUCCESS;
}
kstat_t krhino_buf_queue_create(kbuf_queue_t *queue, const name_t *name,
void *buf, size_t size, size_t max_msg)
{
return buf_queue_create(queue, name, buf, size, max_msg, K_OBJ_STATIC_ALLOC, RINGBUF_TYPE_DYN);
}
kstat_t krhino_fix_buf_queue_create(kbuf_queue_t *queue, const name_t *name,
void *buf, size_t msg_size, size_t msg_num)
{
return buf_queue_create(queue, name, buf, msg_size * msg_num, msg_size, K_OBJ_STATIC_ALLOC, RINGBUF_TYPE_FIX);
}
kstat_t krhino_buf_queue_del(kbuf_queue_t *queue)
{
CPSR_ALLOC();
klist_t *head;
NULL_PARA_CHK(queue);
RHINO_CRITICAL_ENTER();
INTRPT_NESTED_LEVEL_CHK();
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
if (queue->mm_alloc_flag != K_OBJ_STATIC_ALLOC) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_DEL_ERR;
}
head = &queue->blk_obj.blk_list;
queue->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE;
/* all task blocked on this queue is waken up */
while (!is_klist_empty(head)) {
pend_task_rm(krhino_list_entry(head->next, ktask_t, task_list));
}
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_rm(&queue->buf_queue_item);
#endif
ringbuf_reset(&queue->ringbuf);
RHINO_CRITICAL_EXIT_SCHED();
return RHINO_SUCCESS;
}
#if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
static kstat_t buf_queue_dyn_create(kbuf_queue_t **queue, const name_t *name,
size_t size, size_t max_msg, uint8_t type)
{
kstat_t stat;
kbuf_queue_t *queue_obj;
NULL_PARA_CHK(queue);
if (size == 0u) {
return RHINO_BUF_QUEUE_SIZE_ZERO;
}
queue_obj = krhino_mm_alloc(sizeof(kbuf_queue_t));
if (queue_obj == NULL) {
return RHINO_NO_MEM;
}
queue_obj->buf = krhino_mm_alloc(size);
if (queue_obj->buf == NULL) {
krhino_mm_free(queue_obj);
return RHINO_NO_MEM;
}
stat = buf_queue_create(queue_obj, name, queue_obj->buf, size, max_msg,
K_OBJ_DYN_ALLOC, type);
if (stat != RHINO_SUCCESS) {
krhino_mm_free(queue_obj->buf);
krhino_mm_free(queue_obj);
return stat;
}
*queue = queue_obj;
return RHINO_SUCCESS;
}
kstat_t krhino_buf_queue_dyn_create(kbuf_queue_t **queue, const name_t *name,
size_t size, size_t max_msg)
{
return buf_queue_dyn_create(queue, name, size, max_msg, RINGBUF_TYPE_DYN);
}
kstat_t krhino_fix_buf_queue_dyn_create(kbuf_queue_t **queue, const name_t *name,
size_t msg_size, size_t msg_num)
{
return buf_queue_dyn_create(queue, name, msg_size * msg_num, msg_size, RINGBUF_TYPE_FIX);
}
kstat_t krhino_buf_queue_dyn_del(kbuf_queue_t *queue)
{
CPSR_ALLOC();
klist_t *head;
NULL_PARA_CHK(queue);
RHINO_CRITICAL_ENTER();
INTRPT_NESTED_LEVEL_CHK();
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
if (queue->mm_alloc_flag != K_OBJ_DYN_ALLOC) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_DEL_ERR;
}
head = &queue->blk_obj.blk_list;
queue->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE;
while (!is_klist_empty(head)) {
pend_task_rm(krhino_list_entry(head->next, ktask_t, task_list));
}
#if (RHINO_CONFIG_KOBJ_LIST > 0)
klist_rm(&queue->buf_queue_item);
#endif
ringbuf_reset(&queue->ringbuf);
RHINO_CRITICAL_EXIT_SCHED();
krhino_mm_free(queue->buf);
krhino_mm_free(queue);
return RHINO_SUCCESS;
}
#endif
static kstat_t buf_queue_send(kbuf_queue_t *queue, void *msg, size_t msg_size)
{
CPSR_ALLOC();
klist_t *head;
ktask_t *task;
kstat_t err;
uint8_t cur_cpu_num;
RHINO_CRITICAL_ENTER();
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
cur_cpu_num = cpu_cur_get();
(void)cur_cpu_num;
if (msg_size > queue->max_msg_size) {
TRACE_BUF_QUEUE_MAX(g_active_task[cur_cpu_num], queue, msg, msg_size);
RHINO_CRITICAL_EXIT();
return RHINO_BUF_QUEUE_MSG_SIZE_OVERFLOW;
}
if (msg_size == 0) {
RHINO_CRITICAL_EXIT();
return RHINO_INV_PARAM;
}
head = &queue->blk_obj.blk_list;
/* buf queue is not full here, if there is no blocked receive task */
if (is_klist_empty(head)) {
err = ringbuf_push(&(queue->ringbuf), msg, msg_size);
if (err != RHINO_SUCCESS) {
RHINO_CRITICAL_EXIT();
if (err == RHINO_RINGBUF_FULL) {
err = RHINO_BUF_QUEUE_FULL;
}
return err;
}
queue->cur_num++;
if (queue->peak_num < queue->cur_num) {
queue->peak_num = queue->cur_num;
}
if (queue->min_free_buf_size > queue->ringbuf.freesize) {
queue->min_free_buf_size = queue->ringbuf.freesize;
}
TRACE_BUF_QUEUE_POST(g_active_task[cur_cpu_num], queue, msg, msg_size);
RHINO_CRITICAL_EXIT();
return RHINO_SUCCESS;
}
task = krhino_list_entry(head->next, ktask_t, task_list);
memcpy(task->msg, msg, msg_size);
task->bq_msg_size = msg_size;
pend_task_wakeup(task);
TRACE_BUF_QUEUE_TASK_WAKE(g_active_task[cur_cpu_num], task, queue);
RHINO_CRITICAL_EXIT_SCHED();
return RHINO_SUCCESS;
}
kstat_t krhino_buf_queue_send(kbuf_queue_t *queue, void *msg, size_t size)
{
NULL_PARA_CHK(queue);
NULL_PARA_CHK(msg);
return buf_queue_send(queue, msg, size);
}
kstat_t krhino_buf_queue_recv(kbuf_queue_t *queue, tick_t ticks, void *msg, size_t *size)
{
CPSR_ALLOC();
kstat_t ret;
uint8_t cur_cpu_num;
NULL_PARA_CHK(queue);
NULL_PARA_CHK(msg);
NULL_PARA_CHK(size);
RHINO_CRITICAL_ENTER();
cur_cpu_num = cpu_cur_get();
TASK_CANCEL_CHK(queue);
if ((g_intrpt_nested_level[cur_cpu_num] > 0u) && (ticks != RHINO_NO_WAIT)) {
RHINO_CRITICAL_EXIT();
return RHINO_NOT_CALLED_BY_INTRPT;
}
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
if (queue->cur_num > 0u) {
ringbuf_pop(&(queue->ringbuf), msg, size);
queue->cur_num--;
RHINO_CRITICAL_EXIT();
return RHINO_SUCCESS;
}
if (ticks == RHINO_NO_WAIT) {
*size = 0u;
RHINO_CRITICAL_EXIT();
return RHINO_NO_PEND_WAIT;
}
if (g_sched_lock[cur_cpu_num] > 0u) {
*size = 0u;
RHINO_CRITICAL_EXIT();
return RHINO_SCHED_DISABLE;
}
g_active_task[cur_cpu_num]->msg = msg;
pend_to_blk_obj(&queue->blk_obj, g_active_task[cur_cpu_num], ticks);
TRACE_BUF_QUEUE_GET_BLK(g_active_task[cur_cpu_num], queue, ticks);
RHINO_CRITICAL_EXIT_SCHED();
RHINO_CPU_INTRPT_DISABLE();
cur_cpu_num = cpu_cur_get();
ret = pend_state_end_proc(g_active_task[cur_cpu_num], &queue->blk_obj);
switch (ret) {
case RHINO_SUCCESS:
*size = g_active_task[cur_cpu_num]->bq_msg_size;
break;
default:
*size = 0u;
break;
}
RHINO_CPU_INTRPT_ENABLE();
return ret;
}
kstat_t krhino_buf_queue_flush(kbuf_queue_t *queue)
{
CPSR_ALLOC();
NULL_PARA_CHK(queue);
RHINO_CRITICAL_ENTER();
INTRPT_NESTED_LEVEL_CHK();
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
ringbuf_reset(&(queue->ringbuf));
queue->cur_num = 0u;
queue->peak_num = 0u;
queue->min_free_buf_size = queue->ringbuf.freesize;
RHINO_CRITICAL_EXIT();
return RHINO_SUCCESS;
}
kstat_t krhino_buf_queue_info_get(kbuf_queue_t *queue, kbuf_queue_info_t *info)
{
CPSR_ALLOC();
NULL_PARA_CHK(queue);
NULL_PARA_CHK(info);
RHINO_CRITICAL_ENTER();
if (queue->blk_obj.obj_type != RHINO_BUF_QUEUE_OBJ_TYPE) {
RHINO_CRITICAL_EXIT();
return RHINO_KOBJ_TYPE_ERR;
}
info->free_buf_size = queue->ringbuf.freesize;
info->min_free_buf_size = queue->min_free_buf_size;
info->buf_size = queue->ringbuf.end - queue->ringbuf.buf;
info->max_msg_size = queue->max_msg_size;
info->cur_num = queue->cur_num;
info->peak_num = queue->peak_num;
RHINO_CRITICAL_EXIT();
return RHINO_SUCCESS;
}
#endif
|
YifuLiu/AliOS-Things
|
kernel/rhino/k_buf_queue.c
|
C
|
apache-2.0
| 10,144
|
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "k_api.h"
#if (RHINO_CONFIG_SCHED_CFS > 0)
static struct k_rbtree_root_t cfs_root = RBT_ROOT;
/*
* Insert @key into rbtree, On success, return 0, else return -1
*/
static void node_insert(struct k_rbtree_root_t *root, cfs_node *node, lr_timer_t key)
{
struct k_rbtree_node_t **tmp = &(root->rbt_node), *parent = NULL;
/* Figure out where to put new node */
while (*tmp) {
cfs_node *my = k_rbtree_entry(*tmp, cfs_node, rbt_node);
parent = *tmp;
if (key <= my->key)
tmp = &((*tmp)->rbt_left);
else if (key > my->key)
tmp = &((*tmp)->rbt_right);
}
node->key = key;
/* Add new node and rebalance tree. */
k_rbtree_link_node(&node->rbt_node, parent, tmp);
k_rbtree_insert_color(&node->rbt_node, root);
}
void cfs_node_insert(cfs_node *node, lr_timer_t key)
{
node_insert(&cfs_root, node, key);
}
void cfs_node_del(cfs_node *node)
{
k_rbtree_erase(&node->rbt_node, &cfs_root);
}
lr_timer_t cfs_node_min_get(void)
{
struct k_rbtree_node_t *tmp;
cfs_node *node_cfs;
tmp = k_rbtree_first(&cfs_root);
if (tmp == NULL) {
return 0;
}
node_cfs = k_rbtree_entry(tmp, cfs_node, rbt_node);
return node_cfs->key;
}
ktask_t *cfs_preferred_task_get(void)
{
struct k_rbtree_node_t *tmp;
cfs_node *node_cfs;
ktask_t *task;
tmp = k_rbtree_first(&cfs_root);
if (tmp == NULL) {
return 0;
}
node_cfs = k_rbtree_entry(tmp, cfs_node, rbt_node);
task = krhino_list_entry(node_cfs, ktask_t, node);
return task;
}
#endif
|
YifuLiu/AliOS-Things
|
kernel/rhino/k_cfs.c
|
C
|
apache-2.0
| 1,687
|