file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/dma.c
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file dma.c
* @brief This file provides code for the configuration
* of all the requested memory to memory DMA transfers.
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dma.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure DMA */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Enable DMA controller clock
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMAMUX1_CLK_ENABLE();
__HAL_RCC_DMA1_CLK_ENABLE();
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
| 1,412 |
C
| 26.173076 | 80 | 0.395892 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_app_hooks.c
|
/**
******************************************************************************
* @file mc_app_hooks.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file implements default motor control app hooks.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCAppHooks
*/
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
#include "mc_app_hooks.h"
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MCTasks
* @{
*/
/**
* @defgroup MCAppHooks Motor Control Applicative hooks
* @brief User defined functions that are called in the Motor Control tasks.
*
*
* @{
*/
/**
* @brief Hook function called right before the end of the MCboot function.
*
*
*
*/
__weak void MC_APP_BootHook(void)
{
/*
* This function can be overloaded or the application can inject
* code into it that will be executed at the end of MCboot().
*/
/* USER CODE BEGIN BootHook */
/* USER CODE END BootHook */
}
/**
* @brief Hook function called right after the Medium Frequency Task for Motor 1.
*
*
*
*/
__weak void MC_APP_PostMediumFrequencyHook_M1(void)
{
/*
* This function can be overloaded or the application can inject
* code into it that will be executed right after the Medium
* Frequency Task of Motor 1
*/
/* USER SECTION BEGIN PostMediumFrequencyHookM1 */
/* USER SECTION END PostMediumFrequencyHookM1 */
}
/** @} */
/** @} */
/** @} */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 2,067 |
C
| 23.046511 | 85 | 0.544267 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mcp.c
|
/**
******************************************************************************
* @file mcp.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides firmware functions that implement the MCP protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include "mc_type.h"
#include "mcp.h"
#include "register_interface.h"
#include "mc_config.h"
#include "mcp_config.h"
#include "mc_api.h"
/** @addtogroup MCSDK
* @{
*/
/** @defgroup MCP Motor Control Protocol
*
* @brief Motor Control Protocol components of the Motor Control SDK.
*
* These components implement the features needed to drive and monitor motor control applications embedded in STM32 MCUs.
* They mainly focus on the communication with the controller, both on the receiving and the transmitting end.
*
* @{
*/
/**
* @brief Parses the payload in the received packet and call the required function in order to modify a value.
*
* The function called depends on the targeted motor and/or targeted register : RI_SetRegisterGlobal or RI_SetRegisterMotorX.
*
* @param pHandle Handler of the current instance of the MCP component
* @param txSyncFreeSpace Space available for synchronous transmission
*
* @retval Returns #MCP_CMD_OK if the command is acknowledged and #MCP_CMD_NOK if not.
*/
uint8_t RI_SetRegCommandParser (MCP_Handle_t * pHandle, uint16_t txSyncFreeSpace)
{
uint8_t retVal = MCP_CMD_OK;
#ifdef NULL_PTR_CHECK_REG_INT
if (MC_NULL == pHandle)
{
retVal = MCP_CMD_NOK;
}
else
{
#endif
uint16_t * dataElementID;
uint8_t * rxData = pHandle->rxBuffer;
uint8_t * txData = pHandle->txBuffer;
int16_t rxLength = pHandle->rxLength;
uint16_t size = 0U;
uint8_t accessResult;
uint16_t regID;
uint8_t typeID;
uint8_t motorID;
uint8_t (*SetRegFcts[NBR_OF_MOTORS+1])(uint16_t, uint8_t, uint8_t*, uint16_t*, int16_t) = {&RI_SetRegisterGlobal, &RI_SetRegisterMotor1};
uint8_t number_of_item =0;
pHandle->txLength = 0;
while (rxLength > 0)
{
number_of_item ++;
dataElementID = (uint16_t *) rxData;
rxLength = rxLength-MCP_ID_SIZE; // We consume 2 byte in the DataID
rxData = rxData+MCP_ID_SIZE; // Shift buffer to the next data
regID = *dataElementID & REG_MASK;
typeID = (uint8_t)*dataElementID & TYPE_MASK;
motorID = (uint8_t)((*dataElementID & MOTOR_MASK));
if (motorID > NBR_OF_MOTORS)
{
retVal = MCP_CMD_NOK;
rxLength = 0;
}
else
{
accessResult = SetRegFcts[motorID](regID, typeID, rxData, &size, rxLength);
/* Prepare next data*/
rxLength = (int16_t) (rxLength - size);
rxData = rxData+size;
/* If there is only one CMD in the buffer, we do not store the result */
if ((1U == number_of_item) && (0 == rxLength))
{
retVal = accessResult;
}
else
{/* Store the result for each access to be able to report failing access */
if (txSyncFreeSpace !=0 )
{
*txData = accessResult;
txData = txData+1;
pHandle->txLength++;
txSyncFreeSpace--; /* decrement one by one no wraparound possible */
retVal = (accessResult != MCP_CMD_OK) ? MCP_CMD_NOK : retVal;
if ((accessResult == MCP_ERROR_BAD_DATA_TYPE) || (accessResult == MCP_ERROR_BAD_RAW_FORMAT))
{ /* From this point we are not able to continue to decode CMD buffer*/
/* We stop the parsing */
rxLength = 0;
}
}
else
{
/* Stop parsing the cmd buffer as no space to answer */
/* If we reach this state, chances are high the command was badly formated or received */
rxLength = 0;
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
}
}
}
/* If all accesses are fine, just one global MCP_CMD_OK is required*/
if (MCP_CMD_OK == retVal)
{
pHandle->txLength = 0;
}
else
{
/* Nothing to do */
}
#ifdef NULL_PTR_CHECK_REG_INT
}
#endif
return (retVal);
}
/**
* @brief Parses the payload in the received packet and call the required function in order to return a value.
*
* The function called depends on the targeted motor and/or targeted register : RI_GetRegisterGlobal or RI_GetRegisterMotorX.
*
* @param pHandle Handler of the current instance of the MCP component
* @param txSyncFreeSpace Space available for synchronous transmission
*
* @retval Returns #MCP_CMD_OK if the command is acknowledged and #MCP_CMD_NOK if not.
*/
uint8_t RI_GetRegCommandParser (MCP_Handle_t * pHandle, uint16_t txSyncFreeSpace)
{
uint8_t retVal = MCP_CMD_NOK;
#ifdef NULL_PTR_CHECK_REG_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
uint16_t * dataElementID;
uint8_t * rxData = pHandle->rxBuffer;
uint8_t * txData = pHandle->txBuffer;
uint16_t size = 0U;
uint16_t rxLength = pHandle->rxLength;
int16_t freeSpaceS16 = (int16_t) txSyncFreeSpace;
uint16_t regID;
uint8_t typeID;
uint8_t motorID;
uint8_t (*GetRegFcts[NBR_OF_MOTORS+1])(uint16_t, uint8_t, uint8_t*, uint16_t*, int16_t) = {&RI_GetRegisterGlobal, &RI_GetRegisterMotor1};
pHandle->txLength = 0;
while (rxLength > 0U)
{
dataElementID = (uint16_t *) rxData;
rxLength = rxLength - MCP_ID_SIZE;
rxData = rxData + MCP_ID_SIZE; // Shift buffer to the next MCP_ID
regID = *dataElementID & REG_MASK;
typeID = (uint8_t)*dataElementID & TYPE_MASK;
motorID = (uint8_t)((*dataElementID & MOTOR_MASK));
if (motorID > NBR_OF_MOTORS)
{
retVal = MCP_CMD_NOK;
rxLength = 0;
}
else
{
retVal = GetRegFcts[motorID](regID, typeID, txData, &size, freeSpaceS16);
if (retVal == MCP_CMD_OK )
{
/* Prepare next data */
txData = txData+size;
pHandle->txLength += size;
freeSpaceS16 = freeSpaceS16-size;
}
else
{
rxLength = 0;
}
}
}
#ifdef NULL_PTR_CHECK_REG_INT
}
#endif
return (retVal);
}
/**
* @brief Parses the header from the received packet and call the required function depending on the command sent by the controller device.
*
* @param pHandle Handler of the current instance of the MCP component
*/
void MCP_ReceivedPacket(MCP_Handle_t *pHandle)
{
const uint16_t *packetHeader;
uint16_t command;
int16_t txSyncFreeSpace;
uint8_t motorID;
uint8_t MCPResponse;
uint8_t userCommand=0;
#ifdef NULL_PTR_CHECK_MCP
if ((MC_NULL == pHandle) || (0U == pHandle->rxLength))
{
/* Nothing to do, txBuffer and txLength have not been modified */
}
else /* Length is 0, this is a request to send back the last packet */
{
#endif
packetHeader = (uint16_t *)pHandle->rxBuffer; //cstat !MISRAC2012-Rule-11.3
command = (uint16_t)(*packetHeader & CMD_MASK);
if ((command & MCP_USER_CMD_MASK) == MCP_USER_CMD)
{
userCommand = ((uint8_t)(command & 0xF8U) >> 3U);
command = MCP_USER_CMD;
}
else
{
/* Nothing to do */
}
motorID = (uint8_t)((*packetHeader - 1U) & MOTOR_MASK);
MCI_Handle_t *pMCI = &Mci[motorID];
/* Removing MCP Header from RxBuffer */
pHandle->rxLength = pHandle->rxLength - MCP_HEADER_SIZE;
pHandle->rxBuffer = pHandle->rxBuffer + MCP_HEADER_SIZE;
/* Commands requiering payload response must be aware of space available for the payload */
/* Last byte is reserved for MCP response*/
txSyncFreeSpace = (int16_t)pHandle->pTransportLayer->txSyncMaxPayload - 1;
/* Initialization of the tx length, command which send back data has to increment the txLength
* (case of Read register) */
pHandle->txLength = 0U;
switch (command)
{
case GET_MCP_VERSION:
{
pHandle->txLength = 4U;
*pHandle->txBuffer = MCP_VERSION;
MCPResponse = MCP_CMD_OK;
break;
}
case SET_DATA_ELEMENT:
{
MCPResponse = RI_SetRegCommandParser(pHandle, (uint16_t)txSyncFreeSpace);
break;
}
case GET_DATA_ELEMENT:
{
MCPResponse = RI_GetRegCommandParser(pHandle, (uint16_t)txSyncFreeSpace);
break;
}
case START_MOTOR:
{
MCPResponse = (MCI_StartWithPolarizationMotor(pMCI) == false) ? MCP_CMD_OK : MCP_CMD_NOK;
break;
}
case STOP_MOTOR: /* Todo: Check the pertinance of return value */
{
(void)MCI_StopMotor(pMCI);
MCPResponse = MCP_CMD_OK;
break;
}
case STOP_RAMP:
{
if (RUN == MCI_GetSTMState(pMCI))
{
MCI_StopRamp(pMCI);
}
else
{
/* Nothing to do */
}
MCPResponse = MCP_CMD_OK;
break;
}
case START_STOP:
{
/* Queries the STM and a command start or stop depending on the state */
if (IDLE == MCI_GetSTMState(pMCI))
{
MCPResponse = (MCI_StartWithPolarizationMotor(pMCI) == true) ? MCP_CMD_OK : MCP_CMD_NOK;
}
else
{
(void)MCI_StopMotor(pMCI);
MCPResponse = MCP_CMD_OK;
}
break;
}
case FAULT_ACK:
{
(void)MCI_FaultAcknowledged(pMCI);
MCPResponse = MCP_CMD_OK;
break;
}
case IQDREF_CLEAR:
{
MCI_Clear_Iqdref(pMCI);
MCPResponse = MCP_CMD_OK;
break;
}
case PFC_ENABLE:
case PFC_DISABLE:
case PFC_FAULT_ACK:
{
MCPResponse = MCP_CMD_UNKNOWN;
break;
}
case PROFILER_CMD:
{
MCPResponse = MC_ProfilerCommand(pHandle->rxLength, pHandle->rxBuffer, txSyncFreeSpace, &pHandle->txLength,
pHandle->txBuffer);
break;
}
case MCP_USER_CMD:
{
if ((userCommand < MCP_USER_CALLBACK_MAX) && (MCP_UserCallBack[userCommand] != NULL))
{
MCPResponse = MCP_UserCallBack[userCommand](pHandle->rxLength, pHandle->rxBuffer, txSyncFreeSpace,
&pHandle->txLength, pHandle->txBuffer);
}
else
{
MCPResponse = MCP_ERROR_CALLBACK_NOT_REGISTRED;
}
break;
}
default :
{
MCPResponse = MCP_CMD_UNKNOWN;
break;
}
}
pHandle->txBuffer[pHandle->txLength] = MCPResponse;
pHandle->txLength++;
#ifdef NULL_PTR_CHECK_MCP
}
#endif
}
/**
* @brief Stores user's MCP function to be later called as MCP function.
*
* @param callBackID: ID used to get to the stored @p fctCB function
* @param fctCB: User call back function structure
*
* @retval Returns #MCP_CMD_OK if the command is acknowledged and #MCP_CMD_NOK if not
*/
uint8_t MCP_RegisterCallBack (uint8_t callBackID, MCP_user_cb_t fctCB)
{
uint8_t result;
if (callBackID < MCP_USER_CALLBACK_MAX)
{
MCP_UserCallBack[callBackID] = fctCB;
result = MCP_CMD_OK;
}
else
{
result = MCP_CMD_NOK;
}
return (result);
}
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 11,873 |
C
| 27.004717 | 141 | 0.583677 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/regular_conversion_manager.c
|
/**
******************************************************************************
* @file regular_conversion_manager.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides firmware functions that implement the following features
* of the regular_conversion_manager component of the Motor Control SDK:
* Register conversion with or without callback
* Execute regular conv directly from Temperature and VBus sensors
* Execute user regular conversion scheduled by medium frequency task
* Manage user conversion state machine
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
#include "regular_conversion_manager.h"
#include "mc_config.h"
/** @addtogroup MCSDK
* @{
*/
/** @defgroup RCM Regular Conversion Manager
* @brief Regular Conversion Manager component of the Motor Control SDK
*
* MotorControl SDK makes an extensive usage of ADCs. Some conversions are timing critical
* like current reading, and some have less constraints. If an ADC offers both Injected and Regular,
* channels, critical conversions will be systematically done on Injected channels, because they
* interrupt any ongoing regular conversion so as to be executed without delay.
* Others conversions, mainly Bus voltage, and Temperature sensing are performed with regular channels.
* If users wants to perform ADC conversions with an ADC already used by MC SDK, they must use regular
* conversions. It is forbidden to use Injected channel on an ADC that is already in use for current reading.
* As usera and MC-SDK may share ADC regular scheduler, this component intents to manage all the
* regular conversions.
*
* If users wants to execute their own conversion, they first have to register it through the
* RCM_RegisterRegConv_WithCB() or RCM_RegisterRegConv() APIs. Multiple conversions can be registered,
* but only one can be scheduled at a time .
*
* A requested user regular conversion will be executed by the medium frequency task after the
* MC-SDK regular safety conversions: Bus voltage and Temperature.
*
* If a callback is registered, particular care must be taken with the code executed inside the CB.
* The callback code is executed under Medium frequency task IRQ context (Systick).
*
* If the Users do not register a callback, they must poll the RCM state machine to know if
* a conversion is ready to be read, scheduled, or free to be scheduled. This is performed through
* the RCM_GetUserConvState() API.
*
* If the state is #RCM_USERCONV_IDLE, a conversion is ready to be scheduled.
* if a conversion is already scheduled, the returned value is #RCM_USERCONV_REQUESTED.
* if a conversion is ready to be read, the returned value is #RCM_USERCONV_EOC.
* In #RCM_USERCONV_EOC state, a call to RCM_GetUserConv will consume the value, and set the state machine back
* to #RCM_USERCONV_IDLE state. It implies that a second call without new conversion performed,
* will send back 0xffff which is an error value meaning that the data is not available.
* If a conversion request is executed, but the previous conversion has not been completed, nor consumed,
* the request is discarded and the RCM_RequestUserConv() return false.
*
* If a callback is registered, the data read is sent back to the callback parameters, and therefor consumed.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/**
* @brief Document as stated in template.h
*
* ...
*/
typedef enum
{
notvalid,
ongoing,
valid
} RCM_status_t;
typedef struct
{
bool enable;
RCM_status_t status;
uint16_t value;
uint8_t prev;
uint8_t next;
} RCM_NoInj_t;
typedef struct
{
RCM_exec_cb_t cb;
void *data;
} RCM_callback_t;
/* Private defines -----------------------------------------------------------*/
/**
* @brief Number of regular conversion allowed By default.
*
* In single drive configuration, it is defined to 4. 2 of them are consumed by
* Bus voltage and temperature reading. This leaves 2 handles available for
* user conversions
*
* In dual drives configuration, it is defined to 6. 2 of them are consumed by
* Bus voltage and temperature reading for each motor. This leaves 2 handles
* available for user conversion.
*
* Defined to 4 here.
*/
#define RCM_MAX_CONV 4U
/* Global variables ----------------------------------------------------------*/
static RegConv_t *RCM_handle_array[RCM_MAX_CONV];
static RCM_callback_t RCM_CB_array[RCM_MAX_CONV];
static RCM_NoInj_t RCM_NoInj_array[RCM_MAX_CONV];
static uint8_t RCM_currentHandle;
static uint16_t RCM_UserConvValue;
static RCM_UserConvState_t RCM_UserConvState;
static RegConv_t* RCM_UserConvHandle;
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
* @brief Registers a regular conversion, and attaches a callback.
*
* This function registers a regular ADC conversion that can be later scheduled for execution. It
* returns a handle that uniquely identifies the conversion. This handle is used in the other API
* of the Regular Converion Manager to reference the registered conversion.
*
* A regular conversion is defined by an ADC + ADC channel pair. If a registration already exists
* for the requested ADC + ADC channel pair, the same handle will be reused.
*
* The regular conversion is registered along with a callback that is executed each time the
* conversion has completed. The callback is invoked with two parameters:
*
* - the handle of the regular conversion
* - a data pointer, supplied by uthe users at registration time.
*
* The registration may fail if there is no space left for additional conversions. The
* maximum number of regular conversion that can be registered is defined by #RCM_MAX_CONV.
*
* @note Users who do not want a callback to be executed at the end of the conversion,
* should use RCM_RegisterRegConv() instead.
*
* @param regConv Pointer to the regular conversion parameters.
* Contains ADC, Channel and sampling time to be used.
*
* @param fctCB Function called once the regular conversion is executed.
*
* @param Data Used to save a user context. this parameter will be send back by
* the fctCB function. @b Note: This parameter can be NULL if not used.
*
*/
void RCM_RegisterRegConv_WithCB (RegConv_t *regConv, RCM_exec_cb_t fctCB, void *data)
{
RCM_RegisterRegConv(regConv);
if (regConv->convHandle < RCM_MAX_CONV)
{
RCM_CB_array [regConv->convHandle].cb = fctCB;
RCM_CB_array [regConv->convHandle].data = data;
}
else
{
/* Nothing to do */
}
}
/**
* @brief Registers a regular conversion.
*
* This function registers a regular ADC conversion that can be later scheduled for execution. It
* returns a handle that uniquely identifies the conversion. This handle is used in the other API
* of the Regular Converion Manager to reference the registered conversion.
*
* A regular conversion is defined by an ADC + ADC channel pair. If a registration already exists
* for the requested ADC + ADC channel pair, the same handle will be reused.
*
* The registration may fail if there is no space left for additional conversions. The
* maximum number of regular conversion that can be registered is defined by #RCM_MAX_CONV.
*
* @note Users who do not want a callback to be executed at the end of the conversion,
* should use RCM_RegisterRegConv() instead.
*
* @param regConv Pointer to the regular conversion parameters.
* Contains ADC, Channel and sampling time to be used.
*
*/
void RCM_RegisterRegConv(RegConv_t *regConv)
{
uint8_t handle = 255U;
#ifdef NULL_PTR_CHECK_REG_CON_MNG
if (MC_NULL == regConv)
{
handle = 0U;
}
else
{
#endif
uint8_t i = 0;
/* Parse the array to be sure that same
* conversion does not already exist*/
while (i < RCM_MAX_CONV)
{
if ((0 == RCM_handle_array [i]) && (handle > RCM_MAX_CONV))
{
handle = i; /* First location available, but still looping to check that this config does not already exist */
}
else
{
/* Nothing to do */
}
/* Ticket 64042 : If RCM_handle_array [i] is null access to data member will cause Memory Fault */
if (RCM_handle_array [i] != 0)
{
if ((RCM_handle_array [i]->channel == regConv->channel)
&& (RCM_handle_array [i]->regADC == regConv->regADC))
{
handle = i; /* Reuse the same handle */
i = RCM_MAX_CONV; /* We can skip the rest of the loop */
}
else
{
/* Nothing to do */
}
}
else
{
/* Nothing to do */
}
i++;
}
if (handle < RCM_MAX_CONV)
{
RCM_handle_array [handle] = regConv;
RCM_CB_array [handle].cb = NULL; /* If a previous callback was attached, it is cleared */
if (0U == LL_ADC_IsEnabled(regConv->regADC))
{
LL_ADC_DisableIT_EOC(regConv->regADC);
LL_ADC_ClearFlag_EOC(regConv->regADC);
LL_ADC_DisableIT_JEOC(regConv->regADC);
LL_ADC_ClearFlag_JEOC(regConv->regADC);
LL_ADC_StartCalibration(regConv->regADC, LL_ADC_SINGLE_ENDED);
while (1U == LL_ADC_IsCalibrationOnGoing(regConv->regADC))
{
/* Nothing to do */
}
/* ADC Enable (must be done after calibration) */
/* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0
* following a calibration phase, could have no effect on ADC
* within certain AHB/ADC clock ratio
*/
while (0U == LL_ADC_IsActiveFlag_ADRDY(regConv->regADC))
{
LL_ADC_Enable(regConv->regADC);
}
}
else
{
/* Nothing to do */
}
/* Conversion handler is created, will be enabled by the first call to RCM_ExecRegularConv */
RCM_NoInj_array[handle].enable = false;
RCM_NoInj_array[handle].next = handle;
RCM_NoInj_array[handle].prev = handle;
/* Reset regular conversion sequencer length set by cubeMX */
LL_ADC_REG_SetSequencerLength(regConv->regADC, LL_ADC_REG_SEQ_SCAN_DISABLE);
/* Configure the sampling time (should already be configured by for non user conversions) */
LL_ADC_SetChannelSamplingTime(regConv->regADC, __LL_ADC_DECIMAL_NB_TO_CHANNEL(regConv->channel),
regConv->samplingTime);
}
else
{
/* Nothing to do handle is already set to error value : 255 */
}
#ifdef NULL_PTR_CHECK_REG_CON_MNG
}
#endif
regConv->convHandle = handle;
}
/*
* This function is used to read the result of a regular conversion.
* Depending of the MC state machine, this function can poll on the ADC end of conversion or not.
* If the ADC is already in use for currents sensing, the regular conversion can not
* be executed instantaneously but have to be scheduled in order to be executed after currents sensing
* inside HF task.
* This function takes care of inserting the handle into the scheduler.
* If it is possible to execute the conversion instantaneously, it will be executed, and result returned.
* Otherwise, the latest stored conversion result will be returned.
*
* NOTE: This function is not part of the public API and users should not call it.
*/
uint16_t RCM_ExecRegularConv (RegConv_t *regConv)
{
uint16_t retVal;
uint8_t handle = regConv->convHandle;
uint8_t formerNext;
uint8_t i=0;
uint8_t LastEnable = RCM_MAX_CONV;
if (false == RCM_NoInj_array [handle].enable)
{
/* Find position in the list */
while (i < RCM_MAX_CONV)
{
if (true == RCM_NoInj_array [i].enable)
{
if (RCM_NoInj_array[i].next > handle)
/* We found a previous reg conv to link with */
{
formerNext = RCM_NoInj_array [i].next;
RCM_NoInj_array[handle].next = formerNext;
RCM_NoInj_array[handle].prev = i;
RCM_NoInj_array[i].next = handle;
RCM_NoInj_array[formerNext].prev = handle;
i = RCM_MAX_CONV; /* Stop the loop, handler inserted */
}
else
{ /* We found an enabled regular conv,
* but do not know yet if it is the one we have to be linked to */
LastEnable = i;
}
}
else
{
/* Nothing to do */
}
i++;
if (RCM_MAX_CONV == i)
/* We reach end of the array without handler inserted */
{
if (LastEnable != RCM_MAX_CONV )
/* We find a regular conversion with smaller position to be linked with */
{
formerNext = RCM_NoInj_array[LastEnable].next;
RCM_NoInj_array[handle].next = formerNext;
RCM_NoInj_array[handle].prev = LastEnable;
RCM_NoInj_array[LastEnable].next = handle;
RCM_NoInj_array[formerNext].prev = handle;
}
else
{ /* The current handle is the only one in the list */
/* Previous and next are already pointing to itself (done at registerRegConv) */
RCM_currentHandle = handle;
}
}
else
{
/* Nothing to do we are parsing the array, nothing inserted yet */
}
}
/* The handle is now linked with others, we can set the enable flag */
RCM_NoInj_array[handle].enable = true;
RCM_NoInj_array[handle].status = notvalid;
if (RCM_NoInj_array[RCM_currentHandle].status != ongoing)
{/* Select the new conversion to be the next scheduled only if a conversion is not ongoing */
RCM_currentHandle = handle;
}
else
{
/* Nothing to do */
}
}
else
{
/* Nothing to do the current handle is already scheduled */
}
if (false == PWM_Handle_M1.ADCRegularLocked)
/* The ADC is free to be used asynchronously */
{
LL_ADC_REG_SetSequencerRanks(RCM_handle_array[handle]->regADC,
LL_ADC_REG_RANK_1,
__LL_ADC_DECIMAL_NB_TO_CHANNEL(RCM_handle_array[handle]->channel));
(void)LL_ADC_REG_ReadConversionData12(RCM_handle_array[handle]->regADC);
/* Start ADC conversion */
LL_ADC_REG_StartConversion(RCM_handle_array[handle]->regADC);
/* Wait EOC */
while ( 0U == LL_ADC_IsActiveFlag_EOC(RCM_handle_array[handle]->regADC))
{
/* Nothing to do */
}
/* Read the "Regular" conversion (Not related to current sampling) */
RCM_NoInj_array[handle].value = LL_ADC_REG_ReadConversionData12(RCM_handle_array[handle]->regADC);
RCM_currentHandle = RCM_NoInj_array[handle].next;
RCM_NoInj_array[handle].status = valid;
}
else
{
/* Nothing to do */
}
retVal = RCM_NoInj_array[handle].value;
return (retVal);
}
/**
* @brief Schedules a regular conversion for execution.
*
* This function requests the execution of the user-defined regular conversion identified
* by @p handle. All user defined conversion requests must be performed inside routines with the
* same priority level. If a previous regular conversion request is pending this function has no
* effect, for this reason is better to call RCM_GetUserConvState() and check if the state is
* #RCM_USERCONV_IDLE before calling RCM_RequestUserConv().
*
* @param handle used for the user conversion.
*
* @return True if the regular conversion could be scheduled and false otherwise.
*/
bool RCM_RequestUserConv(RegConv_t *regConv)
{
bool retVal = false;
if (RCM_USERCONV_IDLE == RCM_UserConvState)
{
RCM_UserConvHandle = regConv;
/* must be done last so that RCM_UserConvHandle already has the right value */
RCM_UserConvState = RCM_USERCONV_REQUESTED;
retVal = true;
}
else
{
/* Nothing to do */
}
return (retVal);
}
/**
* @brief Returns the last user-defined regular conversion that was executed.
*
* This function returns a valid result if the state returned by
* RCM_GetUserConvState is #RCM_USERCONV_EOC.
*
* @retval uint16_t The converted value or 0xFFFF in case of conversion error.
*/
uint16_t RCM_GetUserConv(void)
{
uint16_t hRetVal = 0xFFFFu;
if (RCM_USERCONV_EOC == RCM_UserConvState)
{
hRetVal = RCM_UserConvValue;
RCM_UserConvState = RCM_USERCONV_IDLE;
}
else
{
/* Nothing to do */
}
return (hRetVal);
}
/*
* This function must be scheduled by mc_task.
* It executes the current user conversion that has been selected by the
* latest call to RCM_RequestUserConv.
*
* NOTE: This function is not part of the public API and users should not call it.
*/
void RCM_ExecUserConv()
{
uint8_t handle;
if (RCM_UserConvHandle != NULL)
{
handle = RCM_UserConvHandle->convHandle;
if (RCM_USERCONV_REQUESTED == RCM_UserConvState)
{
RCM_UserConvValue = RCM_ExecRegularConv(RCM_UserConvHandle);
/* Regular conversion is read from RCM_NoInj_array but we must take care that first conversion is done */
/* Status could also be ongoing, but decision is taken to provide previous conversion
* instead of waiting for RCM_NoInj_array [handle].status == valid */
if (RCM_NoInj_array [handle].status != notvalid)
{
RCM_UserConvState = RCM_USERCONV_EOC;
}
else
{
/* Nothing to do */
}
if (RCM_CB_array[handle].cb != NULL)
{
RCM_UserConvState = RCM_USERCONV_IDLE;
RCM_CB_array[handle].cb(RCM_UserConvHandle, RCM_UserConvValue,
RCM_CB_array[handle].data);
}
else
{
/* Nothing to do */
}
}
}
else
{
/* Nothing to do */
}
}
/**
* @brief Returns the status of the last requested regular conversion.
*
* It can be one of the following values:
* - UDRC_STATE_IDLE no regular conversion request pending.
* - UDRC_STATE_REQUESTED regular conversion has been requested and not completed.
* - UDRC_STATE_EOC regular conversion has been completed but not readed from the user.
*
* @retval The state of the last user-defined regular conversion.
*/
RCM_UserConvState_t RCM_GetUserConvState(void)
{
return (RCM_UserConvState);
}
/**
* @brief Un-schedules a regular conversion
*
* This function does not poll ADC read and is meant to be used when
* ADCs do not support injected channels.
*
* In such configurations, once a regular conversion has been executed once,
* It is continuously scheduled in HF task after current reading.
*
* This function remove the handle from the scheduling.
*
* @note Note that even though, in such configurations, regular conversions are
* continuously scheduled after having been requested once, the results of
* subsequent conversions are not made available unless the users invoke
* RCM_RequestUserConv() again.
*
*/
bool RCM_PauseRegularConv(RegConv_t *regConv)
{
bool retVal;
uint8_t Prev;
uint8_t Next;
uint8_t handle = regConv->convHandle;
if (handle < RCM_MAX_CONV)
{
retVal = true;
if (true == RCM_NoInj_array [handle].enable)
{
RCM_NoInj_array [handle].enable = false;
RCM_NoInj_array [handle].status = notvalid;
Prev = RCM_NoInj_array [handle].prev;
Next = RCM_NoInj_array [handle].next;
RCM_NoInj_array [Prev].next = RCM_NoInj_array [handle].next;
RCM_NoInj_array [Next].prev = RCM_NoInj_array [handle].prev;
}
else
{
/* Nothing to do */
}
}
else
{
retVal = false;
}
return (retVal);
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__((section (".ccmram")))
#endif
#endif
/*
* Starts the next scheduled regular conversion
*
* This function does not poll on ADC read and is foreseen to be used inside
* high frequency task where ADC are shared between currents reading
* and user conversion.
*
* NOTE: This function is not part of the public API and users should not call it.
*/
void RCM_ExecNextConv(void)
{
if (true == RCM_NoInj_array [RCM_currentHandle].enable)
{
/* When this function is called, the ADC conversions triggered by External
event for current reading has been completed.
ADC is therefore ready to be started because already stopped */
/* Clear EOC */
LL_ADC_ClearFlag_EOC(RCM_handle_array[RCM_currentHandle]->regADC);
LL_ADC_REG_SetSequencerRanks(RCM_handle_array[RCM_currentHandle]->regADC,
LL_ADC_REG_RANK_1,
__LL_ADC_DECIMAL_NB_TO_CHANNEL(RCM_handle_array[RCM_currentHandle]->channel));
(void)LL_ADC_REG_ReadConversionData12(RCM_handle_array[RCM_currentHandle]->regADC);
/* Start ADC for regular conversion */
LL_ADC_REG_StartConversion(RCM_handle_array[RCM_currentHandle]->regADC);
RCM_NoInj_array[RCM_currentHandle].status = ongoing;
}
else
{
/* Nothing to do, conversion not enabled have already notvalid status */
}
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__((section (".ccmram")))
#endif
#endif
/*
* Reads the result of the ongoing regular conversion
*
* This function is foreseen to be used inside
* high frequency task where ADC are shared between current reading
* and user conversion.
*
* NOTE: This function is not part of the public API and users should not call it.
*/
void RCM_ReadOngoingConv(void)
{
uint32_t result;
RCM_status_t status;
status = RCM_NoInj_array[RCM_currentHandle].status;
result = LL_ADC_IsActiveFlag_EOC(RCM_handle_array[RCM_currentHandle]->regADC);
if (( valid == status ) || ( notvalid == status ) || ( 0U == result ))
{
/* Nothing to do */
}
else
{
/* Reading of ADC Converted Value */
RCM_NoInj_array[RCM_currentHandle].value
= LL_ADC_REG_ReadConversionData12(RCM_handle_array[RCM_currentHandle]->regADC);
RCM_NoInj_array[RCM_currentHandle].status = valid;
/* Restore back DMA configuration */
}
/* Prepare next conversion */
RCM_currentHandle = RCM_NoInj_array [RCM_currentHandle].next;
}
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 23,017 |
C
| 33.458084 | 118 | 0.649346 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_math.c
|
/**
******************************************************************************
* @file mc_math.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides mathematics functions useful for and specific to
* Motor Control.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "mc_math.h"
#include "mc_type.h"
/** @addtogroup MCSDK
* @{
*/
/** @defgroup MC_Math Motor Control Math functions
* @brief Motor Control Mathematic functions of the Motor Control SDK
*
* @todo Document the Motor Control Math "module".
*
* @{
*/
/* Private macro -------------------------------------------------------------*/
#define divSQRT_3 (int32_t)0x49E6 /* 1/sqrt(3) in q1.15 format=0.5773315 */
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__( ( section ( ".ccmram" ) ) )
#endif
#endif
/**
* @brief This function transforms stator values a and b (which are
* directed along axes each displaced by 120 degrees) into values
* alpha and beta in a stationary qd reference frame.
* alpha = a
* beta = -(2*b+a)/sqrt(3)
* @param Input: stator values a and b in ab_t format.
* @retval Stator values alpha and beta in alphabeta_t format.
*/
__weak alphabeta_t MCM_Clarke(ab_t Input)
{
alphabeta_t Output;
int32_t a_divSQRT3_tmp;
int32_t b_divSQRT3_tmp;
int32_t wbeta_tmp;
int16_t hbeta_tmp;
/* qIalpha = qIas*/
Output.alpha = Input.a;
a_divSQRT3_tmp = divSQRT_3 * ((int32_t)Input.a);
b_divSQRT3_tmp = divSQRT_3 * ((int32_t)Input.b);
/* qIbeta = -(2*qIbs+qIas)/sqrt(3) */
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
/* WARNING: the below instruction is not MISRA compliant, user should verify
that Cortex-M3 assembly instruction ASR (arithmetic shift right) is used by
the compiler to perform the shift (instead of LSR logical shift right) */
//cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
wbeta_tmp = (-(a_divSQRT3_tmp) - (b_divSQRT3_tmp) - (b_divSQRT3_tmp)) >> 15;
#else
wbeta_tmp = (-(a_divSQRT3_tmp) - (b_divSQRT3_tmp) - (b_divSQRT3_tmp)) / 32768;
#endif
/* Check saturation of Ibeta */
if (wbeta_tmp > INT16_MAX)
{
hbeta_tmp = INT16_MAX;
}
else if (wbeta_tmp < (-32768))
{
hbeta_tmp = ((int16_t)-32768);
}
else
{
hbeta_tmp = ((int16_t)wbeta_tmp);
}
Output.beta = hbeta_tmp;
if (((int16_t )-32768) == Output.beta)
{
Output.beta = -32767;
}
else
{
/* Nothing to do */
}
return (Output);
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__( ( section ( ".ccmram" ) ) )
#endif
#endif
/**
* @brief This function transforms stator values alpha and beta, which
* belong to a stationary qd reference frame, to a rotor flux
* synchronous reference frame (properly oriented), so as q and d.
* d= alpha *sin(theta)+ beta *cos(Theta)
* q= alpha *cos(Theta)- beta *sin(Theta)
* @param Input: stator values alpha and beta in alphabeta_t format.
* @param Theta: rotating frame angular position in q1.15 format.
* @retval Stator values q and d in qd_t format
*/
__weak qd_t MCM_Park(alphabeta_t Input, int16_t Theta)
{
qd_t Output;
int32_t d_tmp_1;
int32_t d_tmp_2;
int32_t q_tmp_1;
int32_t q_tmp_2;
int32_t wqd_tmp;
int16_t hqd_tmp;
Trig_Components Local_Vector_Components;
Local_Vector_Components = MCM_Trig_Functions(Theta);
/* No overflow guaranteed */
q_tmp_1 = Input.alpha * ((int32_t )Local_Vector_Components.hCos);
/* No overflow guaranteed */
q_tmp_2 = Input.beta * ((int32_t)Local_Vector_Components.hSin);
/* Iq component in Q1.15 Format */
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
/* WARNING: the below instruction is not MISRA compliant, user should verify
that Cortex-M3 assembly instruction ASR (arithmetic shift right) is used by
the compiler to perform the shift (instead of LSR logical shift right) */
wqd_tmp = (q_tmp_1 - q_tmp_2) >> 15; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
#else
wqd_tmp = (q_tmp_1 - q_tmp_2) / 32768;
#endif
/* Check saturation of Iq */
if (wqd_tmp > INT16_MAX)
{
hqd_tmp = INT16_MAX;
}
else if (wqd_tmp < (-32768))
{
hqd_tmp = ((int16_t)-32768);
}
else
{
hqd_tmp = ((int16_t)wqd_tmp);
}
Output.q = hqd_tmp;
if (((int16_t)-32768) == Output.q)
{
Output.q = -32767;
}
else
{
/* Nothing to do */
}
/* No overflow guaranteed */
d_tmp_1 = Input.alpha * ((int32_t )Local_Vector_Components.hSin);
/* No overflow guaranteed */
d_tmp_2 = Input.beta * ((int32_t )Local_Vector_Components.hCos);
/* Id component in Q1.15 Format */
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
/* WARNING: the below instruction is not MISRA compliant, user should verify
that Cortex-M3 assembly instruction ASR (arithmetic shift right) is used by
the compiler to perform the shift (instead of LSR logical shift right) */
wqd_tmp = (d_tmp_1 + d_tmp_2) >> 15; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
#else
wqd_tmp = (d_tmp_1 + d_tmp_2) / 32768;
#endif
/* Check saturation of Id */
if (wqd_tmp > INT16_MAX)
{
hqd_tmp = INT16_MAX;
}
else if (wqd_tmp < (-32768))
{
hqd_tmp = ((int16_t)-32768);
}
else
{
hqd_tmp = ((int16_t)wqd_tmp);
}
Output.d = hqd_tmp;
if (((int16_t)-32768) == Output.d)
{
Output.d = -32767;
}
else
{
/* Nothing to do */
}
return (Output);
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__( ( section ( ".ccmram" ) ) )
#endif
#endif
/**
* @brief This function transforms stator voltage qVq and qVd, that belong to
* a rotor flux synchronous rotating frame, to a stationary reference
* frame, so as to obtain qValpha and qVbeta:
* Valfa= Vq*Cos(theta)+ Vd*Sin(theta)
* Vbeta=-Vq*Sin(theta)+ Vd*Cos(theta)
* @param Input: stator voltage Vq and Vd in qd_t format.
* @param Theta: rotating frame angular position in q1.15 format.
* @retval Stator voltage Valpha and Vbeta in qd_t format.
*/
__weak alphabeta_t MCM_Rev_Park(qd_t Input, int16_t Theta)
{
int32_t alpha_tmp1;
int32_t alpha_tmp2;
int32_t beta_tmp1;
int32_t beta_tmp2;
Trig_Components Local_Vector_Components;
alphabeta_t Output;
Local_Vector_Components = MCM_Trig_Functions(Theta);
/* No overflow guaranteed */
alpha_tmp1 = Input.q * ((int32_t)Local_Vector_Components.hCos);
alpha_tmp2 = Input.d * ((int32_t)Local_Vector_Components.hSin);
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
/* WARNING: the below instruction is not MISRA compliant, user should verify
that Cortex-M3 assembly instruction ASR (arithmetic shift right) is used by
the compiler to perform the shift (instead of LSR logical shift right) */
//cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
Output.alpha = (int16_t)(((alpha_tmp1) + (alpha_tmp2)) >> 15);
#else
Output.alpha = (int16_t)(((alpha_tmp1) + (alpha_tmp2)) / 32768);
#endif
beta_tmp1 = Input.q * ((int32_t)Local_Vector_Components.hSin);
beta_tmp2 = Input.d * ((int32_t)Local_Vector_Components.hCos);
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
/* WARNING: the below instruction is not MISRA compliant, user should verify
that Cortex-M3 assembly instruction ASR (arithmetic shift right) is used by
the compiler to perform the shift (instead of LSR logical shift right) */
//cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
Output.beta = (int16_t)((beta_tmp2 - beta_tmp1) >> 15);
#else
Output.beta = (int16_t)((beta_tmp2 - beta_tmp1) / 32768);
#endif
return (Output);
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__( ( section ( ".ccmram" ) ) )
#endif
#endif
/**
* @brief This function returns cosine and sine functions of the angle fed in input.
* @param hAngle: angle in q1.15 format.
* @retval Sin(angle) and Cos(angle) in Trig_Components format.
*/
__weak Trig_Components MCM_Trig_Functions(int16_t hAngle)
{
/* MISRAC2012-violation Rule 19.2. The union keyword should not be used.
* If this rule is not followed, the kinds of behavior that need to be determined
* are:
* Padding — how much padding is inserted at the end of the union;
* Alignment — how are members of any structures within the union aligned;
* Endianness — is the most significant byte of a word stored at the lowest or
* highest memory address;
* Bit-order — how are bits numbered within bytes and how are bits allocated to
* bit fields.
* Low. Use of union (u32toi16x2). */
//cstat -MISRAC2012-Rule-19.2
union u32toi16x2 {
uint32_t CordicRdata;
Trig_Components Components;
} CosSin;
//cstat +MISRAC2012-Rule-19.2
/* Configure CORDIC */
/* Misra violation Rule 11.4 A�Conversion�should�not�be�performed�between�a�
* pointer�to�object and an integer type */
WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_COSINE);
/* Misra violation Rule�11.4 A�Conversion�should�not�be�performed�between�a
* pointer�to�object and an integer type */
LL_CORDIC_WriteData(CORDIC, ((uint32_t)0x7FFF0000) + ((uint32_t)hAngle));
/* Read angle */
/* Misra violation Rule�11.4 A�Conversion�should�not�be�performed between�a
* pointer�to object and an integer type */
CosSin.CordicRdata = LL_CORDIC_ReadData(CORDIC);
return (CosSin.Components); //cstat !UNION-type-punning
}
#if defined (CCMRAM)
#if defined (__ICCARM__)
#pragma location = ".ccmram"
#elif defined (__CC_ARM) || defined(__GNUC__)
__attribute__( ( section ( ".ccmram" ) ) )
#endif
#endif
/**
* @brief It calculates the square root of a non-negative int32_t. It returns 0 for negative int32_t.
* @param Input int32_t number.
* @retval int32_t Square root of Input (0 if Input<0).
*/
__weak int32_t MCM_Sqrt(int32_t wInput)
{
int32_t wtemprootnew;
if (wInput > 0)
{
uint32_t retVal;
/* Disable Irq as sqrt is used in MF and HF task */
__disable_irq();
/* Configure CORDIC */
WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_SQRT);
LL_CORDIC_WriteData(CORDIC, ((uint32_t)wInput));
/* Read sqrt and return */
#ifndef FULL_MISRA_C_COMPLIANCY_MC_MATH
retVal = (LL_CORDIC_ReadData(CORDIC)) >> 15; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6
#else
retVal = (LL_CORDIC_ReadData(CORDIC)) / 32768U;
#endif
wtemprootnew = (int32_t)retVal;
__enable_irq();
}
else
{
wtemprootnew = (int32_t)0;
}
return (wtemprootnew);
}
/**
* @brief This function codify a floating point number into the relative 32bit integer.
* @param float Floating point number to be coded.
* @retval uint32_t Coded 32bit integer.
*/
__weak uint32_t MCM_floatToIntBit( float_t x ) //cstat !MISRAC2012-Dir-4.6_a
{
const uint32_t *pInt;
pInt = (uint32_t *)(&x); //cstat !MISRAC2012-Rule-11.3
return (*pInt);
}
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 11,992 |
C
| 29.439086 | 119 | 0.625834 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_parameters.c
|
/**
******************************************************************************
* @file mc_parameters.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides definitions of HW parameters specific to the
* configuration of the subsystem.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
//cstat -MISRAC2012-Rule-21.1
#include "main.h" //cstat !MISRAC2012-Rule-21.1
//cstat +MISRAC2012-Rule-21.1
#include "parameters_conversion.h"
#include "r3_1_g4xx_pwm_curr_fdbk.h"
/* USER CODE BEGIN Additional include */
/* USER CODE END Additional include */
#define FREQ_RATIO 1 /* Dummy value for single drive */
#define FREQ_RELATION HIGHEST_FREQ /* Dummy value for single drive */
/**
* @brief Current sensor parameters Motor 1 - three shunt - G4
*/
const R3_1_Params_t R3_1_ParamsM1 =
{
/* Dual MC parameters --------------------------------------------------------*/
.FreqRatio = FREQ_RATIO,
.IsHigherFreqTim = FREQ_RELATION,
/* Current reading A/D Conversions initialization -----------------------------*/
.ADCx = ADC1,
.ADCConfig = {
(7U << ADC_JSQR_JSQ1_Pos)
| (6U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
,(1U << ADC_JSQR_JSQ1_Pos)
| (6U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
,(1U << ADC_JSQR_JSQ1_Pos)
| (6U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
,(1U << ADC_JSQR_JSQ1_Pos)
| (7U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
,(1U << ADC_JSQR_JSQ1_Pos)
| (7U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
,(7U << ADC_JSQR_JSQ1_Pos)
| (6U << ADC_JSQR_JSQ2_Pos) | 1<< ADC_JSQR_JL_Pos
| (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO & ~ADC_INJ_TRIG_EXT_EDGE_DEFAULT)
},
/* PWM generation parameters --------------------------------------------------*/
.RepetitionCounter = REP_COUNTER,
.Tafter = TW_AFTER,
.Tbefore = TW_BEFORE_R3_1,
.Tsampling = (uint16_t)SAMPLING_TIME,
.Tcase2 = (uint16_t)SAMPLING_TIME + (uint16_t)TDEAD + (uint16_t)TRISE,
.Tcase3 = ((uint16_t)TDEAD + (uint16_t)TNOISE + (uint16_t)SAMPLING_TIME)/2u,
.TIMx = TIM1,
/* Internal OPAMP common settings --------------------------------------------*/
.OPAMPParams = MC_NULL,
/* Internal COMP settings ----------------------------------------------------*/
.CompOCPASelection = MC_NULL,
.CompOCPAInvInput_MODE = NONE,
.CompOCPBSelection = MC_NULL,
.CompOCPBInvInput_MODE = NONE,
.CompOCPCSelection = MC_NULL,
.CompOCPCInvInput_MODE = NONE,
.DAC_OCP_ASelection = MC_NULL,
.DAC_OCP_BSelection = MC_NULL,
.DAC_OCP_CSelection = MC_NULL,
.DAC_Channel_OCPA = (uint32_t) 0,
.DAC_Channel_OCPB = (uint32_t) 0,
.DAC_Channel_OCPC = (uint32_t) 0,
.CompOVPSelection = MC_NULL,
.CompOVPInvInput_MODE = NONE,
.DAC_OVP_Selection = MC_NULL,
.DAC_Channel_OVP = (uint32_t) 0,
/* DAC settings --------------------------------------------------------------*/
.DAC_OCP_Threshold = 0,
.DAC_OVP_Threshold = 23830,
};
ScaleParams_t scaleParams_M1 =
{
.voltage = NOMINAL_BUS_VOLTAGE_V/(1.73205 * 32767), /* sqrt(3) = 1.73205 */
.current = CURRENT_CONV_FACTOR_INV,
.frequency = (1.15 * MAX_APPLICATION_SPEED_UNIT * U_RPM)/(32768* SPEED_UNIT)
};
/* USER CODE BEGIN Additional parameters */
/* USER CODE END Additional parameters */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 4,662 |
C
| 37.53719 | 89 | 0.510725 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/cordic.c
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file cordic.c
* @brief This file provides code for the configuration
* of the CORDIC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "cordic.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
CORDIC_HandleTypeDef hcordic;
/* CORDIC init function */
void MX_CORDIC_Init(void)
{
/* USER CODE BEGIN CORDIC_Init 0 */
/* USER CODE END CORDIC_Init 0 */
/* USER CODE BEGIN CORDIC_Init 1 */
/* USER CODE END CORDIC_Init 1 */
hcordic.Instance = CORDIC;
if (HAL_CORDIC_Init(&hcordic) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CORDIC_Init 2 */
/* USER CODE END CORDIC_Init 2 */
}
void HAL_CORDIC_MspInit(CORDIC_HandleTypeDef* cordicHandle)
{
if(cordicHandle->Instance==CORDIC)
{
/* USER CODE BEGIN CORDIC_MspInit 0 */
/* USER CODE END CORDIC_MspInit 0 */
/* CORDIC clock enable */
__HAL_RCC_CORDIC_CLK_ENABLE();
/* USER CODE BEGIN CORDIC_MspInit 1 */
/* USER CODE END CORDIC_MspInit 1 */
}
}
void HAL_CORDIC_MspDeInit(CORDIC_HandleTypeDef* cordicHandle)
{
if(cordicHandle->Instance==CORDIC)
{
/* USER CODE BEGIN CORDIC_MspDeInit 0 */
/* USER CODE END CORDIC_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_CORDIC_CLK_DISABLE();
/* USER CODE BEGIN CORDIC_MspDeInit 1 */
/* USER CODE END CORDIC_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
| 2,034 |
C
| 22.66279 | 80 | 0.549656 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/main.c
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 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.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "cordic.h"
#include "crc.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "app_x-cube-ai.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <math.h>
#include <stdint.h>
#include "network.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define VEL_SCALE 20
#define NUM_FLOATS 8
#define MAX_EFFORT 0.175 //Nm
#define TORQUE_K 0.0562 //Nm/A
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
union floatUnion {
float floatValue[NUM_FLOATS];
uint8_t bytes[NUM_FLOATS * sizeof(float)];
};
union floatUnion data;
float sin_encode, cos_encode;
float vel_scaled;
ai_float in_data1[AI_NETWORK_IN_1_SIZE];
ai_float out_data1[AI_NETWORK_OUT_1_SIZE];
ai_float out_data2[AI_NETWORK_OUT_2_SIZE];
ai_float out_data3[AI_NETWORK_OUT_3_SIZE];
volatile uint8_t data_flag;
float action;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_NVIC_Init(void);
/* USER CODE BEGIN PFP */
void convert_angle(float angle, float *sin_component, float *cos_component);
float scale_vel(float rpm);
float clip(float value, float min, float max);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
data_flag=0;
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_CORDIC_Init();
MX_TIM1_Init();
MX_TIM2_Init();
MX_USART2_UART_Init();
MX_MotorControl_Init();
MX_CRC_Init();
MX_TIM3_Init();
MX_TIM5_Init();
MX_X_CUBE_AI_Init();
/* Initialize interrupts */
MX_NVIC_Init();
/* USER CODE BEGIN 2 */
MC_StartMotor1();
// MC_ProgramSpeedRampMotor1_F(-250, 1000);
MC_ProgramTorqueRampMotor1_F(0.0, 0);
HAL_TIM_Base_Start_IT(&htim5);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
if(data_flag)
{
TIM3->CNT = 0;
HAL_TIM_Base_Start(&htim3);
float enc_mec_angle = (float)ENCODER_M1._Super.hMecAngle/65536*2*M_PI;
convert_angle(enc_mec_angle, &sin_encode, &cos_encode);
vel_scaled = scale_vel(MC_GetAverageMecSpeedMotor1_F());
in_data1[0] = sin_encode; // Sin Encoding
in_data1[1] = cos_encode; // Cosine Encoding
in_data1[2] = vel_scaled; // Velocity
MX_X_CUBE_AI_Process();
action = clip(out_data1[0], -1.0, 1.0) * MAX_EFFORT/TORQUE_K; //Result is in Amps
MC_ProgramTorqueRampMotor1_F(action, 0);
HAL_TIM_Base_Stop(&htim3);
data.floatValue[0] = out_data1[0]; // Value
data.floatValue[1] = out_data2[0]; // Mu
data.floatValue[2] = out_data3[0]; // STD
// ab_f_t m1_ab = MC_GetIabMotor1_F();
// qd_f_t m1_qd MC_GetIqdMotor1_F();
// qd_f_t m1_qdref MC_GetIqdrefMotor1_F();
// data.floatValue[0] = (float)TIM3->CNT/10000.0;
// data.floatValue[1] = MC_GetMecSpeedReferenceMotor1_F();
// data.floatValue[2] = MC_GetAverageMecSpeedMotor1_F();
// data.floatValue[3] = MC_GetTerefMotor1_F(); //electrical torque reference
// data.floatValue[4] = MC_GetAveragePowerMotor1_F();
data.floatValue[5] = sin_encode;
data.floatValue[6] = cos_encode;
data.floatValue[7] = vel_scaled;
// HAL_UART_Transmit(&huart2, data.bytes, sizeof(data.bytes), 100);
data_flag = 0;
}
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV6;
RCC_OscInitStruct.PLL.PLLN = 85;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV8;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
{
Error_Handler();
}
/** Enables the Clock Security System
*/
HAL_RCC_EnableCSS();
}
/**
* @brief NVIC Configuration.
* @retval None
*/
static void MX_NVIC_Init(void)
{
/* USART2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(USART2_IRQn, 3, 1);
HAL_NVIC_EnableIRQ(USART2_IRQn);
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 3, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* TIM1_BRK_TIM15_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM1_BRK_TIM15_IRQn, 4, 1);
HAL_NVIC_EnableIRQ(TIM1_BRK_TIM15_IRQn);
/* TIM1_UP_TIM16_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn);
/* ADC1_2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(ADC1_2_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
/* TIM2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(TIM2_IRQn, 3, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
/* EXTI15_10_IRQn interrupt configuration */
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 3, 0);
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
}
/* USER CODE BEGIN 4 */
void convert_angle(float angle, float *sin_component, float *cos_component) {
// Apply sine and cosine functions
float offset_angle = angle + M_PI;
*sin_component = sinf(offset_angle);
*cos_component = cosf(offset_angle);
}
float scale_vel(float rpm) {
return rpm * (2 * M_PI / 60) / VEL_SCALE;
}
float clip(float value, float min, float max) {
if (value < min) {
return min;
} else if (value > max) {
return max;
} else {
return value;
}
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
| 9,294 |
C
| 28.321766 | 87 | 0.603292 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_config.c
|
/**
******************************************************************************
* @file mc_config.c
* @author Motor Control SDK Team,ST Microelectronics
* @brief Motor Control Subsystem components configuration and handler structures.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044,the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
//cstat -MISRAC2012-Rule-21.1
#include "main.h" //cstat !MISRAC2012-Rule-21.1
//cstat +MISRAC2012-Rule-21.1
#include "mc_type.h"
#include "parameters_conversion.h"
#include "mc_parameters.h"
#include "mc_config.h"
/* USER CODE BEGIN Additional include */
/* USER CODE END Additional include */
#define FREQ_RATIO 1 /* Dummy value for single drive */
#define FREQ_RELATION HIGHEST_FREQ /* Dummy value for single drive */
#include "pqd_motor_power_measurement.h"
/* USER CODE BEGIN Additional define */
/* USER CODE END Additional define */
PQD_MotorPowMeas_Handle_t PQD_MotorPowMeasM1 =
{
.ConvFact = PQD_CONVERSION_FACTOR
};
/**
* @brief PI / PID Speed loop parameters Motor 1.
*/
PID_Handle_t PIDSpeedHandle_M1 =
{
.hDefKpGain = (int16_t)PID_SPEED_KP_DEFAULT,
.hDefKiGain = (int16_t)PID_SPEED_KI_DEFAULT,
.wUpperIntegralLimit = (int32_t)IQMAX * (int32_t)SP_KIDIV,
.wLowerIntegralLimit = -(int32_t)IQMAX * (int32_t)SP_KIDIV,
.hUpperOutputLimit = (int16_t)IQMAX,
.hLowerOutputLimit = -(int16_t)IQMAX,
.hKpDivisor = (uint16_t)SP_KPDIV,
.hKiDivisor = (uint16_t)SP_KIDIV,
.hKpDivisorPOW2 = (uint16_t)SP_KPDIV_LOG,
.hKiDivisorPOW2 = (uint16_t)SP_KIDIV_LOG,
.hDefKdGain = 0x0000U,
.hKdDivisor = 0x0000U,
.hKdDivisorPOW2 = 0x0000U,
};
/**
* @brief PI / PID Iq loop parameters Motor 1.
*/
PID_Handle_t PIDIqHandle_M1 =
{
.hDefKpGain = (int16_t)PID_TORQUE_KP_DEFAULT,
.hDefKiGain = (int16_t)PID_TORQUE_KI_DEFAULT,
.wUpperIntegralLimit = (int32_t)INT16_MAX * TF_KIDIV,
.wLowerIntegralLimit = (int32_t)-INT16_MAX * TF_KIDIV,
.hUpperOutputLimit = INT16_MAX,
.hLowerOutputLimit = -INT16_MAX,
.hKpDivisor = (uint16_t)TF_KPDIV,
.hKiDivisor = (uint16_t)TF_KIDIV,
.hKpDivisorPOW2 = (uint16_t)TF_KPDIV_LOG,
.hKiDivisorPOW2 = (uint16_t)TF_KIDIV_LOG,
.hDefKdGain = 0x0000U,
.hKdDivisor = 0x0000U,
.hKdDivisorPOW2 = 0x0000U,
};
/**
* @brief PI / PID Id loop parameters Motor 1.
*/
PID_Handle_t PIDIdHandle_M1 =
{
.hDefKpGain = (int16_t)PID_FLUX_KP_DEFAULT,
.hDefKiGain = (int16_t)PID_FLUX_KI_DEFAULT,
.wUpperIntegralLimit = (int32_t)INT16_MAX * TF_KIDIV,
.wLowerIntegralLimit = (int32_t)-INT16_MAX * TF_KIDIV,
.hUpperOutputLimit = INT16_MAX,
.hLowerOutputLimit = -INT16_MAX,
.hKpDivisor = (uint16_t)TF_KPDIV,
.hKiDivisor = (uint16_t)TF_KIDIV,
.hKpDivisorPOW2 = (uint16_t)TF_KPDIV_LOG,
.hKiDivisorPOW2 = (uint16_t)TF_KIDIV_LOG,
.hDefKdGain = 0x0000U,
.hKdDivisor = 0x0000U,
.hKdDivisorPOW2 = 0x0000U,
};
/**
* @brief SpeednTorque Controller parameters Motor 1.
*/
SpeednTorqCtrl_Handle_t SpeednTorqCtrlM1 =
{
.STCFrequencyHz = MEDIUM_FREQUENCY_TASK_RATE,
.MaxAppPositiveMecSpeedUnit = (uint16_t)(MAX_APPLICATION_SPEED_UNIT),
.MinAppPositiveMecSpeedUnit = (uint16_t)(MIN_APPLICATION_SPEED_UNIT),
.MaxAppNegativeMecSpeedUnit = (int16_t)(-MIN_APPLICATION_SPEED_UNIT),
.MinAppNegativeMecSpeedUnit = (int16_t)(-MAX_APPLICATION_SPEED_UNIT),
.MaxPositiveTorque = (int16_t)NOMINAL_CURRENT,
.MinNegativeTorque = -(int16_t)NOMINAL_CURRENT,
.ModeDefault = DEFAULT_CONTROL_MODE,
.MecSpeedRefUnitDefault = (int16_t)(DEFAULT_TARGET_SPEED_UNIT),
.TorqueRefDefault = (int16_t)DEFAULT_TORQUE_COMPONENT,
.IdrefDefault = (int16_t)DEFAULT_FLUX_COMPONENT,
};
/**
* @brief PWM parameters Motor 1 for one ADC.
*/
PWMC_R3_1_Handle_t PWM_Handle_M1 =
{
{
.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents,
.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointSectX,
.pFctSetOffsetCalib = &R3_1_SetOffsetCalib,
.pFctGetOffsetCalib = &R3_1_GetOffsetCalib,
.pFctSwitchOffPwm = &R3_1_SwitchOffPWM,
.pFctSwitchOnPwm = &R3_1_SwitchOnPWM,
.pFctCurrReadingCalib = &R3_1_CurrentReadingPolarization,
.pFctTurnOnLowSides = &R3_1_TurnOnLowSides,
.pFctOCPSetReferenceVoltage = MC_NULL,
.pFctRLDetectionModeEnable = &R3_1_RLDetectionModeEnable,
.pFctRLDetectionModeDisable = &R3_1_RLDetectionModeDisable,
.pFctRLDetectionModeSetDuty = &R3_1_RLDetectionModeSetDuty,
.pFctRLTurnOnLowSidesAndStart = &R3_1_RLTurnOnLowSidesAndStart,
.LowSideOutputs = (LowSideOutputsFunction_t)LOW_SIDE_SIGNALS_ENABLING,
.pwm_en_u_port = MC_NULL,
.pwm_en_u_pin = (uint16_t)0,
.pwm_en_v_port = MC_NULL,
.pwm_en_v_pin = (uint16_t)0,
.pwm_en_w_port = MC_NULL,
.pwm_en_w_pin = (uint16_t)0,
.hT_Sqrt3 = (PWM_PERIOD_CYCLES*SQRT3FACTOR)/16384u,
.Sector = 0,
.CntPhA = 0,
.CntPhB = 0,
.CntPhC = 0,
.SWerror = 0,
.TurnOnLowSidesAction = false,
.OffCalibrWaitTimeCounter = 0,
.Motor = M1,
.RLDetectionMode = false,
.SingleShuntTopology = false,
.Ia = 0,
.Ib = 0,
.Ic = 0,
.LPFIqd_const = LPF_FILT_CONST,
.DTTest = 0,
.DTCompCnt = DTCOMPCNT,
.PWMperiod = PWM_PERIOD_CYCLES,
.Ton = TON,
.Toff = TOFF,
.OverCurrentFlag = false,
.OverVoltageFlag = false,
.BrakeActionLock = false,
.driverProtectionFlag = false,
},
.PhaseAOffset = 0,
.PhaseBOffset = 0,
.PhaseCOffset = 0,
.Half_PWMPeriod = PWM_PERIOD_CYCLES / 2u,
.ADC_ExternalPolarityInjected = 0,
.PolarizationCounter = 0,
.PolarizationSector = 0,
.ADCRegularLocked = false,
.pParams_str = &R3_1_ParamsM1
};
/**
* @brief SpeedNPosition sensor parameters Motor 1 - Base Class.
*/
VirtualSpeedSensor_Handle_t VirtualSpeedSensorM1 =
{
._Super =
{
.bElToMecRatio = POLE_PAIR_NUM,
.hMaxReliableMecSpeedUnit = (uint16_t)(1.15*MAX_APPLICATION_SPEED_UNIT),
.hMinReliableMecSpeedUnit = (uint16_t)(MIN_APPLICATION_SPEED_UNIT),
.bMaximumSpeedErrorsNumber = M1_SS_MEAS_ERRORS_BEFORE_FAULTS,
.hMaxReliableMecAccelUnitP = 65535,
.hMeasurementFrequency = TF_REGULATION_RATE_SCALED,
.DPPConvFactor = DPP_CONV_FACTOR,
},
.hSpeedSamplingFreqHz = MEDIUM_FREQUENCY_TASK_RATE,
.hTransitionSteps = (int16_t)((TF_REGULATION_RATE * TRANSITION_DURATION) / 1000.0),
};
/**
* @brief SpeedNPosition sensor parameters Motor 1 - State Observer + PLL.
*/
STO_PLL_Handle_t STO_PLL_M1 =
{
._Super =
{
.bElToMecRatio = POLE_PAIR_NUM,
.SpeedUnit = SPEED_UNIT,
.hMaxReliableMecSpeedUnit = (uint16_t)(1.15 * MAX_APPLICATION_SPEED_UNIT),
.hMinReliableMecSpeedUnit = (uint16_t)(MIN_APPLICATION_SPEED_UNIT),
.bMaximumSpeedErrorsNumber = M1_SS_MEAS_ERRORS_BEFORE_FAULTS,
.hMaxReliableMecAccelUnitP = 65535,
.hMeasurementFrequency = TF_REGULATION_RATE_SCALED,
.DPPConvFactor = DPP_CONV_FACTOR,
},
.hC1 = C1,
.hC2 = C2,
.hC3 = C3,
.hC4 = C4,
.hC5 = C5,
.hF1 = F1,
.hF2 = F2,
.PIRegulator =
{
.hDefKpGain = PLL_KP_GAIN,
.hDefKiGain = PLL_KI_GAIN,
.hDefKdGain = 0x0000U,
.hKpDivisor = PLL_KPDIV,
.hKiDivisor = PLL_KIDIV,
.hKdDivisor = 0x0000U,
.wUpperIntegralLimit = INT32_MAX,
.wLowerIntegralLimit = -INT32_MAX,
.hUpperOutputLimit = INT16_MAX,
.hLowerOutputLimit = -INT16_MAX,
.hKpDivisorPOW2 = PLL_KPDIV_LOG,
.hKiDivisorPOW2 = PLL_KIDIV_LOG,
.hKdDivisorPOW2 = 0x0000U,
},
.SpeedBufferSizeUnit = STO_FIFO_DEPTH_UNIT,
.SpeedBufferSizeDpp = STO_FIFO_DEPTH_DPP,
.VariancePercentage = PERCENTAGE_FACTOR,
.SpeedValidationBand_H = SPEED_BAND_UPPER_LIMIT,
.SpeedValidationBand_L = SPEED_BAND_LOWER_LIMIT,
.MinStartUpValidSpeed = OBS_MINIMUM_SPEED_UNIT,
.StartUpConsistThreshold = NB_CONSECUTIVE_TESTS,
.Reliability_hysteresys = M1_SS_MEAS_ERRORS_BEFORE_FAULTS,
.BemfConsistencyCheck = M1_BEMF_CONSISTENCY_TOL,
.BemfConsistencyGain = M1_BEMF_CONSISTENCY_GAIN,
.MaxAppPositiveMecSpeedUnit = (uint16_t)(MAX_APPLICATION_SPEED_UNIT * 1.15),
.F1LOG = F1_LOG,
.F2LOG = F2_LOG,
.SpeedBufferSizeDppLOG = STO_FIFO_DEPTH_DPP_LOG,
.hForcedDirection = 0x0000U
};
/**
* @brief SpeedNPosition sensor parameters Motor 1 - Encoder.
*/
ENCODER_Handle_t ENCODER_M1 =
{
._Super =
{
.bElToMecRatio = POLE_PAIR_NUM,
.hMaxReliableMecSpeedUnit = (uint16_t)(1.15 * MAX_APPLICATION_SPEED_UNIT),
.hMinReliableMecSpeedUnit = (uint16_t)(MIN_APPLICATION_SPEED_UNIT),
.bMaximumSpeedErrorsNumber = M1_SS_MEAS_ERRORS_BEFORE_FAULTS,
.hMaxReliableMecAccelUnitP = 65535,
.hMeasurementFrequency = TF_REGULATION_RATE_SCALED,
.DPPConvFactor = DPP_CONV_FACTOR,
},
.PulseNumber = M1_ENCODER_PPR * 4,
.SpeedSamplingFreqHz = MEDIUM_FREQUENCY_TASK_RATE,
.SpeedBufferSize = ENC_AVERAGING_FIFO_DEPTH,
.TIMx = TIM2,
.ICx_Filter = M1_ENC_IC_FILTER_LL,
};
/**
* @brief Encoder Alignment Controller parameters Motor 1.
*/
EncAlign_Handle_t EncAlignCtrlM1 =
{
.hEACFrequencyHz = MEDIUM_FREQUENCY_TASK_RATE,
.hFinalTorque = FINAL_I_ALIGNMENT,
.hElAngle = ALIGNMENT_ANGLE_S16,
.hDurationms = M1_ALIGNMENT_DURATION,
.bElToMecRatio = POLE_PAIR_NUM,
};
/**
* Virtual temperature sensor parameters Motor 1.
*/
NTC_Handle_t TempSensor_M1 =
{
.bSensorType = VIRTUAL_SENSOR,
.hExpectedTemp_d = 555,
.hExpectedTemp_C = M1_VIRTUAL_HEAT_SINK_TEMPERATURE_VALUE,
};
/* Bus voltage sensor value filter buffer */
static uint16_t RealBusVoltageSensorFilterBufferM1[M1_VBUS_SW_FILTER_BW_FACTOR];
/**
* Bus voltage sensor parameters Motor 1.
*/
RegConv_t VbusRegConv_M1 =
{
.regADC = ADC1,
.channel = MC_ADC_CHANNEL_2,
.samplingTime = M1_VBUS_SAMPLING_TIME,
};
RDivider_Handle_t BusVoltageSensor_M1 =
{
._Super =
{
.SensorType = REAL_SENSOR,
.ConversionFactor = (uint16_t)(ADC_REFERENCE_VOLTAGE / VBUS_PARTITIONING_FACTOR),
},
.LowPassFilterBW = M1_VBUS_SW_FILTER_BW_FACTOR,
.OverVoltageThreshold = OVERVOLTAGE_THRESHOLD_d,
.OverVoltageThresholdLow = OVERVOLTAGE_THRESHOLD_d,
.OverVoltageHysteresisUpDir = true,
.UnderVoltageThreshold = UNDERVOLTAGE_THRESHOLD_d,
.aBuffer = RealBusVoltageSensorFilterBufferM1,
};
/** RAMP for Motor1
*
*/
RampExtMngr_Handle_t RampExtMngrHFParamsM1 =
{
.FrequencyHz = TF_REGULATION_RATE
};
/**
* @brief CircleLimitation Component parameters Motor 1 - Base Component.
*/
CircleLimitation_Handle_t CircleLimitationM1 =
{
.MaxModule = MAX_MODULE,
.MaxVd = (uint16_t)((MAX_MODULE * 950) / 1000),
};
MCI_Handle_t Mci[NBR_OF_MOTORS];
SpeednTorqCtrl_Handle_t *pSTC[NBR_OF_MOTORS] = {&SpeednTorqCtrlM1};
NTC_Handle_t *pTemperatureSensor[NBR_OF_MOTORS] = {&TempSensor_M1};
PID_Handle_t *pPIDIq[NBR_OF_MOTORS] = {&PIDIqHandle_M1};
PID_Handle_t *pPIDId[NBR_OF_MOTORS] = {&PIDIdHandle_M1};
PQD_MotorPowMeas_Handle_t *pMPM[NBR_OF_MOTORS] = {&PQD_MotorPowMeasM1};
/* USER CODE BEGIN Additional configuration */
/* USER CODE END Additional configuration */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 13,057 |
C
| 34.387534 | 96 | 0.592479 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/network_data_params.c
|
/**
******************************************************************************
* @file network_data_params.c
* @author AST Embedded Analytics Research Platform
* @date Tue Jan 16 16:02:48 2024
* @brief AI Tool Automatic Code Generator for Embedded NN computing
******************************************************************************
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
******************************************************************************
*/
#include "network_data_params.h"
/** Activations Section ****************************************************/
ai_handle g_network_activations_table[1 + 2] = {
AI_HANDLE_PTR(AI_MAGIC_MARKER),
AI_HANDLE_PTR(NULL),
AI_HANDLE_PTR(AI_MAGIC_MARKER),
};
/** Weights Section ********************************************************/
AI_ALIGNED(32)
const ai_u64 s_network_weights_array_u64[5605] = {
0xc0202e8bU, 0x3f117e3b3ec19bebU, 0x3c9a901b3ec14b1fU, 0xbc8856913f3b0461U,
0xbe94180b3e8414b0U, 0xbeeb643c3d6095bdU, 0x3f2e4bf23e7871c5U, 0x3ea6017abedadf73U,
0x3e4f562d3e90781dU, 0x3ebf8245bcb225d8U, 0x3e3a7ebabdd261adU, 0xbe7c42593de9e913U,
0xbf139e6e3e09e884U, 0xbcf60b073e4509ecU, 0xbeb25e2e3f2f2d00U, 0xbe9d74d33cfd8a5bU,
0x3e09fa80be92c91fU, 0x3f2db3cebf444a02U, 0x3f96bed5be1f9e18U, 0xbd222a3b3eb01365U,
0xbceec9553f58a236U, 0x3e469b7b3e8a318cU, 0x3d4c20dabe254a44U, 0x3b3f71c0beb3a3eaU,
0x3f3fceeb3ee76468U, 0x3e3a1ad5be0a1f83U, 0x3d4ba7663dac2926U, 0xbf151402bea21908U,
0xbe4142183e4940f8U, 0x3db0c2553f38d3f9U, 0x3eb9d7173e34b9dbU, 0x3e997d293e09292aU,
0x3e3de249bf419491U, 0x3e97d4c4be167802U, 0x3cfd85f5be301d35U, 0x3eba1185be89c79eU,
0xbf22841abeb11d43U, 0x3ec463adbeeb8eb5U, 0x3e848f063e98dcd3U, 0xbf3c4fa5bf2611e0U,
0xbdd5a7393bf4a892U, 0x3e8aed223e3f3f11U, 0xbf1f9ced3e8ddae8U, 0x3e52aed7be9fec0dU,
0x3ecdcbddbefe944aU, 0x3f54b9e6bd81fe39U, 0xbd6b9d4abe67a39aU, 0x3e8e031c3da1e8d8U,
0x3f2bc172392b7b62U, 0xbead2e0a3d893fb1U, 0x3eb8f14cbe6f5f70U, 0xbeffdf15be91451cU,
0xbcef2d12bedf71edU, 0x3db0fda23d54c95aU, 0x3e0f6d1dbe292f78U, 0xbde2a464beb5173aU,
0xbe2fc800beee10d1U, 0x3ee48a71bdd2f978U, 0x3de4eb063e633bfaU, 0xbdf8c6bebf592819U,
0xbd516ebcbcf92494U, 0x3d8bbcf3beb86d31U, 0x3d592b69bedb7765U, 0x3e0521ae3c82fc62U,
0x3c960532beca6cf3U, 0x3e1ad55cbee5b333U, 0x3f0f9941be8a207bU, 0x3ee81010be248055U,
0xbee97ff23ed6d59aU, 0xbead9cef3e5aeedbU, 0xbe0393c7be88929bU, 0x3e40cbcdbefadd14U,
0x3ebf7550bcd63e1eU, 0x3ea0d7ebbec29538U, 0x3d16b57abf22b9f1U, 0x3e8298d13d4b8409U,
0x3ea3d1a83f136b20U, 0x3e61458fbf7e676aU, 0x3ed0e962bad2076cU, 0x3ed95ce7be5e7cb9U,
0x3cd0a252bf2e24b7U, 0x3dfcad1f3da380e7U, 0x3eb07f57beb05e39U, 0x3ea7bc813eae8372U,
0x3f2264a5bdd022e7U, 0xbbf48eba3ea6b81fU, 0xbd6501803f68318aU, 0xbea370dcbe2522a2U,
0x3d891fd4be2dd8d1U, 0xbea3e69cbeab23fcU, 0xbf2a4ecc3d16d41eU, 0x3e6bc8523e9a8e58U,
0xbc2cb944bf68453dU, 0x3c57ec7c3e090752U, 0x3e83c80ebe3e906dU, 0x3bd097113f031c01U,
0xbe303f9bbe05ed82U, 0x3e1f90f53cf63710U, 0x3e9f9fae3d920f2bU, 0xbea0a81b3e721477U,
0xbc334190bc8f3f38U, 0x3e578af9bd66124aU, 0xbf579f4c3dc42ca3U, 0x3ee2b172be4eea6aU,
0xbe07711d3ef3b462U, 0xbebbe57abd67ac91U, 0xbd1a0a41be2456abU, 0x3ecd38f1bbe618efU,
0xbf69e7b33dd4d870U, 0x3da946153e0df325U, 0x3eb865e33f896d98U, 0x3f35fc08bd4c32a6U,
0xbde67ef43e0c3fb6U, 0xbe5ceaff3f08e4ebU, 0xbf4286d63e81dccbU, 0x3ea463b03d21ec32U,
0xbebad84a3f008e31U, 0xbf026145bdf37da4U, 0x3e82a4c13e6febf1U, 0xbca71db03f8cb702U,
0xbe50910ebdfc7ea4U, 0xbe273a74bee84693U, 0x3d8de276bf0ca8d8U, 0x3dbc0ee73ca7981bU,
0x3e3a3376be2860b5U, 0xbe93bc03bf40b618U, 0xbec242f83dede36dU, 0xbe81b3e03cfab7d1U,
0xbd91a070bec9ce11U, 0xbde8174c3ccf5ae9U, 0x3e697fd1bef724bcU, 0x3e5115a1bf0d5d00U,
0x3f5e98f43e8a3f2dU, 0x3e812927bea2e6bfU, 0x3e78aadfbeb99c0dU, 0xbeab8e343ed2e898U,
0x3df4037abd73ade4U, 0x3f0fb3fabf067e8cU, 0x3f7562a7be1d71feU, 0x3eb609273eee16c9U,
0xbe2b98acbf205b15U, 0x3e4923c23da2b094U, 0x3e591ffabf05cb4dU, 0xbd22f661bf1d60c3U,
0xbd97ba3c3d7c1925U, 0xbeb58c0f3db5ca4bU, 0x3d3efcb83f0ab289U, 0xbe4ebfecbe727a32U,
0xbe522196be88f65dU, 0xbd27a690bef40a94U, 0xbe977bebbe39a379U, 0x3cf1ba88bc2bafc5U,
0x3b8f3060bb353a7aU, 0x3c02efe53c3f63c8U, 0xbdf6cc7b3e211541U, 0xbe2bbe983f459b89U,
0xbe88da433c4cc020U, 0x3f0ca450bd92526fU, 0xbf4cf5623f378695U, 0x3f61f3413e31ec91U,
0x3ef679a6bd034dd3U, 0xbe2e08803f811552U, 0xbef67ada3d712bccU, 0x3ea773e5be826770U,
0xbe9680b53f00a878U, 0xbec85284bca5259dU, 0xbca09b82bed0de28U, 0x3ef18fdebe9d81ecU,
0xbf4c4482bcbb8c07U, 0x3e2bad7bbeb6bc5eU, 0xbd53349dbf1b3b6bU, 0xbf00f1b93e13f791U,
0x3d1631a6bd056440U, 0xbe937dc0be862349U, 0xbf13182bbe1ded86U, 0x3ecbf053be749f58U,
0xbcd2381ebeca1f80U, 0xbd415131bd3b7fe3U, 0x3eeb27cf3dc2a622U, 0xbe70c45a3f2429e8U,
0x3eebd5763e5b78e1U, 0xbe1c5d833e836409U, 0xbe8eab2b3f68dcd8U, 0xbedb0d81bc5e0628U,
0x3d918bc73ca7faa8U, 0xbdac08063defd257U, 0xbeab44bfbe83cb8dU, 0x3ee2d915be2f7979U,
0xbe2f56663f3730e3U, 0xbf4162733e827825U, 0x3df89f84bc93bac6U, 0x3f139eeb3e91d0faU,
0x3f5afd7ebe387f27U, 0x3e61237cbefe59d7U, 0x3e48c5a43f37244fU, 0xbf4745153ec65ba8U,
0xbe85ffd63ea40330U, 0x3d94ff93be4a651bU, 0x3d3d95ffbdcee45bU, 0xbea1527abe6629d3U,
0x3bc43f663e458af2U, 0x3d925db7bdd7a8f2U, 0x3d7bb8853e860c1eU, 0xbe79eea23c695237U,
0x3e232bc5be3e4249U, 0xbe75e4fe3da8c2bcU, 0xbcafa9d53e91e065U, 0xbe604a17bea04fdbU,
0x3e0d2c9bbeabf1ddU, 0x3d5e32a63e0567a3U, 0xbe2aea90be869519U, 0x3d7253c0bdf805bdU,
0xbea413babe33e5b6U, 0xbe865964be89ca08U, 0xbe8474703d9a0c94U, 0xbe598a4ebeac9f45U,
0xbe6e0d21be888984U, 0x3df38c863dae3813U, 0x3d325c9ebe96b08bU, 0xbcffa6e43e302653U,
0xbc2145e23d6b4763U, 0xbdc1dbf93e679eb8U, 0xbd3bbe69be4285daU, 0xbc9e3185be4065bcU,
0x3df704323db8ed14U, 0x3e3f4f75bab67518U, 0x3e28417ebda35e82U, 0x3e258ee9be5378c7U,
0x3deca43a3e0b3ba8U, 0x3da6a894bb294e61U, 0xbd0995e6bea646deU, 0x3a019da8be1b062fU,
0xbcf44055be81ce21U, 0xbea236b8bd4f4398U, 0x3e2c9adabdcd6eceU, 0xbe0b151bbe92c2d3U,
0x3e9023c73e05f3d9U, 0xbe6ebf9ebe4cf0afU, 0x3da4a1b13e9d5d10U, 0x3df1f92c3e705e3cU,
0xbd484878bd83ec07U, 0xbc9ebc943d9d69feU, 0xbe67639dbe5db0d0U, 0xbd762eedbe4615ddU,
0xbe43cbf8be4a9baaU, 0xbcd5760bbdb0ea7fU, 0x3d1b8436be8c1501U, 0xbe97a7e83d835889U,
0x3d806fd6be032846U, 0xbe8be4ecbe59f9a2U, 0xba12dbb6bec242c8U, 0x3dbcdb8e3deee458U,
0xbe0b702c3ddf2e5cU, 0x3d79c3cf3e582017U, 0xbe311ca33df79659U, 0xbe78a4a1be3cdb4eU,
0xbe71484fbdaf4361U, 0x3b3ca4c2be7d8409U, 0xbe014f3fbe83ad05U, 0x3dd532e0be3c0bbbU,
0xbccd5a28be6588b9U, 0xbb1b47f4be1ad0caU, 0x3c01112e3d1cf594U, 0xbc39678e3d4c5ab8U,
0x3c47ba003d1bdb66U, 0x3db9c5edbdd0158bU, 0xbb653f99bd13c3f0U, 0xbd8edb213d188658U,
0xbcd32466bd9f2daeU, 0x3d0df3b83dcb830dU, 0xbe71f6a8bd9d0e1aU, 0xbe838e83bd9000f6U,
0xbcea074e3d19496fU, 0xbdd0877cbd1e41e7U, 0x3d968162bc8ac58bU, 0xbde29adabdedd093U,
0x3cc078703ca884fdU, 0xbda14006bd8d678eU, 0xbc87c9c7bd189c39U, 0xbc805b133d455a72U,
0xbb9d9482bdaf52deU, 0xbd2bfba73c15bdb2U, 0xbb92d5e13d4fcf6aU, 0xbcfe86863d35613eU,
0xbd8728d3bdf7c459U, 0xbb6d28bbbd3b42e8U, 0xbdbeaf9dbdaa78afU, 0xbdf84466bdc86816U,
0xbd752a46bdc243cfU, 0x3e07cc343ba3f93aU, 0xbe35ad81bd1ae1caU, 0xbccfb0923e4411c4U,
0xbd016c71bc312231U, 0x3bb6e830bdbec035U, 0xbda625c33d8c47cdU, 0xbdbf8b92bd0031c2U,
0x3d953639bcfd507cU, 0xbb172dd33d515492U, 0xbe342dbd3c0ef31bU, 0xbd4a6577bd88dc6aU,
0xbda28b48bc5ec36cU, 0x3dc0f77cbe3d1311U, 0xbde0ac16bda2931eU, 0xbc77c47a3b99536eU,
0xbd2cab413cf9e7a4U, 0xbdba952abd847ac9U, 0x3df8fd68bc5b0bfaU, 0xbdd064303d0b8906U,
0xbdc91b39bdd31fddU, 0x3db5aca43dc8a83eU, 0x3bbbef22bcf18eb4U, 0xbe6304b0bda4c69eU,
0xbd2ff8603d5c8061U, 0xbdbc92dabccd35e3U, 0xbe1de2dbbda0d5e3U, 0xbad6e98abdd28ab0U,
0xbe075f2b3db4a129U, 0xbe2cadb73d17bf95U, 0x3cd390d7bd647142U, 0xbcecbbdd3d0e1f58U,
0xbe0374a53d6a2f39U, 0x3bada013bd4f40aeU, 0xbb011e6c3d9074e1U, 0x3dd414dcbe4f0894U,
0xbd304b733d8b5e14U, 0xbe87f666bd449bf0U, 0x3e576b5b3e033c05U, 0x3e2a6299be49b852U,
0xbcafbf6ebe05fb7eU, 0xbe5a185c3dd80cedU, 0xbe469fc7be847085U, 0xbe0c595ebd1efa3eU,
0xbcb8ba3d3deb3ef4U, 0xbe5c473abd928644U, 0xbd162b12bc9df399U, 0xbd977b9abd9e0e95U,
0x3ec5925fbdece6fdU, 0x3d3b7a04be427ff9U, 0x3cda5b7c3c5a3cccU, 0x3aa26495be5bf4cfU,
0xbdb2ed55bd91433dU, 0xbd3d39b1be366fa3U, 0x3d9002dbbc095e3cU, 0xbe2cf6b33a12889cU,
0x3c3694343e456b3bU, 0xbd1b02d33e48a8b7U, 0x3d72bb9bbe1c74e5U, 0x3b53a5b33ccf120fU,
0xbdbf2314bd4bfbe4U, 0x3c3cce9a3cabc5b9U, 0xbd66670dbdd14becU, 0x3e373da2bd4c3407U,
0xbdd63cf2bde361e1U, 0xbd8f1ec1bdb1e026U, 0xbcbc5a81be53c833U, 0x3e29a311be22c050U,
0x3dc153b6be2e2f72U, 0xbd53f37a3c804de4U, 0x3e67f061bdc0caffU, 0x3e681606be33814bU,
0xbd58216b3d169c56U, 0xbdc41a32be914298U, 0x3c84400abe323a1eU, 0xbd86ede53d72c08aU,
0xbd6db2b6be1122d4U, 0xbe002d053d883d0fU, 0xbe305af6be06fdd6U, 0xbc8d2b2c3baaa2f7U,
0xbdd2470ebe33404bU, 0xbd6d3a8d3d64ea13U, 0xbd65a7efbe6aa2aeU, 0x3d3d0236bd3de737U,
0xbdc401253e00bcb0U, 0xbd0aa785bd89d6e3U, 0x3d2cd52e3d2d9bdeU, 0xbd59dfbd3de4a347U,
0x3d981126bd2a805bU, 0x3e02c2db3e1f2ca8U, 0x3e4d2a1cbde7e0beU, 0x3e248f5a3c9f9de4U,
0xbdd77416bdc57320U, 0xbde2e8b6bd181c30U, 0xbdc7234b3cc7f60fU, 0xbcb281fdbcb0977dU,
0xbe8521aa3d672acbU, 0xbd8d92853d3d56beU, 0x3e79b5c2bdbe0fb3U, 0x3e4b0a81bd3a2dcaU,
0x3d1b4aa8be897b8dU, 0xbdc00090bdd2efc8U, 0x3d4ee2763e35009bU, 0x3a62dde2be2a3b1dU,
0xbd55e790bda503d0U, 0x3dc584e1bcf69df7U, 0xbd1877103d8ad653U, 0xbd181568bd9f8396U,
0x3b666d1a3bf78811U, 0x3c1dc810bb6266c1U, 0xbda6eeca3d24b80aU, 0x3d20e543bdd456b9U,
0xbd31432a3e080f49U, 0xbe676d38be3863dfU, 0xbe7fcd4b3d1f1778U, 0x3dd1d77a3d90061fU,
0xbddb593e3d7d09c0U, 0x3d83393cbd2ccf14U, 0xbd414865be05ded4U, 0xbd18716bbdd2498fU,
0x3cc3f95dbd83bb47U, 0x3db4cc023e1503bfU, 0x3e333b153bd2baedU, 0xbd8ab3093caf37f5U,
0xbd192a523dcb5d65U, 0xbda0d084bc9be70bU, 0x3c385386bc5d928fU, 0x3bcc66bd3e58de51U,
0xbc69a54d3ccecb44U, 0xba817510bda0fe1dU, 0xbe6968ddbb65005dU, 0xbe00cdc6bc514f25U,
0xbda7eab73e8c17efU, 0xbe3a57613c6dcd57U, 0x3d9d973c3e19e603U, 0x3d038fdabe1771bfU,
0xbe060196bd5d70a8U, 0x3e0f8cd33af9d038U, 0xbc056680bd1eab4eU, 0x3e041b3d3da112dcU,
0xbe3549e03daa7b4dU, 0xbe4295a43d45effcU, 0x3d990100bd90e3acU, 0xbc638a033df82a25U,
0x3d8926babcd42aa5U, 0x3da2718dbe029a6eU, 0x3dda29e0bd6ba033U, 0xbabb98e53e0aeeebU,
0xbd709c453e3c3fbdU, 0x3d739adfbd3f0577U, 0xbdb9678d3bfdf414U, 0xbddb07a0bdf2753bU,
0xbd8d1c6e3c4171a6U, 0x3caf13a0bc127917U, 0xbc2bd6193d712102U, 0x3d1f55413e007f45U,
0xbbb88be83da4bee7U, 0x3dab95bc3d2e673bU, 0x3d2aaf34bc634ee2U, 0xbe047a6c3bf4a2e6U,
0x3dc4b7db3cac5ff8U, 0x3cca222e3d60f21aU, 0xbd8402ae3c1b702dU, 0xbe01a1e5bdcca9a6U,
0x3e4f630d3d00757dU, 0x3d263aae3e4f1cc8U, 0x3e7c9faebd0d46daU, 0x3d9c8b1f3d876d10U,
0xbe6c8e453d0f0c05U, 0x3cdf9b353ae91066U, 0x3e8985533c6ed144U, 0x3d2d467f3c752c45U,
0xbd939366bc8c51c1U, 0xbe45ec30be4fc0eaU, 0xbe645ae2bb9ff8b6U, 0xbd2b16fd39fa1de7U,
0xba8b4829bd403b6cU, 0xbbe9cfdabd3be82eU, 0xbe4e9d3a3e02f4feU, 0x3e6daf90bdb94474U,
0x3c95fab3bdc85a50U, 0xbd9f1a8abd482626U, 0xbd5dc888be2d82f2U, 0xbd29aae7bc9c94e5U,
0xbe28d3cebe147ab7U, 0xbd80ac6b3d930b39U, 0xbdbdf493bd6b7602U, 0xbd151dce3d93b885U,
0xbda9d3083dee111fU, 0xbc769befbb21a964U, 0x3d6ba791bdd1c185U, 0x3c872440bcb7b5dfU,
0xbda1e971bd07321cU, 0x3d79d3b8bd277003U, 0x3d8adfec3e535584U, 0xbe5474e6bdaa2990U,
0xbde6e5b8be04673fU, 0x3d7e5378bd27ea5fU, 0x3d73afb5bd98e247U, 0x3e98be7abe885506U,
0xbdf94c8a3d0a8498U, 0x3dfff28ebd8aee36U, 0x3c745f74be0f2ac7U, 0xbe2e100b3d84d5fbU,
0x3d0e81a8bdcc5f47U, 0x3dc524563afd99e1U, 0xbe63815b3d53f559U, 0xbdca39e6be8148b1U,
0xbd12f7453e44197bU, 0xbce3c312be14b5fbU, 0xbdce6f483e098892U, 0x3b98a39ebe2024f9U,
0x3c9558e9bc5ab3f0U, 0x3beabb7bbe1724d5U, 0x3d044408bdf0b313U, 0xbdeb26b73dac1f4bU,
0xbdba1f92bd0e68cfU, 0x3dcba1e8bd8bcb6cU, 0xbdba0493bdb0b099U, 0x3cea8b8ebdfa7a0fU,
0xbe05efc1bdc3a14cU, 0x3e41f20fbc4f74f3U, 0xbd886afa3d5fedaeU, 0xbb758dc23b8836ecU,
0xbe87e2403cc57f2bU, 0xbdbd908fbddec34aU, 0x3d10bf9dbe490b5dU, 0xbddc87bd3d83da65U,
0x3e2fe270bd3801abU, 0x3e39627abd85d8afU, 0x3e2d5120bcf01446U, 0x3ab69e43be248700U,
0x3de250463ddb3a56U, 0xbdc027f93df0ce0cU, 0xbcc53341be59b17eU, 0xbe1f3f683da8e161U,
0x3d877eb33c1e4036U, 0x3da32e073db6499dU, 0xbd68fc473d9647bbU, 0x3d40fb48bc3bf74dU,
0xbdd9309dbde00379U, 0xbd28ce10bd29fcf7U, 0xbe05b2903d5c73bbU, 0x3e11deb33d6b3773U,
0xbe8d0349be83fafdU, 0xbdfbd9dc3d9ca991U, 0xbd0a822d3e3f51a7U, 0xbe3cad333dbfd753U,
0x3e213fc73d880d2aU, 0xbe1b4cb8bd313861U, 0x3e211a773be1d20eU, 0xbcc2707c3c196855U,
0x3d739d0c3cf81d8aU, 0x3e5047383df2b02bU, 0x3c870f193c96e1b8U, 0xbd3cae95bd620728U,
0xbc958d98be2592cdU, 0x3d67a9c03e27f5eeU, 0xbd3129c23d842062U, 0x3d48169e3d5e0b93U,
0xbce63ac33d7d0e50U, 0xbdddc65c3df26892U, 0xbd43974ebcac9686U, 0xbd8d98743e073933U,
0xbe7f12963d95592aU, 0xbda669cd3eaee7bdU, 0xbd452befbce3c7d0U, 0xbcdaca673d34dbe5U,
0xbcbc65383dba33c2U, 0xbd91811e3ddac1b5U, 0x3e130fb13c9d0f2dU, 0xbda09d323daf56c2U,
0xbe90b9ecbdad8bf5U, 0x3e67db3abd12b4e9U, 0xbdb387443e29f710U, 0x3e2b99a5be3a562fU,
0xbc8c82bebd0384aeU, 0x3d6ea717bd2dc261U, 0x3d07e6323e4cf7b7U, 0xbd1e74173cb4f923U,
0x3e1e82683e6f4ba4U, 0xbd910e43bd5f8a02U, 0xbdc054abbe255858U, 0x3cc4bada3e6ba72dU,
0x3d1dbfd13caec0cdU, 0x3db3c722bd8de086U, 0x3d0a4ec0bdbf606fU, 0xbd2bdaefbc8cffc1U,
0xbd8b1d86bd986c23U, 0xbcfe2bcc3d994186U, 0xbdd593cd3dc1a941U, 0xbd9557b23ddaf65fU,
0x3e2994fbbd888246U, 0xbd6bce913def709aU, 0xbdd016f03d8e46e4U, 0x3e89f8eb3d3555cfU,
0xbcecdd393e7cd54bU, 0x3d4c95723e0796dcU, 0x3c1a22fc3cdfab3bU, 0xbd62b873bda728e5U,
0xbe01c7eabe904a7eU, 0x3ca60a41bdad13f7U, 0xbcea49a73d3face4U, 0x3da1dcfe3d66040eU,
0xbdaa1e59bdc01d03U, 0xbdd0d8c3bcf30e73U, 0xbd171390be3c89baU, 0xbd95c4253d3a2195U,
0xbd7916a4bde75aa0U, 0xbd96e0ba3d543fb2U, 0xbcc49c653de0f5e1U, 0xbd8da69ebc42c1abU,
0xbdaa979dbe3db296U, 0xbd01612dbe39554bU, 0x3d0a95afbdd047bdU, 0xbdd664d4bcb61adeU,
0x3c09f77f3dbf3b9aU, 0xbdc728ebbe11353cU, 0x3defab1d3c9f1c4aU, 0x3df185763db15be9U,
0xba26737abdfff909U, 0x3cba2b87b9006ddeU, 0x3d0021e63ce0edacU, 0xbe27ed5ebdf38822U,
0xbdc215ccbd175ee7U, 0xbda10265bdb8b57fU, 0xbd23b639bd9cc2a5U, 0x3d8babc1bb073d7fU,
0xbe17ba7c3e1b6deeU, 0xbdfa3c39bdbdc958U, 0x3d8bd76c3d70a7d5U, 0x3e0c1938bdb7f7b1U,
0xbdc82a00be1f9534U, 0xbb20c5333dd9f0c7U, 0xbe4e78adbdff2b8bU, 0xbd4e68e2bd8ca7e5U,
0xbc27e6723d7403d2U, 0xbe80e18d3d6abd36U, 0xb9613b07bd0bf8d6U, 0x3d76b6193cab6950U,
0x3d574a7dbe1003eeU, 0xbdd0b19a3d553132U, 0xbd8274b3bd997b06U, 0x3d9ec9dcbd16e085U,
0xbe138021bdf06762U, 0xbb898393bde8d544U, 0x3cc568debbf2b7f5U, 0x3c9aa6593dab323cU,
0x3d3e62f73e04772aU, 0xbdb05010bd612ca7U, 0xbde026133c6ea290U, 0xbe82a624becf2093U,
0xbd83965a3d81fb1cU, 0x3c985d8a3dc6cf89U, 0xbdcf7cedbdb62ac6U, 0x3d6b4f32bd3116c9U,
0xbd9236003c7e6683U, 0xbcf352613d115eabU, 0xbd952694be836b17U, 0xbc95f82a3dcc4880U,
0xbd4a99563e07ec92U, 0xbb19e78f3d554c36U, 0xbee0c77c3d09dc8eU, 0x3c11cee3be1c013cU,
0xbe357fb3b98e5608U, 0x3d1ee5e1bc9e241eU, 0xbeab33fd3d793ed4U, 0x3e616ec5bc4f0e27U,
0x3e5ef538bea1fafaU, 0xbf3390ef3e732af7U, 0xbdcf76e6bef5f5fcU, 0xbdc4c9693e210567U,
0x3c5f82ddbd1dc672U, 0xbe6abb2ebd82e014U, 0xbdb7c37b3e04154bU, 0x3d226e4a3e0bedb1U,
0xbd17bc533cd3c032U, 0x3dbd51d33d34f0a3U, 0xbf1d02363e3f32ddU, 0xbf074b1f3e4cdb41U,
0x3db00c443cc1e9e6U, 0xbc083faa3e72495eU, 0x3e3353fd3e8d5c18U, 0x3e6d830c3e308b30U,
0xbd5c6ae33e23553dU, 0x3d5469133e3b4d38U, 0x3da36d24bd62d1cbU, 0xbebafdb93d877cebU,
0xbdb82b763e1b60deU, 0xbebfd4563de21f70U, 0xbdd466bb3d69f8b0U, 0xbe9a9ff03c88cf96U,
0x3d029610befe6997U, 0x3e92de913e1cb7bcU, 0xbe212ec33e007558U, 0xbcdc7ee0bcd2a8beU,
0xbc882ea9bd1dd357U, 0x3df8b4dfbda2b387U, 0x3e31f033be015bdaU, 0x3e2faa403e7c896bU,
0xbf20c2f0be377c68U, 0x3e136d97bdf903a3U, 0x3e78cd44be5c40a5U, 0x3da8130fbeca5573U,
0x3bc4a4023e87b71dU, 0x3e3fb0293dd23825U, 0x3e30cdbdbcfab636U, 0xbead0c8c3e15cc2cU,
0xbd94aaad3dd452d5U, 0xbf0b57903c1c60edU, 0x3e0de8413caa26d4U, 0x3de0aa1d3e57ce1aU,
0x3cb5b29d3de6e81dU, 0xbc61bcd53e3054acU, 0xbcea51ba3c7b655bU, 0x3e1cdc80be0e826aU,
0x3d892356be0fad37U, 0x3e34c986be7771e6U, 0x3e0e10d6bcf8a162U, 0x3decf5383e6921f6U,
0x3df5c4f93e523047U, 0x3e16fa2e3cb8334dU, 0x3d5689403cfb761dU, 0x3d2d1d09be5e9513U,
0x3e1e67dbbe52f26cU, 0x3d6fcd01bd4508f2U, 0x3e2e9e1fbe344f00U, 0xbeb970aabd480d01U,
0x3dba30cb3d2fe430U, 0xbd39cff7be5fb7f4U, 0xbcc1358bbe6676b3U, 0xbe17f655bd5f2f21U,
0x3d9d7801be8451a7U, 0xbecfa0983e6a0ea4U, 0x3e42b9373dc35b11U, 0xbf0a0336bf12f14cU,
0x3d06caabbd980413U, 0xbcd214c5bda35751U, 0xbecef5f23ec24698U, 0x3ea8fd46be301968U,
0x3d9bee64be168441U, 0xbcce6abe3ea4cbb0U, 0x3e1e35073e773230U, 0x3e147c8b3e6e90fdU,
0xbdde0fe9befb54f1U, 0x3e2c3d0ebecb750aU, 0xbe3678b93e3ba252U, 0x3e2664413de629ccU,
0x3f07a96ebe21c23bU, 0x3da6b36f3e3bcf56U, 0x3da911f73dbf7e26U, 0xbdde32f8be6e7f42U,
0x3e5db23e3c0a5788U, 0x3d97a8b1be85d84dU, 0x3e5fa5cdbdc5154fU, 0x3cbef5b2be37c35cU,
0xbd8cc7b23d0c7d97U, 0xbed8577dbec784fdU, 0x3da1c4f83e7e8f1fU, 0x3ebc21443e65e721U,
0xbe2ee7debe648a93U, 0x3c45ad35bd252061U, 0xbe98289ebd5621a3U, 0x3818be663ef0814cU,
0x3df049de3e47ee61U, 0xbec17ab93eceeac3U, 0xbe088b8dbf0d6acfU, 0x3d7c2a713e0a696fU,
0xbe1a9eb73e07d78dU, 0x3d8ec9e83d128ca5U, 0x3e8d021a3dc2889bU, 0x3eba505a3da86305U,
0x3dd2c3333eb37545U, 0x3d8edcd8be10b23aU, 0x3f01d2a43da3f9f7U, 0x3e0ee33ebef31f38U,
0xbbd3582cbddaac5eU, 0xbe8b8ee13e745feeU, 0x3e5589c83e85eba1U, 0x3e9b59db3e8687bfU,
0xbe736482bcebe384U, 0xbba2df0e3d8ac2f3U, 0xbd36986abe953f0bU, 0xbda3ab273e97a4acU,
0xbc0757363dfb4c8fU, 0x3e28ea9e3edbebc2U, 0x3daae75a3eb09be0U, 0x3d6be31f3e43af49U,
0xbda73b51bdd84770U, 0xbf06bf79be3fdcd5U, 0x3d8691783e5253f8U, 0x3db96a2a3e9954edU,
0xbd0cdd553e642c66U, 0xbe8efce9bf06797bU, 0x3dd6508d3e71b763U, 0xbef235563dab6f60U,
0xbe977076be8c889cU, 0xbe7e3a6bbe14c6a5U, 0x3ea3d615bcb7938eU, 0x3e90d283be48c274U,
0xbe8dc2643e92706dU, 0xbde6bd37bec84f6cU, 0xbeded88c3e4304d5U, 0x3cb95456bc2bb0bdU,
0xbeb1f4b4bdb1d967U, 0xbd9fc0b53e235d57U, 0xbdc2e47f3e2bb83aU, 0xbd9e4243bdcdcd46U,
0x3d8307c23e021537U, 0xbebe87d23e95715eU, 0xbe818b883e3448a9U, 0xbdc8f337bd3b69dfU,
0x3d909c153d9867ceU, 0xbd8d75c73e71dc62U, 0x3e2dbda03e0e7084U, 0xbd8693b03ec3c169U,
0xbbb2503d3e90f43aU, 0x3e218028be3cb375U, 0xbe934bfc3e9a1aefU, 0xbe4404d23e9762b8U,
0xbeabb69cbca3b63fU, 0xbd72fcd23e29a19aU, 0xbe1cdb8dbe598553U, 0x3e2e5187bea5ad1aU,
0x3e280c7c3e4ab77aU, 0xbdc0474a3d53c546U, 0xbc981f68be6192baU, 0xbcdceca1bcacb1f8U,
0x3dd290f6be5ac01fU, 0x3e4eaec0be54c5e3U, 0xbd9380663e38c94bU, 0xbede3d90bedfd193U,
0x3e5511cdbded370dU, 0x3ea949d7be802307U, 0xbdafac4bbee5fb3dU, 0xbdf67e4f3ea795c5U,
0x3e46a6723e7751f8U, 0x3e91f847bc5632ebU, 0xbee3319c3e23a93fU, 0x3ce44afd3def4a91U,
0xbe166ff63e3f0220U, 0x3a3bc066bd87b649U, 0x3e72d24d3e755698U, 0x3bcaa54ebd4a347bU,
0x3daaf2353e5336f2U, 0x3c56416f3e4a96c6U, 0x3e1b7d09bdb6501dU, 0xbeb8fc75beb9456aU,
0x3e8c811cbeeac1a9U, 0x3e828cb4be8df5cdU, 0xbe273c8c3e90bf10U, 0x3e87516a3e92e62cU,
0x3e84d0333dee11bfU, 0x3d6f898e3db4ed87U, 0xbe2c14e4bec7c131U, 0x3eba3443be5fab91U,
0x3e29cd64bc06abedU, 0x3e69a7d5bea62dd2U, 0xbe6a2c95bd873b33U, 0x3dbf5aa6be7d23cbU,
0x3b43c5fbbe3a0ac5U, 0xbe4de4ffbe84e6ccU, 0x3da8ffcf3d2aabceU, 0x3dee8c22bdb5e6d7U,
0xbe8f04ea3c65a983U, 0x3e05d5b63c6db422U, 0xbe7a0862bed07cc7U, 0x3e0077eb3dfc856cU,
0x3d4e39183d79f7cdU, 0xbe88d33d3dfa172aU, 0x3e5e8d253dc6f780U, 0x3dc770e4be0bae25U,
0x3e02885bbca115b6U, 0x3c901a603d461bfeU, 0x3cee59143dfddcccU, 0xbde3b0b8be2e6db5U,
0xbd82dd31be958f5cU, 0xbc9c48b93d9d086dU, 0x3b921a6cbe039130U, 0x3e102de6bddf87a6U,
0x3cab93683d990115U, 0xbb449d62bcbda48aU, 0x3da74bbbbe8d1604U, 0xbce03793bd549cecU,
0x3d0755e9bdfb1e62U, 0x3e14788d3d41b8c5U, 0x3e38d850bdd4ed50U, 0x3de5d6b83dffc8f4U,
0xbe852b68be3394c4U, 0x3e1bf489bb98f529U, 0x3e4f02263d67b791U, 0x3d9bc4d73dd9ffb3U,
0x3e3798babdbecf48U, 0xbd8ef6db3cf4b68cU, 0x3b47cdd23e7e83a8U, 0xbdd9482ebd4cf4acU,
0xbe7c52363e4462c2U, 0xbe32a27abea62b97U, 0x3e0956803db31b53U, 0x3beadd2d3d2e2425U,
0xbd9c8224bdfa8379U, 0x3e1635d5bc996078U, 0x3db0b9563d308c91U, 0xbd10eb31bb8557ceU,
0x3de98439bdb5b446U, 0x3d62b3cc3e0e9eb5U, 0x3e01c279bea91d2aU, 0xbd45efe4bd20f209U,
0xbeb91a563e0384a1U, 0x3c24ed1abd1d2ddaU, 0xbc1121eebd481882U, 0xbe6ca7503e30c1ecU,
0x3d43d4923a92f175U, 0x3dfbf449bc4db71fU, 0x3d8a36513dba0768U, 0x3c8c7c09bd6c0e7fU,
0xba932a323e091875U, 0xbd88b78b3e125ea5U, 0x3e24cae73ba0e9a9U, 0x3d895d38bdc7d299U,
0xbec85aa1bd6ce1efU, 0x3d9869ba3dc9fab3U, 0x3e0270c73de93200U, 0xbc6be746bad0122bU,
0xbd59632abe6e4110U, 0x3d3493a03e9403b1U, 0xbe0dc7bc3e47a986U, 0x3b345e6bbe152026U,
0xbe8f1c83bdb7f02cU, 0x3e3251e03c9b9e5eU, 0x3dd4c4b0be5acb12U, 0xbf0daf3f3dbab743U,
0xbe090b79bf112cf1U, 0xbdceb9e53d8503d4U, 0x3c6d5440bda2df2bU, 0xbe00d55bbdb60358U,
0xbd8eb7e83cbf2bd5U, 0x3d26fcc83d38e346U, 0x3dfb3108bd04c49cU, 0x3d3d2d8a3ca25cb1U,
0xbefaae0bbc95962eU, 0xbe961de93de4e5a6U, 0xbd8637f33e153c53U, 0x3c2ea942bd8110ccU,
0x39af8c113e4e11daU, 0x3e0834783c96f83eU, 0xbd969cfd3e45c5dfU, 0xbcae96453e474a83U,
0x3d8bf908bdbbbd1eU, 0xbec35cfb3e6b6991U, 0xbc094a6e3dd1ae26U, 0xbedc73753c27c45cU,
0xbd66e4533d04184cU, 0xbe8bd3fabc8e16a2U, 0x3c9e259dbed32ab3U, 0x3e065fe1bc847dd9U,
0xbdb17fe63dc66533U, 0xbd8a01b6bdf8eccaU, 0xbc6454f23bc4efc4U, 0x3e0f3a54bebb1104U,
0xbd025c4abd08d437U, 0x3a65f4393db12837U, 0xbf1877aabf0c158dU, 0x3e53543ebd9ba8d9U,
0x3e29d650be6243d1U, 0xbde8ecc4bee11152U, 0x3caf8df23e1d2899U, 0xbd3c89b63dd16590U,
0x3da832f73e000e4bU, 0xbeacf18f3d23e667U, 0x3c3c67bdbd4510cfU, 0xbee97ac7bbb4f4f7U,
0x3c4e796dbcaf67bdU, 0x3e3d3fa33d14bd82U, 0x3d80f1c0bd5a30f0U, 0x3d910ae33dca4b15U,
0xbd21c3bf3dc24225U, 0x3e1c87f7be022ea4U, 0x3dc9ba34be4784fdU, 0x3e03eac7be2f8de5U,
0x3d9e2385bdbb5178U, 0xbdb3bc233e1a6bacU, 0x3e1df3283d4763fcU, 0x3e4b32ccbe42c4bcU,
0x3da4c197bd146211U, 0xbd184225be7593ffU, 0x3e15002cbe87eea3U, 0x3d3160d23cfa919aU,
0x3e2cfed1be5a6784U, 0xbeac144ebc60b2d9U, 0x3ce512f5bd09a3f6U, 0xbe08e794bdd8a1caU,
0xbe6b91a5be868c21U, 0xbda34048bdeee368U, 0xbca40483bd91d27fU, 0x3dde62cfb9523490U,
0xbe208f643e0b7d8cU, 0x3d069ebabce235d1U, 0xbeadfa4abe3e7180U, 0xbdb6a13cbe6fa1b7U,
0x3cfb164c3d8eb5f2U, 0xbe10981bbe7b7d3cU, 0xbee78a583e894b77U, 0xbd834908bdfaeff4U,
0x3eb378d23c9fd933U, 0xbcc2ee71be40c18aU, 0x3e1ae6c03c80d3a2U, 0x3df8a8943df0c44eU,
0x3c992cddbe2f8eb1U, 0x3de7ada63ef05e50U, 0xbe26c3de3dddb3cdU, 0x3dba599a3e178da9U,
0x3dc31e7a3e9ec4b7U, 0xbeaa74563e2aaee0U, 0x3df9ffa5be178df2U, 0xbcd5de47bd7c55dbU,
0xbe71aac8bddc4e56U, 0xbd8d5d8fbcda8aa6U, 0xbe073e16bc26a13cU, 0x3deea2fc3c966bfbU,
0xbddd78f83d6daea0U, 0xbe25bd83bd98e4daU, 0xbdac6c03becd2101U, 0x3e4af236be47713fU,
0xbe5ed67dbe435e20U, 0xbe358602be7f132eU, 0x3e41c8aabd139caeU, 0xbd69524bbe4240dcU,
0x3e250562bba22961U, 0xbdb0b2603de0d87bU, 0xbe0b3ba93e412e0dU, 0x3d9aae7bbe68dfcbU,
0xbcd1b7cd3e09d3a3U, 0x3e03e157beb9a568U, 0xbe48c1c63e8e29d9U, 0xbe67cef2be4c82b1U,
0x3df7b232be69dcffU, 0xbe3962033d66c6b4U, 0x3e2b257ebd0ca456U, 0x3da20fe73e74b253U,
0x3e19a46d3de366d3U, 0x3e0eb7a93dccf187U, 0x3e118bb03da157a7U, 0xbebffb10bbcf1df6U,
0xbe709ddbbe983a8eU, 0xbd99c5d1bd87a00bU, 0x3e459aa63df56becU, 0xbba6fcd5be6d3353U,
0xbd6cce27be0aae6bU, 0xbe0ee1803dc25a45U, 0xbe9857afbd840923U, 0x3dab3861baa341aaU,
0x3d441df63e26be37U, 0xbdd5d0be3e316bb5U, 0x3e36100e3e0ad0ecU, 0xbe41defe3e28fc71U,
0x3da482bdbe2209e2U, 0x3bce1c3cbd1b4bd7U, 0x3e8622abbec6b56cU, 0xbdded5b43dece3f7U,
0x3dd4b8bd3dbce506U, 0x3d23c7943e1f06dcU, 0xbe46d8b2bd768bb3U, 0xbb819793bd32ff57U,
0x3e073708be94a5b5U, 0xbe03ea9dba52f91cU, 0xbda5f6c0bcf37bafU, 0x3da0c9103e5a15d0U,
0xbe78bd3dbe8a1570U, 0xbe5964a73e78b6e9U, 0x3de9dba93e0a017dU, 0xbe08e73c3d2f22a3U,
0x3dbde5f63e09891cU, 0xbe6e8413bde94f50U, 0x3e1033b33d4ed4abU, 0x3e05d756bd3d76ebU,
0x3e3156913e30231fU, 0x3ea6906e3dbfc7a4U, 0x3d92ac15bd21639aU, 0x3da082343e10c51fU,
0xbe1faa44bdc6ce44U, 0xbd45217f3dc26cf2U, 0xbdb0fd1c3e7823c8U, 0xbe0a9092bd3e2f3bU,
0xbd8c032b3e0fd33fU, 0xbe12175ebd886ca8U, 0x3c8763df3db2371bU, 0xbdbef5e83e9dd1d8U,
0xbe4ad0073d69ae8eU, 0x3d0b66b93e978b4cU, 0x3d543647be2c0e6eU, 0x3c604cf93db3e3e7U,
0x3e690fba3e490f39U, 0xbe48ea573d98b2dcU, 0x3dde8d733cc16c19U, 0x3c4ec58f3d5e8e7fU,
0xbe370388bcb8cf97U, 0x3d14d618bdba6c59U, 0xbdbb024c3d195e8fU, 0x3e20fe36bd903d53U,
0xbdf29f3cbda13869U, 0x3e11d1cfbd83c3bbU, 0xbe2cbe283dbcc432U, 0xbd5227dd3e28dc35U,
0x3e07947c3e42c89aU, 0xbe2ec9dfbd373679U, 0xbd8e01eebe693b23U, 0xbd640a783e125fb0U,
0xbcec782a3dbdcc9bU, 0x3dbbd0fe3cba5c81U, 0x3b2c7dfc3dfae6f0U, 0x3c7aae2f3e7bafaaU,
0x3d488fd6bd135252U, 0x3d8486da3cefd78dU, 0xbdbe410d3cb800e6U, 0x3cfcda89bd135799U,
0x3d8abaa33c128816U, 0x3c1d59a03d3bd337U, 0xbdb232f5bd567299U, 0x3e18bf673e8e80bbU,
0xbe31edba3ebcd779U, 0x3dfde6ac3e4bd039U, 0x3e7595a93d1b0483U, 0xbe4806a43c9f0c45U,
0xbd330e73bd8ed3e6U, 0xbc71352dbd7b0847U, 0x3d2a3244bc6342f7U, 0xbda000293d91efd3U,
0x3d9d6fa93d72b0ddU, 0xbe4ed0a8be39ba39U, 0xbdac0b8bbe6b6b3bU, 0x3d6eb835bd5766cfU,
0x3cef9463be332489U, 0xbe93b8223e31b9e6U, 0xbdba4eabbe46e71fU, 0x3e3b1ec2bde6635aU,
0xbd2015c8be270696U, 0x3cbf990cbe163fb5U, 0x3dbc6b8c3cc06b5eU, 0xbd6ab5cabe1b708dU,
0xbbd300513e123a47U, 0xbe0253a9bd413050U, 0x3d9def233e0efbbdU, 0x3d45fade3e01abf3U,
0xbe609469bc29b012U, 0x3df9ef57bdfb2e83U, 0xbcb94df7bd8e9618U, 0xbe27680fbda80ca5U,
0x3d049963bd61f0baU, 0xbdc6fe0c3dd527acU, 0x3de5ca1b3db5eb7aU, 0xbc96e6233d3daa7cU,
0xbe29f25fbddf6860U, 0xbd9962a7be34e8abU, 0x3deb8c61be72ccc6U, 0xbe634f57be1c4976U,
0xbe11ad2dbe1d86dfU, 0x3e1ce511bd8096ecU, 0xbd8c0d37be26aa78U, 0x3e18254a3d6cd92fU,
0xbe0b93ae3dab9e1aU, 0xbda4b204bc05a81eU, 0x3d2b3142bdee4228U, 0xbd6135773d8b592cU,
0xbc17cdf8be896379U, 0xbe5083963dfd0d4dU, 0xbdd03b29be404fb1U, 0x3cbfde8ebe19e3e1U,
0xbe058aa3bd492301U, 0x3dd0bd27baa60eefU, 0x3d7b62193df91a3dU, 0x3caaef133c0af478U,
0x3d5173453bf27adbU, 0x3d582945bd30d467U, 0xbe65bf65be03c24cU, 0xbdab5ce1be6a4e7eU,
0xbcd248013c856c61U, 0x3cc5472c3d805295U, 0xbe12461dbe28cecbU, 0xbd4349c9bdb2eba6U,
0xbe0b41a0bc9128acU, 0xbd8a5673bd9ef965U, 0x3d4cd52abdd4deb3U, 0x3d83f8a03d7d9d0fU,
0xbca9417e3d81fccfU, 0x3dd42dae3de10a7fU, 0xbde7f2cf3c878031U, 0x3ce64020bd1d2e7fU,
0xbd83f876bd7170ccU, 0x3df65a27be223c23U, 0xbc5932dc3da75a9aU, 0xbdc23a103dd01f81U,
0x3e5d8faa3e836395U, 0x3daf62c2be05a643U, 0xbe139b9e3e4acebfU, 0xbd72bb3ebeb72d65U,
0x3d0ebbe5bd10a399U, 0xbd8c004e3e85250aU, 0x3e09ffa0bdc4fba2U, 0xbdf59f82be40d7baU,
0xbe4ccc643dc0bd31U, 0xbe8639a23e87b9e5U, 0xbd061628bdc76ba6U, 0x3e3b36813e826aa1U,
0xbe927002bc875eaaU, 0x3e2505043e36cd5bU, 0x3e80623d3d837f94U, 0x3e8b8773be5391caU,
0x3e83a4dc3deaac08U, 0x3e0146f83dda770fU, 0xbdcff223bdc0cd88U, 0xbc86815c3c02f81aU,
0x3e1e8453be0bf4a1U, 0x3c960bfabe1e21b6U, 0x3cba0dcabe3bb076U, 0x3d3874c1ba87aa4cU,
0xbd9042223e77ab8cU, 0x3c987b07be19e56fU, 0xbe8746bbbe543fffU, 0xbe8ac3203d884620U,
0xbe23c4e13e1bb203U, 0xbeb23832bdeaba4eU, 0xbe141a64bb6454e6U, 0xbe5b32733e9266aeU,
0x3cc6c45d3e7f739dU, 0x3d1de0bb3e26ceedU, 0x3e302c54bc332c6bU, 0xbea5f0093dc64ec5U,
0x3dd6f09d3d94037fU, 0xbe48cdf9bde62bacU, 0x3dadb88fbe03d5b9U, 0xbd929ad4bd9540b2U,
0xbe6262cdbd67a8a5U, 0x3e1e48fb3d1f3f17U, 0x3dbc7136be85d4e5U, 0x3e3a27413e40cc10U,
0xbd3ff2c83da16756U, 0x3cf040ae3c098c85U, 0x3bdec97b3e4059bfU, 0xbd2e15573e625ed0U,
0x3e5c1d39bcd8a6f4U, 0xbe433ebb3d1daf5dU, 0x3e3cb9703d6c58d6U, 0xbe4d1c513e6f803aU,
0xbdf1223cbe0f858fU, 0x3db7995ebe88ee3eU, 0xbd4c152cbd6eb068U, 0x3e814b03bdf7ce08U,
0x3e2e7fa63e1c3483U, 0xbc4048273d166ffbU, 0xbd2ad17bbc3a185bU, 0x3d40309c3eb0a9ceU,
0xbdfce3c23d6a7be4U, 0xbd880f93bd8f2d2cU, 0xbe5204053e30b565U, 0x3e7330de3e0d6de2U,
0x3dd59c17bcabf828U, 0xbd41ab8dbe13d3b0U, 0xbdf0e87b3d9a8da8U, 0xbdd3a895be053d9cU,
0xbe6e0f4e3e4045d4U, 0xbc5fd7053e423424U, 0xbd0e805ebd8f9f0fU, 0x3d90d65f3dc75573U,
0xbe3c027a3c011c5aU, 0x3e6340babdcce873U, 0x3bd6cdb1be048520U, 0xbe1bdfb9ba542236U,
0x3cf2670fbd4ca089U, 0xbe55a29ebcfe272fU, 0xbd211a163c83812fU, 0x3cea6c143dbd6b39U,
0x3c79201fbd8b706aU, 0x3dd626fc3dee82d0U, 0x3d6f56103e7d72d1U, 0x3e624683be20b6ebU,
0xbd50269a3d8882c0U, 0xbdac266f3d57fe78U, 0x3e4958683c6149a3U, 0xbdb6f9253da1c6ccU,
0x3e4222103d9e1e42U, 0x3c6d87e6bdda20b3U, 0xbd61dcb6be16dd95U, 0x3dbff5a0be0bdd8aU,
0x3e65e6ecbde60cf9U, 0x3e3c8350be879941U, 0xbe69de773e16d90eU, 0x3e43a997bba507baU,
0xbc0f58e4be2ac5e4U, 0x3cddfeb83e139e62U, 0x3d95c759bdcecf8cU, 0x3e86b549be161036U,
0x3de2e4d6bdb174dcU, 0xbad12085be99af7cU, 0xbe5d0a4c3e37e4f5U, 0x3ce41c24bdc76da0U,
0xbe1d7d963da8de3aU, 0xbd95b3973dfb8f24U, 0xbd2199f03e27c539U, 0x3deeda84bdeb8431U,
0xbd162d6f3d93b228U, 0xbda665663e38051eU, 0xbdb344dcbdebee4aU, 0x3d905dbfbe0f8140U,
0xbcec4a023dad150cU, 0x3ec99e37bda12c51U, 0x3e7fd6e73dfe88ecU, 0x3e6f30d4bdcb45caU,
0x3dd2f7d5bc95c322U, 0xbe0b0ed33d519ddbU, 0xbdf01dbebd1ab74bU, 0xbc274ce3bda94a0fU,
0x3e85936bbda4bcedU, 0xbcf887313e1472c1U, 0x3d885789bd040924U, 0x3ede683ebddca756U,
0x3e9c6985bd827c29U, 0x3e1fa566bd10ecb1U, 0x3cde6afc3c92f8faU, 0x3d8862353e803ccbU,
0x3da4aa5ebe3750a4U, 0xbddf6c7fbd8137b1U, 0x3ddbdc3b3d8f4011U, 0x3cea72943e209f5dU,
0x3d42ccd1bd80aa60U, 0xbd37b5053d39865fU, 0x3c47e292bd1fdbceU, 0x3cc8e9bb3d95c1b7U,
0x3ca7607e3d593cd5U, 0x3d85e367baf2cc25U, 0xbcc11524bddbf6adU, 0xbd602efd3de06106U,
0x3df3dc92bcdef247U, 0xbd011ee33c1ea5ffU, 0x3d89ee293da4cee6U, 0xbdb5bf49baff11e0U,
0xbd70a57a3c9bb0d0U, 0xbce4f6d53cf393b6U, 0x3dce4f98bcd37d72U, 0x3d9430f83cf851e6U,
0x3c77108e3d25714aU, 0xbd42844bbcbd0e0dU, 0x3c0e1e84bd4606a3U, 0xbd63744abd1ca21fU,
0xbae2072b3d53d687U, 0x3b973916bbaffa88U, 0x3c8a348abc310ff8U, 0xbdafb71a3d10942aU,
0x3d726c183db8b39fU, 0xbcbddb743d4b2a80U, 0xbe3a611d3dfeba6dU, 0xbd8487263db3d003U,
0xbad6d699bc7b9a35U, 0x3da25014bc58bdeaU, 0x3df39233bd406231U, 0x3cf889d93daf9cb4U,
0x3dd290da3d8250b0U, 0xbd214c293e0e01e9U, 0xbe2a95603d6ed847U, 0x3e06e4033d0b00d1U,
0xbca05b593e38be11U, 0x3e0d5dff3d26d8beU, 0x3d8a680bbc2ed3bfU, 0x3c36492ebcffb5e1U,
0x3dd3dfa93da437e6U, 0xbd8f5c323d5009d7U, 0x3c833f003dc7e41bU, 0xbcba12c2bd1ffb9bU,
0x3d9e6815bc802821U, 0x3c441a7e3cecf6c9U, 0x3d1cd49ebcbbeaa0U, 0x3d1579543e2e5674U,
0x3ddf55d63e3813f9U, 0x3d4c5cd23e2b7da0U, 0xbc3f83bf3cbcba9cU, 0x3dc5b2563d9f2b26U,
0x3c53dd3dbc1ee05aU, 0xbe08b2abb92404e1U, 0x3ddfc44fbd6bbd98U, 0x3dbb97ce3d1dc8abU,
0xbbfcfe833cb86a5bU, 0x3e3df7113e54d418U, 0x3e039dbf3d1e52fbU, 0x3e09d1393d8bec2fU,
0x3e257314bc2528d2U, 0xbe87deabbdf2a564U, 0x3e0eb4473d970b4dU, 0x3e1dd288bde992a1U,
0xbdcbaa833db8e989U, 0xbc881c453db418a4U, 0xbe438271be9ad4f4U, 0xbe0566f53d905543U,
0x3d8650b9bdfa2707U, 0xbd9bfa72bdf1f65fU, 0x3de3ec1bbd9f4afbU, 0xbe8723a33e32b949U,
0x3dd2aa5ebdb111a3U, 0x3bc1a904be634336U, 0xbdd043e23d27237eU, 0xbd90a115be95d09bU,
0xbe26b338bd7b5cafU, 0xbde1c7e0be6515d8U, 0xbdd2ca5e3df0aa8eU, 0xbe33502cbcba5e58U,
0x3ca57b7fbd171a41U, 0x3d2613013e251fb8U, 0x3c5aba55be01c23fU, 0xbe04f3f8bcdab430U,
0xbd1fd81cbdfde844U, 0xbdc9c084bd6d29e0U, 0x3c24749fbe0a8af8U, 0x3e2592763e177d97U,
0xbe023fbdbe21bc59U, 0xbc2117f8bdc9b17aU, 0x3d20da3dbdf8b9d9U, 0x3d913bd63cf337f9U,
0x3e9f90fdbeb219b1U, 0xbe3e6fdcbd7f504dU, 0x3dd23551be320748U, 0x3ce57cdcbe23c5aeU,
0xbedbe1a2be0ec2dfU, 0xbd4419f9be9cb163U, 0x3d8f792a3dc1e6b9U, 0xbea3ba68bde7cf2bU,
0xbd6deb1fbe49b955U, 0xbca459cb3e2dce2bU, 0xbe0f5cf3bdd8a6feU, 0xbd9155253dfa0869U,
0x3cf47d87be4923c1U, 0x3e1e9c663bb2be09U, 0xbd62bf52be87def7U, 0x3ce587aebc132f80U,
0xbd9878ff3e1abe9aU, 0xbe2f13d2be0af796U, 0x3e6bd7bfbcc414a6U, 0xbc8545e5bac0fdbdU,
0xbcb8bb77bd3385d1U, 0xbdcf90c9bdb355bfU, 0x3e20ec753c2388caU, 0xbdc8f9583d4bd390U,
0xbdac1195bde4f2d1U, 0xbe1e1019bc0f9a60U, 0x3d69aa8abd9b6d47U, 0xbe02756ebead31d1U,
0xbe55977d3d519c53U, 0x3e6ce626bd98815eU, 0xba7e073cbd47b136U, 0x3e6f385a3e121586U,
0x3c857749be18c9c6U, 0x3dd2f000ba8b757fU, 0xbd88e1383e901e7eU, 0x3c8f5cf33cb05822U,
0xbbb4a2193d79ca12U, 0xbdd1341a3d221bf3U, 0xbd5fff66bdaa4093U, 0xbea4660dbddff417U,
0xbd3f5293be712651U, 0x3da8d9343baeaf0cU, 0xba96d1ffbdb91780U, 0xbce95932bdd5b661U,
0xbd8dfde7bdab7442U, 0x3ce8dba4bde8a84cU, 0x3ddf40333d8ca1e5U, 0x3d26a93a3d7c3768U,
0xbe1f133cbdd69094U, 0xbe2b5e7dbbff9850U, 0x3ba1fb173d922c02U, 0xbd2b2529bdba0dfeU,
0x3b8c4e103d9068b6U, 0xbcc4cc5a3dc95097U, 0x3db73f9cbbc7d9ceU, 0xbe26aeb8bd7272e9U,
0xbe0e0da43dcb74c6U, 0xbd1d7cfa3e00719aU, 0x3d78e2cabdafcc75U, 0x3a975c713d8f528dU,
0x3c610330bd96d58aU, 0xbe137a5a3c1bdbc8U, 0x3d9dc659bddad810U, 0xbdaffcfd3c9a1b34U,
0xbde061233b02f4e2U, 0xbdba9bee3da9d667U, 0x3d4e287f3d9b730fU, 0xbcb73a56bdca1d67U,
0xbd8f92f3ba1c0657U, 0xbc8ae6583d597062U, 0xbdc17445bd0dd457U, 0xbde5b941bd87ab97U,
0x3dad9bcc3e077369U, 0x3cbd79dc3d8d028eU, 0x3dd37b2ebc0db257U, 0xbe18a11ebd916fc9U,
0xb9a6ce3e3ddcf723U, 0xbc62543bbe136a07U, 0xbd606648bdd66ea8U, 0xbe27fef5bda638b1U,
0xbda46e733d99f55dU, 0x3d2d65bdbe40a5eeU, 0xbca4de42be24f50fU, 0x3dd024863cfe2d60U,
0xbd9024e3bb16fef4U, 0xbdf3015bbe138c97U, 0xbca80b763d7db297U, 0x3d604d6c3d5c690cU,
0x3da8569e3dd30b25U, 0x3d9047ff3cd0bb5bU, 0xbe01e076bd190264U, 0x3d84836cbdf71becU,
0xbc3f3001be0ed15cU, 0xbdfe5ca1bc8d1ee6U, 0x3d31ea2fbe2b3df7U, 0x3dd558193b8affecU,
0xbe2d1fa23d077f3fU, 0xbe8857a23dbadde8U, 0x3c0b6ca9bbe6652cU, 0x3d949d3e3dbebedaU,
0xbe4972a3be0ad38fU, 0xbdc6f689be76d1f1U, 0xbd065d17be199ad7U, 0xbe85d2433e2a5df9U,
0x3e3849253e9784c4U, 0xbe94fc09be61a0e2U, 0x3dd66166be5ad380U, 0x3d35826cbe865752U,
0xbe348be23c9a63fbU, 0x3d302960be9da981U, 0x3d40060abd4208b2U, 0xbd80de77bdf928c1U,
0x3d2e5590bd57ca48U, 0x3e7fa00ebe35f487U, 0x3e25cf2fbe9987ddU, 0x3dd3795ebe887aa4U,
0x3dc5f1b6be1dd3d9U, 0x3e350d123e011d7dU, 0xbe014740bd361e8fU, 0x3e669e5e3e4174beU,
0x3e2857593e040877U, 0xbde4387ebc8cdf36U, 0x3e3412c23e24a7cfU, 0x3e6e2937bea70dfdU,
0xbe4d59cfbccb9728U, 0x3e4f2115be7ac284U, 0xbdac680d3cab314dU, 0xbebba816be62e40cU,
0x3e2b5dee3dc66788U, 0xbe4301c33e7102b2U, 0xbe55baa9bdc3b523U, 0x3e29f51dbdb8d670U,
0xbe14b1e0be8a02fcU, 0xbe768cb7bd865df8U, 0x3e1fd16c3e235ae7U, 0xbed0dd17be684a00U,
0xbdb5a14bbeda519cU, 0xbe67b3d33e74dba6U, 0xbecadcb13e28efe9U, 0x3e4b4969bdbacc0dU,
0x3db2a1d9bd87a9e4U, 0x3d278d503df876ecU, 0x3e2639493e8e96f0U, 0x3e3d1fb4beacabe2U,
0x3d55f50cbe11cae0U, 0xbe187d3cbe33fd0eU, 0x3e58c4423c415ed7U, 0xbde16bc13e6043baU,
0x3e38ebfe3c8d3386U, 0x3dcd85523db4fbc0U, 0xbde46efbbd5100f6U, 0xbeb2e26d3e58f871U,
0xbeef663fbe125c70U, 0xbe58e17d3de7a012U, 0x3e51decf3e69cd3fU, 0x3e1040cabe4fc5a9U,
0xbdd4c4103d682e2cU, 0x3ddd3bd93e6ff424U, 0xbe9631dbbdc7c248U, 0xbe4e04d7bdb9913aU,
0xbc1dc1f13e532e42U, 0xbea938223dc7f4b7U, 0xbb746e803e317a64U, 0xbe5166bbbdd5c5abU,
0xbdf642873d1d0d97U, 0xbe4452d3be013aa6U, 0xbceb1b03bdb35460U, 0x3cd1984bbdb1ff9dU,
0xbde64a593d109820U, 0x3c19acecba75ade2U, 0x3d367d5ebe2e533bU, 0xbda5dd5b3d0c0ba2U,
0xbe186b88be992810U, 0x3c555e80be046e75U, 0xbe1d84083d35e2e3U, 0x3dc058ebbd9a1f3bU,
0xbdd565b7be1e58f6U, 0x3d17770b3c6d95afU, 0xbe4a844e3db217eaU, 0xbd8f3b77bd2af80eU,
0xba3e03003dbd9bf8U, 0xbe0a5cf33e222bf3U, 0x3e90171fbc528024U, 0x3d4afafe3cbd7a54U,
0x3e1d9626be225f9cU, 0x3dd00fe93c8a31f2U, 0x3d78c9e33d4e7b11U, 0xbd903b5dbe5b0781U,
0xbda3e2b73d62a20cU, 0x3d4d02e3be2e5964U, 0x3d3d11efbe7a8522U, 0x3d98005cbdb0d4a6U,
0xbc6c5fb9bd89d266U, 0xbd96f219bbd4cc54U, 0xbdfb9b47bc6c26dbU, 0xbe161750bdf409f2U,
0xbc9290c3bca42147U, 0xbd6872693ca62ec1U, 0xbe959930be531830U, 0xbbc67c39bdbd7daeU,
0xbe8cd8823e0b6b5cU, 0x3dc1bba23d1d4b4fU, 0x3ca980a63e0dc1faU, 0x3dfb5afebde77a51U,
0xbe182a7b3d7da2dcU, 0x3ddfd1013cb792b2U, 0xbe214e37bc9ba980U, 0x3d947f603db3de72U,
0xbd9b0c21be42da01U, 0xbe004cc6bdc8e531U, 0x3b3c9cb5bdb6c876U, 0xbe12b00ebe5eb81eU,
0x3d9f7f0b3e0f2dffU, 0x3d364ee63d7ae4b2U, 0x3d2d38ae3c642bdfU, 0xbcd7f45a3e02da60U,
0x3b4dbaad3dcc3495U, 0xbe5effeebe0e0052U, 0xbe326f5bbe2f39fbU, 0x3d6be089bd402d66U,
0xbe01d31c3dbe4056U, 0xbe2ab6f6bd565888U, 0x3d9ccb1ebe3eeef0U, 0xbc0f0476bdbf24f5U,
0xbdaa35dcbe12d7f1U, 0x3c3047fe3d26f723U, 0x3da11b283e1a2298U, 0xbd862b13bdf02c6dU,
0x3d540bb53df43a0cU, 0xbdc5d35dbe04464fU, 0xbdd77b52bd4f7e6fU, 0xbe11e70e3d18ec3fU,
0x3e3f7ca43e5c5312U, 0x3d8882753dbc5d1bU, 0xbd2fc94abd54d3b0U, 0xbe748935bcf3b10fU,
0xbe0b4ceebe5d5aa9U, 0xbe5872213e2a8a84U, 0xbb8402373e9cb833U, 0xbd7269acbd01d02eU,
0x3c1ed9ab3e26c364U, 0xbe1e0c993d341766U, 0x3eba64883d92d414U, 0x3b98e9123cb88946U,
0xbc9168783d5b57a7U, 0xbcb416663b6ddbe0U, 0xbe3647a13d643561U, 0xbd79b6883d7fb0f3U,
0xbde97affbd85da65U, 0x3db11588bdc2bbecU, 0xbd1ca3cebcfcb24aU, 0xbdb5c52b3e2ec8daU,
0x3e991511bdc9e104U, 0xbb3840f83d47f4a9U, 0xbbdbaa00bd84ba73U, 0x3dc6d3a33d908203U,
0xbcfc3e8abcd6bfddU, 0x3e63eefd3e140a6dU, 0x3beb0cfcbdd46efeU, 0xbe1857efbe0bc5f3U,
0x3d932a43be50b8b7U, 0x3e091bbbbd4bf665U, 0x3e941eeebea06f2fU, 0xbdeb7faf3cac6d8cU,
0x3e90bc81bc357d86U, 0xbcca8d82be452016U, 0x3cf655fd3e360a38U, 0xbd67dd4abdf9a58cU,
0x3e85a7e8bd864556U, 0x3e436e15bd2188e0U, 0xbe046836bea6afc7U, 0xbe39a9743e2984cdU,
0xbcee8cbabe29b1eaU, 0x3ca3018e3c1ad704U, 0x3c0cf9853e1e55f4U, 0xbdcd8a1c3de31e7eU,
0x3de816a6bd73b7ceU, 0x3cb35400bc79f263U, 0xbdfdc9e93d3178dcU, 0xbd8e64debddbaf8fU,
0x3d22acc9bc8c5c24U, 0xbd0639813dc1771eU, 0x3ed01c99be10e0b7U, 0x3ebd0fdb3e783ad1U,
0x3e68de21bddec619U, 0x3c22bc68bdb2b179U, 0xbe0182fe3e3b177dU, 0xbdccfef53d748f47U,
0x3d0ad5c6be1ff820U, 0x3e78254abe12325bU, 0xbe2450043e2da6f3U, 0x3e04cbf9bdad38c3U,
0x3ed30fe9bd5dec11U, 0x3e925feebe313936U, 0x3e403453bdf16ed3U, 0x3d80c2473d55fbf5U,
0xbc87ca053e957eceU, 0x3d9ae0903d60eab0U, 0xbdc50d703d8fd246U, 0x3d454cf9bd8f387aU,
0x3c2bf68dbe6f36edU, 0xbe827b413db74c4aU, 0xbcc71267be90f341U, 0xbd41cf76bc808f81U,
0x3db54ea33d0ae747U, 0xbd925119be5bb2f8U, 0xbd06c0053ad00915U, 0x3e1ad739bce486faU,
0x3e93fcb23b31ab13U, 0x3cdcc4a53d1a1a06U, 0xbdc5d1a33b5504dcU, 0xbe298b92bdcbedfeU,
0x3e7158d93decd75eU, 0x3cd3ed69be167589U, 0x3be9fe4cbd7b5729U, 0x3d5eaa3c3dcea051U,
0x3d7f0259bdf8e927U, 0xbe16ab0bbd9c8d4fU, 0xbcc4b3663d2a52c8U, 0xbe3d4936ba87e838U,
0xbc366714bca234bbU, 0xbd6c0c403dfd3947U, 0xbd4e4a0bbc8ab4e2U, 0xbdbba112bd7277d7U,
0x3dd1e968be94eaa8U, 0xbd1362983acd9f93U, 0xbd8b18803d59b3a1U, 0x3d8ed8893c4b24a8U,
0xbd4169cf3d5a98a3U, 0x3e0ab0dcbdfc18ffU, 0x3e0fbabc3da3a23bU, 0x3d1d4d14be01e03aU,
0xbe693dffbe547d40U, 0x3d1d6b2fbd93d0a5U, 0xbd1502923d0e6c95U, 0x3e03dab5bda178d5U,
0xbd71d0aa3d70409eU, 0xbda00ea1bbd734cfU, 0x3dc0738e3e396b4fU, 0xbab6cedfbcc52bd1U,
0x3d0ee890bd995b57U, 0xbe3721723d6f4aa8U, 0xbd9241653bf132b5U, 0xbc800be2be0f585cU,
0x3e9532a8bdf6183fU, 0x3e1a42da3d5fbb36U, 0x3cbfff48bcd7865eU, 0xbcac236bbe28f7dbU,
0xbd52b0663d520a9aU, 0x3d30d8d63ce2a2eaU, 0xbd6ce14f3db4f283U, 0x3e411f32bd0c435fU,
0x3dc6f520bd261e0dU, 0x3bb556443d0616eeU, 0x3c417a39bc956d98U, 0xbc94d9903d9514cdU,
0xbd1def82be919681U, 0x3ddd5a76bdc9c91cU, 0xbdb5fd3a3ceddc6bU, 0xbe8681de3cebf3d6U,
0xbd9f8674bd8935deU, 0x3d3b3b1e3c3598feU, 0xbe449d50be1d5c66U, 0xbdc23835be24b976U,
0x3e0f87cfbda20f93U, 0x3c346e893e0294adU, 0xbd7c3b643bcf21ddU, 0x3c323112be11cb78U,
0xbdc83f8fbc9c9d5cU, 0x3de4d5d3bcead34eU, 0xbe2423c4bd818f54U, 0x3d7a7136bd905c79U,
0xbe24e5b9bd996b01U, 0x3c941a97be3b3228U, 0xbd41b0a9be702531U, 0xbd82d3a8bd5564c9U,
0xbe073f9dbdb2c315U, 0xbe0e623cbcb07abfU, 0xbd817233be87fa74U, 0xbbf7984b3d93e84eU,
0xbe3768fdbd80787fU, 0xbd212cdcbd37943eU, 0x3c9c70e13e3fff87U, 0xbd71323abd86cec5U,
0x3caf01adbd9ca063U, 0xbd224821be0e78c3U, 0xbe3459e83c3a3fecU, 0x3db995d8bce1b7ecU,
0x3b90726f3dda08e3U, 0xbcb9778dbe16b01aU, 0xbd31865dbcb03d39U, 0xbddd51cfbcd5d05dU,
0x3cb67658bcc389ddU, 0x3e706e51bdd4216aU, 0xbdf4dfa9bd67ab92U, 0xbc752ad3bdbddc61U,
0xbd8431d7bd921d01U, 0xbe5ee1bbbdb4f916U, 0xbc496485be15d86fU, 0x3e19171c3da94fd4U,
0xbd4109ddbddd384fU, 0xbce32a48be31a18cU, 0x3d9098733e120d9dU, 0xbe01c438bdc851f0U,
0xbddbc1d13c65e804U, 0xbcd4ac7fbb9c940aU, 0x3da56ee53e1c99baU, 0xbd416df4bda48b30U,
0xbd084053bd38ea21U, 0xbe111fdc3defdb53U, 0xbd0bf225bdb0be8aU, 0x3d4a82d2bcbc00dcU,
0xbe3ff108bb46de8bU, 0x3d15ad483d041d2aU, 0xbc335f12beaeb637U, 0x3dca7a90bce4900aU,
0x3cd69faebd851d3aU, 0x3d24135dbe242464U, 0x3d6343e13df2979eU, 0xbc22e890bd851a06U,
0x3c9cbb32be003028U, 0xbe2ad9d2bc12c33cU, 0x3dce84983ce470ccU, 0x3dac6911bcfcc848U,
0x3e1f0e7f3e08df33U, 0xbdb798f8bdb1ad70U, 0x3d5957393d29de1bU, 0x3cd027523da9d301U,
0x3e9d13d7bd346917U, 0x3cda632e3e08df1fU, 0xbe350ac93daf724aU, 0xbd8c728c3dec5bacU,
0x3d526842be425657U, 0x3d5ccc843dd938dfU, 0x3e96d126be205c3eU, 0xbc70d7913d2d601fU,
0x3e1575563d2f9497U, 0x3c25bb97bd67cd05U, 0x3bb076b5bdd86173U, 0x3d3e78c23e43d72eU,
0x3d16fdda3d23b579U, 0x3e1ac9fcbd55af41U, 0x3db259af3d86e11eU, 0x3da58109be37e323U,
0xbdc973b93c48042cU, 0x3d924b7ebe54031fU, 0xbdec94233df78bb2U, 0xbcaa9360be00bba1U,
0xbcce36d4be30837eU, 0x3dc6af593e894c1cU, 0x3d98ee43be4b91daU, 0x3e4fadcbbde570b7U,
0xbc1d55e73d90a4d6U, 0x3e512650bdb3a319U, 0xbbb2705c3e7fb672U, 0xbde6ce203daba720U,
0xbe3d43bbbd734919U, 0x3d70ec833d868b8dU, 0xbdfff34b3e89cdc4U, 0x3e153d2bbc958d1aU,
0x3c985ff1bdccf35eU, 0xbe45a77f3e99d2b5U, 0x3d2688813d0b4a70U, 0x3dd9b1a63e55a53dU,
0xbe8284d536650b1eU, 0xbe3c22613e4d0579U, 0xbd39eac23e6b8f3fU, 0x3d80352cbe176ab3U,
0xbd907c5ebe3f642bU, 0xbcc2d502bd9c8d5eU, 0x3e449df6bdcc76c5U, 0xbb94912d3ca2b54cU,
0x3c8e7b12bdb4611cU, 0x3e1d729b3e123a0dU, 0xbdc34b44be29263aU, 0xbda35044bcbc57ebU,
0xbe18fa3ebe0e2943U, 0xbd739fdebdaef85aU, 0xbde8609a3e00be32U, 0x3e9d13793e251da2U,
0xbced19c93ebd784bU, 0xbd5b9c3f3e80ae73U, 0x3e70d54bbe155c6bU, 0xbe03efcabe085924U,
0xbe4e5ff7be192b34U, 0xbdf5da473d5c2910U, 0x3e6f23463e85deb2U, 0xbd3b70b13dcce683U,
0xbe0e554b3dc20612U, 0xbe09db2b3eb34357U, 0x3d83cc9e3e11b041U, 0xbd0f04163e61b79fU,
0x3d6618453d526ad7U, 0xbda774273da0ffc0U, 0x3d939be53dff3766U, 0xbc58beefba1bd570U,
0x3e2c1cbebd0459b3U, 0x3c80238dbd634377U, 0x3da822623cf278e1U, 0xbe16290dbc3eab4fU,
0x3d7f69c03ccc58aaU, 0xbd81b6ea3a5ab29fU, 0x3e5c2a98bd6aebbaU, 0xbe00a5c93ddeeef4U,
0x3d2f7b893da6576eU, 0xbb1ea89a3bc21971U, 0x3d3defa03e069488U, 0xbd5455abba197908U,
0xbd4c29cc3dd577b1U, 0xbd9af5d43c0d33cbU, 0xbdeee8d63d8a9186U, 0x3d88e8d03dad8f40U,
0x3ddbea483d87b9f3U, 0x3d792a5e3e0fd06bU, 0x3dfa7c4f3d41689aU, 0x3d41e62abc177fdeU,
0x3ab2dbc5bd550ab8U, 0x3e1ad1613e23a682U, 0x3be8157abcb03882U, 0x3ddcc6df3dd82c39U,
0x3d8011a2bc626ecbU, 0xbd3fc55bbd39b18bU, 0x3df198b3bda5618cU, 0x3e086405bd810f0bU,
0x3e4ada1abda3b6c4U, 0xbeba03e23da2cd7aU, 0x3d625a743de8d3e6U, 0x3d480956be3007dcU,
0x3d68e4583e178615U, 0x3da5f0bebb64cc31U, 0x3e09bfe13e047e04U, 0x3df341b9bcb220a3U,
0xbdf0a8c5bdb091dcU, 0xbd7c373c3d518822U, 0x3d7a6c19be3447b1U, 0xbdd8fff63e0dbd1dU,
0x3afc85fd3d53ea66U, 0x3de504d93e202d78U, 0x3e2bc045bdb8461fU, 0x3d6348abbdd2ac5dU,
0x3d3cdd783e31346bU, 0xbde814853d3fdfdaU, 0x3e107e913dba56a6U, 0x3cd1cbc8be6b22caU,
0x3df79b1cbd9c0c10U, 0x3e4a4e723deb944fU, 0x3ce27d783b1f2ecbU, 0xbdade705bd3c7090U,
0x3d2c48343d5527d4U, 0xbe28d9c9bc1fdee0U, 0xbc017497be27b8e6U, 0x3d1b7d4d37fa514dU,
0x3d39f597bcaa190bU, 0x3dfb0b8a3dacffb8U, 0x3e1c28d73d4f7dc7U, 0x3e9079d73d1f24c3U,
0x3e1874b5bcdb7e64U, 0x3c2d5bed3d96bb22U, 0xbcb23a673e0e51c7U, 0x3d2ac58bbdea86baU,
0x3d2a7d20bd5b4785U, 0x3c76c80ebd958433U, 0x3d77827e3e5eaa16U, 0x3e15d9f03d596d66U,
0xbdce53a13e9303a3U, 0x3c0ade7fbd71d453U, 0x3e46ba17bd270e97U, 0xbd0beb613deb4a4bU,
0x3df9ced03da527b7U, 0x3e281167bde9570cU, 0x3e416c08bdd6b9a3U, 0x3d87364d3e1c5ffeU,
0xbc91067c3da4f5aaU, 0x3e9062fd3cd250deU, 0xbd1d9b8b3d92e114U, 0x3e6b357fbd4bee97U,
0x3d89ec6b3dbc8aa3U, 0x3dd12ae83dd40f17U, 0x3e89517a3d9b122dU, 0x3dff040d3cbd3838U,
0xbdaff0aabde169e4U, 0x3dc2ffc23e2a7c7bU, 0xbda79da13db57be7U, 0x3e1a9a063da4dd37U,
0xbbfc0b6f3df2da0bU, 0x3d863bb4bdc78f15U, 0x3daf77c03e96e66aU, 0x3de36e1f3c01a9b8U,
0xbc04f6813e4cd05eU, 0xbd5827f3bd329536U, 0xbdae86c93e77b1dfU, 0x3e01da493bf74b5cU,
0xbbda0408be0acc0fU, 0x3d8489dd3cd94097U, 0x3e4740283e7f4518U, 0x3e68f7623e183194U,
0x3d9adcd4bc945d47U, 0xbe30f4ef3cc3feeeU, 0x3e883b6cbac6bba6U, 0xbe0f33163e2bc47bU,
0x3d365fad3e33b59dU, 0x3d732739bd248054U, 0x3cef7c5ebc421713U, 0x3e1023583deb158eU,
0xbde59fcf3d56d345U, 0x3e438f423e0370e7U, 0x3d818a803dda6c90U, 0x3e32ee64bc9f5f0dU,
0x3dd9ceff3dcdd2bdU, 0xbdd00f033e73ca96U, 0xbe0665ecbcbbf65fU, 0x3d9c6e723d957866U,
0x3d44f762bc584804U, 0x3d06c58f3da7962fU, 0x3df619253d0d47f2U, 0x3cd17e1b3c555786U,
0xbd18efe23d73029dU, 0x3e09e9dfbd021803U, 0x3e08f39e3e2f0293U, 0x3d8b455d3d8910abU,
0x3e8407013d9d2bc7U, 0x3e2abe393e514390U, 0x3d9e28c13c3b6669U, 0x3d2181a53dacbe3aU,
0xbe3db86cbd9f68acU, 0x3dc139043e2d9cf6U, 0x3d8771b03ad017fcU, 0xbd8d37d6bdf2215dU,
0xbd0de13f3d191ad8U, 0xbe1d5ad8be534817U, 0xbd33f1c23c02c6b1U, 0x3d338dbabd5c117dU,
0xbc91e5b83c313332U, 0xbc3a94e13a836d78U, 0xbe186f0a3d914e8fU, 0x3e83d69e3d013106U,
0x3dbf76243c8fa06aU, 0xbdc57880bdb28de9U, 0x3da35a77be05d0ffU, 0x3d4eab4abe3f6973U,
0x3d8659dd3c175dd2U, 0xbcc99566bce8ce46U, 0xbcf098a7bd0e57f7U, 0xbd9eebcb3d349a2aU,
0xbd113b083e1527afU, 0x3c0ec8f0bbee0abeU, 0xbd4b8e60bc58100bU, 0x3cb6b4f9bce1cbc5U,
0x3a3b62d83ded0bd1U, 0xbe047c6cbd36efbaU, 0x3e0910e73de31b9dU, 0xbe682a10be4d76cbU,
0xbcba7ae2bdce8886U, 0xbc20b879be0a390aU, 0x3d857e563c88d31cU, 0x3db25681bd9232a9U,
0xbe5e5cc43d630647U, 0x3ddfbab03d98f6d0U, 0x3e0a971abdcc79f0U, 0xbe4b085d3d54a9d7U,
0xbcf306e6be2f5dceU, 0x3d55507ebe2d71f0U, 0xbdd8bf4abc96b70dU, 0xbd231394be0e5fa0U,
0xbe01fcbc3cd85e4cU, 0x3c9d6adc3ba3addcU, 0xbdda67bd3cf58998U, 0xbd321907bd771661U,
0xbc569b09bd677ed3U, 0x3dc5f639be974257U, 0xbd6f99223c4da6a9U, 0xbbdfddc93d54df0cU,
0xbd7131123e1cc995U, 0x3e1ff350bb1b761dU, 0xbdedfb56bda9ad9eU, 0x3d67b8b5bd50d29aU,
0xbc6f3af43e0c993cU, 0x3e4c87adbd99229eU, 0x3db101793d9265f4U, 0xbbd003b23d53437eU,
0xbe22445fbddba329U, 0xbb1281c83d78eb5bU, 0x3d98a813bdb4a3faU, 0xbe02f95cbcfcef59U,
0xbc51683fbc84f9a5U, 0x3df9fd25bc5d1531U, 0x3e161861bdd32a8cU, 0x3dd9f87bbe16c226U,
0x3c3b60d13d8eb872U, 0xbb5e49aa3e2ba353U, 0x3d60b38abdfa04c2U, 0x3d9eb3bb3dc19525U,
0x3c0c48b8be114348U, 0x3d68b4d7bc75e8d4U, 0xbcf8d9393d5cf83cU, 0xbd3b01273c1a6cdeU,
0x3c9f10eb3bcb0680U, 0x3de65fd3bd87bdfdU, 0xbd5c1397bd61e88bU, 0x3d2c58b13dac834aU,
0x3dd96326be21840cU, 0x3dd3c9d53dd22644U, 0x3c4dc0983d83a54aU, 0xbde9ee65bd2f098cU,
0x3bdf744dbd9e01c7U, 0x3e3448703e1ac6a2U, 0x3e01a34fbc1ffcbaU, 0x3d47d723bda8757cU,
0xbd99b1dd3e43f848U, 0x3dc39311bdc059edU, 0xbd37e24fbcd8cb05U, 0x3ccd75f3bd30afd5U,
0xbcde399cbb769fc4U, 0x3d469422be05bea8U, 0xbacaca2f3de9c9d0U, 0xbdce181cbd456b6fU,
0xbd57d5573d9e0ad2U, 0x3dab0948bd2b3049U, 0xbc456688bd33bee8U, 0xbda3a0213df7fd52U,
0xbbd761a93db2d3d7U, 0x3dfc50943bcc3941U, 0x3e5af7c6be2c6076U, 0x3dc7d12b3c1d804aU,
0x3e456aa23ca5983aU, 0xbdadd41b3cae2df7U, 0x3cc333d4bce20511U, 0xbd02e2f93d966eb6U,
0x3d0b5e293dddf7beU, 0xbd2178afbd9fdb37U, 0xbdbeda8f3cbf094dU, 0xbd815f633e44b83cU,
0xbcf32ac3bd4b4483U, 0x3db664e8bca8d97aU, 0xbdd2448d3dbbc2dbU, 0xbd911ccd3bc469efU,
0x3dd6c1e6bdd554d2U, 0x3e259874bd0d5af4U, 0x3dca6d3a3d2ebcf6U, 0xbc7be6f5bd312779U,
0x3dae901cbc9cd957U, 0x3e23b8bf3d61a066U, 0x3d80afd13e1ccfe8U, 0xbd86a9193df3c2c0U,
0x3e4f72063ca0d62aU, 0x3cb719f0bd573eb7U, 0xbd1d804bbe353917U, 0x3e1221c8bc897bceU,
0x3d5bbf84ba5833b1U, 0xbbf2bb55bb729025U, 0x3c324f04be00d4e8U, 0xbcefcd533e2d9298U,
0x3b6e3b043d34683eU, 0x3d4f83fa3d0094e8U, 0x3c4673bd3d8ed600U, 0xbe13a79e3bec204cU,
0xbdb08e13be874286U, 0x3db1b11f3cf77b57U, 0xbe00d3c6bd6a6d55U, 0x3d20fae3bd464557U,
0xbe56ee68bcfae91eU, 0xbcc0f2973da46565U, 0x3d508d75be20b771U, 0xbdd74a42bd89376eU,
0xbd6169edbdf14a93U, 0xbcac72083d71888fU, 0xbe04b4bdbe636e3aU, 0xbd2ea17ebe6591d0U,
0x3d420093bd02e5caU, 0xbc9267913b2f0073U, 0xbbedf4f2be16a8a0U, 0xbe2b79d4bdcbed77U,
0xbe036a783d8ee145U, 0xbe7a6eb0bd824a1cU, 0xbd622313bbf97633U, 0xbd8512b93d3c0e54U,
0x3b824faebe25141bU, 0xbde225443c9e6e94U, 0xbd44bcb4be08d2dcU, 0xbe784e85bda8907aU,
0x3d3fea44bcf1c973U, 0x3cf9de30bd197ff4U, 0xbe5d0262bd5cb82bU, 0xbd7094eebd962be0U,
0xbe8bb142bdab31b4U, 0xbe19f20b3c2706b5U, 0x3db4662abd055df1U, 0xbd5a76acbdce0418U,
0xbcdba584be8bc1ebU, 0xbd983787bd29e13cU, 0xbe42ce7ebe81f85eU, 0xbdd07f0abe307c37U,
0xbd5f36b0bcfeb295U, 0xbe500b76bcb33111U, 0xbc9c399dbe093493U, 0xbd605b78bd40eeedU,
0xbd72ee543c0345e2U, 0xbd7199593d960731U, 0xbda90d00bdf1c1ffU, 0xbdf5b5d9bbda41caU,
0xbe10f697bcfa378bU, 0xbba9664fbd006da7U, 0xbdf022ed3d94ee2bU, 0xbe1c2d92bb778b5fU,
0x3d59d117bdc4b338U, 0xbdd1c5c13dcacdfbU, 0xbd4d1da7bda6794aU, 0xbe94979bbec491d2U,
0xbe32ff8dbd3a2211U, 0xbe0efba1be0ccb72U, 0x3b4dd8e9be62f468U, 0x3cd79ce1bba4379dU,
0xbcd80c47be0da647U, 0xbe25cc2bbdfc9433U, 0xbe4a9ca8bcfb058bU, 0xbd7329fabdad1dd2U,
0xbe1a7b37bd135fb7U, 0x3d52d8acbd5786a7U, 0xbe8bbad03c719c2fU, 0xbccd15b03cb35213U,
0x3cae5f573c95bac4U, 0xbef3a926bccacb39U, 0xbe2b4006be21e312U, 0xbdb56c04bdf971acU,
0xbd5abb14be82213cU, 0xbe3ec08ebe026946U, 0xbe313274beb01844U, 0xbeaa01bc3d98b5cdU,
0x3dbb4cc7bd7b402eU, 0xbe8a047dbe6d9d1bU, 0xbd93ad88be18ba79U, 0x3d14867dbcb19260U,
0x3e38d87ebe2677c0U, 0xbdcb77e6bd96d19aU, 0xbe181e71bdee0777U, 0xbe80c539be58b479U,
0x3d0400313dc7e052U, 0xbc06fcedbe8397cbU, 0xbe93f66c3d10a5a1U, 0x3cbf5b28be72e1a7U,
0xbd2b2a203dc56980U, 0xbdb218093ccf854cU, 0xbe244dc5be8b434bU, 0xbe27d9373dda8463U,
0xbebb3d2cbd976461U, 0xbd929c0dbe96017bU, 0xbe248649be0e33bfU, 0xbddfaea2be93b114U,
0x3daa9831be7208a3U, 0x3d8c598d3c940d81U, 0xbd9e7445be89d6a3U, 0xbc0c8bcbbed1a833U,
0xbe2b34f53b45d235U, 0xbe29fce9bb39f8f1U, 0x3db0a0aebe85bf6cU, 0xbe930b31bd24ba9dU,
0xbe68ce72bf115fbbU, 0xbe0654e9be821ea1U, 0xbd026fc9bdeaa4f5U, 0x3beb4ee3beee8765U,
0x3ca0265bbc778dc5U, 0xbd71866dbdc7ecdeU, 0x3d10b4f03e2eb6dcU, 0xbeb9df2abd8d8a06U,
0xbdfae8acbc496afdU, 0xbd1dfa153d60af92U, 0xbe673a87be1e3d9fU, 0xb98b5ca3bd87258aU,
0x3e1c5340bd9c1ac0U, 0x3e1c16b43de175f4U, 0x3d7ef39a3cb9049aU, 0x3dd69e93be89fce9U,
0xbf4355a6bea94302U, 0x3d5d08ebbf05d5eaU, 0x3c385186bec6b683U, 0xbda33fa23d14ec45U,
0xbd2ddc5abc5f2ebeU, 0x39bc83e4baeac804U, 0xbd994fc2be1090d0U, 0xbeb592acbe586e42U,
0x3e01d796bea43805U, 0x3e2ba668be0862adU, 0xbc79c603beb76d31U, 0xbc83e22dbe79ff9bU,
0xbe1bc5e5bf21f530U, 0xbd1aba273d0a5084U, 0xbebd493cbe6e1d57U, 0x3e5f5ae43e713f4bU,
0x3dbcb7cdbe1fd133U, 0x3e0a206dbbbccdc0U, 0xbc8a9bf23d897ed0U, 0xbdd67cb5bea8a111U,
0xbe6e86913d3351a8U, 0x3e0d104f3e296ef5U, 0xbd2bc6af3c8203d0U, 0x3d8908b2bd382a17U,
0xbe8a07e3bc2c8270U, 0x3ee941e3b9b3d502U, 0x3e0aa87dbda6ac84U, 0xbd63db3b3d35461bU,
0x3ddef426bdba5aabU, 0xbe1fca693d51e7aeU, 0x3d7236f3be1488b5U, 0xbb8cd50d3ce6722bU,
0x3d4d4b553d30c392U, 0x3e2448bd3e47c908U, 0xbc6a032a3e82578bU, 0x3e278db4bd44e103U,
0x3d0cfdd73a7df608U, 0x3cd76401be00dd11U, 0x3e26e21a3b1a5cb2U, 0x3c89a110bd38833aU,
0x3e54575fbc8482eeU, 0x3b8965abbe1ad8dbU, 0xbd1928a3bd1705c1U, 0x3da63d0abe025e14U,
0x3e7c0439bb86bf39U, 0x3e82dd9ebe371334U, 0xbe1fd6233dc404d3U, 0x3e87ae623df7627fU,
0x3e26474cbe0a3f0eU, 0xbcf893a53e5b1930U, 0x3e14454bbd8a1426U, 0x3dd8fff43db5bfdeU,
0xbd862ed6bd7947f5U, 0xbd84c791be8e4f2fU, 0x3c5935923e4a72b2U, 0xbd9e66a7be044f80U,
0x3c2b265f3e28d0d1U, 0xbd763344bcb2fb94U, 0x3d85ea6e3d56596cU, 0x3e20d42fbe9f4eb2U,
0x3d5050053da7f8ebU, 0xbd6ad6b03e02a041U, 0xbd0f56643a9430cfU, 0x3e11ff62bbf2c2b1U,
0x3e0c56873e28b0d3U, 0x3e1ab19d3cd6b3a8U, 0x3e1337a53e962f9aU, 0x3e80abccbc6e0e36U,
0x3d851bf8ba3f56f5U, 0x3c2508623d9191c3U, 0xbe473fb73d6ac1dfU, 0xbd806d8abd8e5cb6U,
0x3e051c70bc91724bU, 0x3ce2f9503e23a974U, 0x3d9930e83ba5627cU, 0x3eb96045bdb4b184U,
0x3eabd7053c9713b1U, 0x3e81a260be3ce689U, 0x3ceec60f3e078cbeU, 0x3d8a5a233e901e19U,
0x3e2d5838bcf8f980U, 0x3dd09c073e1b9847U, 0xbdfa32623e2de51bU, 0xbda2c8d33d28739eU,
0xbd200c7abe22753eU, 0x3dff4ebc3c9c03acU, 0x3eaaef44bd9218deU, 0xbdfe06d93e05e594U,
0x3dc4b67dbda59e33U, 0xbd82ec1d3df8f8deU, 0xbbf6675bbdf6ec30U, 0xbe1b89d23e4a9dacU,
0x3dbc20a93ddfaeedU, 0xbda532963d2c2662U, 0x3d8d3bbfbc164f95U, 0xbc5167c8be3129b0U,
0x3d7b3c1bbd8d247eU, 0x3b71c57dbda11510U, 0xbc241b053cd7e9b7U, 0x3d973f4abd99c4b6U,
0xbdf67ff7bd004389U, 0x3d3f7fa03ea615a5U, 0xbca3553c3cd0a71eU, 0x3e20c1a8bc93cb04U,
0xbd43a6f53db9c4a4U, 0x3dfa74933cf12154U, 0xbd3034ea3e3224d5U, 0xbe03a7cbbd7bc955U,
0xbde75503bd7e8f26U, 0xbcd7a70a3db9c58eU, 0xbe7a9a093e1633d9U, 0x3cdf8abf3e28308eU,
0xbc26bcdcbe81feefU, 0xbd75b4e93e953f77U, 0x3e26905fbd1f7c39U, 0xbda290de3ce0f0fdU,
0xbcf64fb33beb8df6U, 0x3c108d923eabd884U, 0xbe9c67cf3e094693U, 0x3db6dddcbd8622f9U,
0x3b12db12be0689e9U, 0x3ce0fadebdbaff3bU, 0x3e1416cdbd7ace0cU, 0x3def63ae3da10163U,
0xbde24791bd611e26U, 0xbc8783733d509823U, 0xbb518db93bb5cbe0U, 0xbd8ca1c7bd8a0740U,
0xbbd7f65fbd2f80afU, 0x3cdeadae3da84b6bU, 0xbd4c3e9f3d3bc7d9U, 0x3e0b3c583ec6ac30U,
0xbd8a10ec3eced4b8U, 0x3cd4d9363e6c4552U, 0x3e553b983c89f100U, 0xbd479f8bbd987dc9U,
0xbe0c18b0bd9430adU, 0x3c45c6f93d5b5a4bU, 0x3d9cc96d3e84f441U, 0xbddca51cbd3aa1deU,
0xbdb97c4a3dc37330U, 0xbd38267b3ea3de9cU, 0xbdd6b0d03e983909U, 0x3e16a2683e29def3U,
0x3eafea71bc63ed0fU, 0xbe53c7173d83b624U, 0x3e278ed43d93b20aU, 0x3e025883bdf0b73fU,
0x3dd4d4553d07cf20U, 0x3d8b93533dcc4ff4U, 0xbe06a3fcbda244f7U, 0xbca43469bd9d34d6U,
0x3cdcf8863d719309U, 0x3dcfb3233dcbaffeU, 0x3e296f873c4b25ceU, 0xbd9991cd3cc256d4U,
0x3dc356a13bff4c30U, 0x3dfa48623ca7233aU, 0x3e07ffd13e1f93fcU, 0x3e13e786be11f2beU,
0xbda7e308ba5f9318U, 0x3d4bc910b9411effU, 0x3da658353df16ab3U, 0x3da76bbb3dfe0d16U,
0x3df10c123c59845dU, 0x3d8af59b3e4c2ef8U, 0x3d096c9c3d1f4460U, 0x3da357ef3caaec26U,
0x3d1a0590be0cc2f7U, 0x3e49f465bba3c084U, 0x3e2fe4dc3d29f36bU, 0x3d8e0df63d8f4c8aU,
0x3b0ebea5bc1f7d14U, 0x3d9749c0bd53b3ecU, 0x3e8e561c3b7d333cU, 0x3dca153fbbc81d2dU,
0x3e1bcb60bd9210d5U, 0xbd8399b8bc4ff25aU, 0x3dbce1063e271093U, 0x3e32c4e1bd6de1a8U,
0xbc0805ab3e2fc45aU, 0x3df399f2be3c2179U, 0x3c24641c3e8edc84U, 0xbdc87ddf3d417a92U,
0xbc701505be5b061aU, 0x3e2615eb3cbf8402U, 0x3d7f6ed4bcd6d0e4U, 0x3d4219cd3c266ee7U,
0x3dbc4c293c247d34U, 0x3e4b5d293d7c7787U, 0x3e453447bb7577f5U, 0x3e1de3afbd51d85aU,
0xbcfd2ed83cc300d9U, 0xbceae1b53d87c567U, 0x3e226acfbc3b3db8U, 0x3bd0b3043e32cb34U,
0xbd5021b9bd811048U, 0x3d97fe123e95fd6cU, 0x3e4a437e3e27febcU, 0x3e0924353d435652U,
0x3dc65afb3e0a434aU, 0x3c096d0c3d945f9dU, 0x3dad43c93d5ed2d2U, 0xbdde6e56bd9b95daU,
0x3df832583e192542U, 0x3d6d5e0f3df7770aU, 0x3e0273cdbc8c703bU, 0x3e28589a3e2a467fU,
0x3e331d3a3c75a94fU, 0xbdb268e73e2398b0U, 0xbe57351a3e5cb05dU, 0xbe0f1954bdd96cd3U,
0xbb686b143b53fc5eU, 0xbdea4b82bd8b2c37U, 0x3e0c125a3e1c694dU, 0xbd282206bdcd79d7U,
0xbe6aafd93de6f8e6U, 0xbe8cc4c7be0ae08cU, 0xbd91829cbe1fa067U, 0xbd1662673df56a91U,
0x3e3c530ebe44877eU, 0xbe3b0d54be651ff6U, 0xbc8c9241bce342f2U, 0xbe001cd43e45dab3U,
0xbd64d72dba27a665U, 0x3d82c9293de2ac59U, 0xbd819fef3db36d8cU, 0x3e804b28bce35939U,
0x3d8a58eb3d6a4aafU, 0x3e18bffdbe38a1d5U, 0x3d92f3913e36bb0bU, 0x3e19e1ecbc049432U,
0xbdae5a93be694cd6U, 0xbc86af7b3dfe72c9U, 0xbb6ca5ccbc5c2b33U, 0x3d007aa6be2da309U,
0x3d2703fbbdad919fU, 0xbcdeb185bca96533U, 0x3daddb883d78b13fU, 0x3b43b1ea3c412941U,
0xbe2e6890bd9cedf2U, 0xbdff9ca7bdd5711dU, 0xbd6721fb3e0d8058U, 0xbe8836f6be2c8a58U,
0xbd9fdaffbdc10325U, 0xbe69e4fe3e16c426U, 0x3b833343bd75e76bU, 0xbc1442d33e173e1cU,
0x3dc27d39bd35710cU, 0xbd129af13c88b90fU, 0x3e0083e13de1a586U, 0xbe4d524abd8fffb4U,
0x3e4757f63d27c0a9U, 0xbe1fb802be327f87U, 0xbe37a9e1be46512aU, 0x3cfe79613ca3dfdbU,
0xbde99c5ebe12a309U, 0x3d2205163d90b99eU, 0x3c3cbb943e19ca83U, 0x3dd0fce83d907dccU,
0x3dd9492b3d3d8639U, 0xbcbc10a73d5583eaU, 0xbdf45ea8be9eba51U, 0xbd810db9be144bb3U,
0x3e17869cbd9bf448U, 0xbe18990a3e1ba241U, 0xbd9724aebdb33a15U, 0xbcf488a9be00da26U,
0xbc6703e6bdea5d87U, 0xbe14f417be5925d7U, 0x3ddf14f93dbdcf6dU, 0x3dffc14bbd87454cU,
0x3d6c8fc2be332ceeU, 0x3d26f6db3e03e0e7U, 0xbe3c2ea3bcb74721U, 0xbcba736ebc01632aU,
0xbe841f093ce0add8U, 0x3e0806633e662e17U, 0x3e81b5e73d3cb10cU, 0x3e4748c53d1e0ef1U,
0xbcc306293d888007U, 0x3dc360153bb1bb6dU, 0xbdb3b2293e2d51c2U, 0x3dbd85c83e7e9181U,
0x3e044def38a65329U, 0x3d3110963e04fa18U, 0xbe5733ea3de9cf6eU, 0x3e0bf0e6be2eabf4U,
0x3e0c85a0bde1ef73U, 0x3c8dfc8b3d6a7100U, 0x3b0043653daa7b21U, 0xbddb88283e42415fU,
0x3b92c355be3bc8e3U, 0x3d6aa2dbbc8be4d5U, 0x3e08fb1b3e12314dU, 0x3e0cb2533e058165U,
0x3d9e86373e9c669aU, 0x3e71a20fbcaa1f15U, 0xbcf013d53cad0bcfU, 0x3dc28b16bc125ff0U,
0x3e954d523df4178eU, 0x3dcf20563da8cbe2U, 0x3e3ebfee3e7de24cU, 0x3e0e25db3d9f057cU,
0xbc7be0d5bd7a2d98U, 0x3e76caa5bd97148dU, 0x3e439d00bcc69599U, 0x3e9c0fdcbec8b23cU,
0xbd8f6ee73af22519U, 0x3dd683a73e217a55U, 0x3e111c2abe14abd8U, 0x3e84ee6e3e154807U,
0x3dccefdf3de5c385U, 0x3eb18dd7bcf26063U, 0x3e92e01c3d15cf9fU, 0x3cdc8006bea29359U,
0xbc4c793d3da728d5U, 0x3d6dcb08bd86a0e7U, 0xbd40786d3d866ec2U, 0xbd72f8873def002eU,
0x3dcd6bed3e1bfeb6U, 0x3e15d4dd3d7b65cbU, 0x3d9e9efe3d8947c2U, 0xbd89e0823e3d9cbeU,
0x3b8782c0bd953e90U, 0x3dced4413d37f705U, 0x3da5168ebc853958U, 0x3ea814d8bb044696U,
0x3ed344223e3e2cf7U, 0x3e763a10bd92fd42U, 0xbd5fc6e1bc29f956U, 0x3d4f49bc3dbce229U,
0xbc699e76bb9acb8dU, 0x3d976fbcbe13991cU, 0x3e91e72ebe1413e2U, 0x3d07a88f3e2b6307U,
0x3ea9a5643c6b11a3U, 0x3efaacf7bc955dc7U, 0x3e85985dbcf20a50U, 0x3e396c953dc79227U,
0x3dcd91253d9d0223U, 0xbdbd12973e50dbe7U, 0xbeabd45bbd83cf31U, 0xbda55e3bbe11619fU,
0x3e1e4dd53d145ed4U, 0xbd10ba06bda178b9U, 0x3c6fdd5d3dadfe6dU, 0xbcf8b3e0be84bfe3U,
0xbe9625943d48378eU, 0xbd5fff5bbd8c162cU, 0xbd51831ebcd14490U, 0x3d94f6f63c6c9df5U,
0xbdb9aa253d8ec7e1U, 0xbdeea84abdbfcc82U, 0xbd8ceb0b3d89d5d1U, 0xbe2afdc83db86b6bU,
0xbdd84e53be04ac4cU, 0xbe3eaa23be1cb1b6U, 0xbcead079bdd95047U, 0xbd48b5333c0189f1U,
0xbceaac7ebe649486U, 0x3d6dba61bc95d12fU, 0xbd8903423d952908U, 0x3de0d3d2be123e20U,
0xbdcda7adbd4f772dU, 0x3ca27a6f3c9914eeU, 0xbd9501c2be285810U, 0x3db0cebd3e179123U,
0xbd89d7d4bd8648a4U, 0x3c986939be523723U, 0x3cec87143d988418U, 0xbd6f2e1fbdc3cdd8U,
0xbc85c42dbe033281U, 0xbdbe49af3d450284U, 0xbdd2f60bbd123b2fU, 0xbdbaae53bd93d77fU,
0xbe8281e7bd3957eaU, 0xbe2c2035bea86bb5U, 0x3ddc84b0bd88e606U, 0xbcb8ec38bd0f361cU,
0xbd919678be5d9bd5U, 0x3d21bd293d1ab234U, 0x3d69113f3c86edcdU, 0x3cf6a418be0bd3daU,
0xbe895f283d16276fU, 0xbc7f7c89bca6fdabU, 0x3d3e6032baf4e9f5U, 0xbdd40748be1e726eU,
0xbbc393da3e0ca4f2U, 0xbdefc1033d04e594U, 0xbd5f62debdddb2a5U, 0x3c13c098bc7a1cf2U,
0x3d506effbe22cbdaU, 0xbea607cabe6e1d07U, 0xbc367e77bedc5c8dU, 0x3d832389be0bd77dU,
0xbe9bee3ebbbf4a58U, 0xbcb5224d3d723f6dU, 0x3c2e7efd3c674dfbU, 0xbd1ef07b3e0a4b05U,
0xbdc3484abe3af3e7U, 0x3d02c322bd816831U, 0xbdcd6ec0bcfabf43U, 0x3e16cc62be4e8cdfU,
0xbc6ce87fbc6d1db0U, 0xbdbce136bea54b0dU, 0xba0d8063bdb5c8e1U, 0x3d6f68a5be0a0300U,
0x3c010551be268e27U, 0xbda81e5c3d13f1afU, 0xbe784145be7c5651U, 0xbd9c6f9bbe133b8dU,
0xbe370033be92148dU, 0xbc03a4523db1efb8U, 0xbddf9e41bd48ff5aU, 0xbe5e76363dd9b08bU,
0xbc1a6a28bccf272cU, 0xbe123aa43d1a88deU, 0x3caaaf2c3d841b4dU, 0xbccfd1d73e2ca692U,
0xbe59a09bbc85dc0cU, 0xbd74c67bbdc8c764U, 0x3df76908be0dda0cU, 0xbe3d51473d492c1cU,
0xbe1001ebbcbdcad2U, 0x3d07ecc3be4c2fd4U, 0xbe4989b5bdc60cafU, 0xbdc2933c3dad90b3U,
0xbc294b8abe4a08d5U, 0xbd514e11bea1e4eaU, 0xbea79df9bd9512caU, 0xbd4188f8bd019015U,
0xbe28cfc1be12d733U, 0x3d9b5990bbd1d5e8U, 0xbe83de3bbe1cc199U, 0xbe07a6a7bcd753b0U,
0xbbff689cbdf0afb9U, 0xbd1c32bebd4b7f43U, 0x3d723b04bd261625U, 0xbe4c7ff5bd8dbd94U,
0x3b96504cbdae1458U, 0xbd8b2ad63c3bd624U, 0xbe820e6c3c62d3dcU, 0xbe5b4274be5ca3f3U,
0x3db5df99be9b32d6U, 0xbe566ab33c844a75U, 0xbe2688b5bd8173f8U, 0xbe242f6a3cb0a328U,
0x3e537f69be7b6e6dU, 0xbe9d4ad33cb2c8a5U, 0xbe242d2bbe252953U, 0xbdb6f8b53d2af868U,
0xbc8a7ee6be94a998U, 0xbeaaccafbde0c899U, 0xbe79e3e43df0104aU, 0x3d8d88923e26cb5bU,
0x3d1c988e3d3947feU, 0xbe96f3f6bc6f81efU, 0x3e05989d3aa7cfd1U, 0xbd81e1bbbe992cf0U,
0xbce89ab9bd0858f9U, 0xbe821c51be0ed9d5U, 0xbe397e993ddbd1ebU, 0xbd7c8f51bd763d8bU,
0xbe259e84be00aa24U, 0x3b432c21bcea866aU, 0xbe80e126bdaec1aeU, 0xbbc927e0bdb2de82U,
0xbcf8b9d13e0ed326U, 0xbddbeb73be5ad997U, 0xbe4b0ab4be64dcf7U, 0x3d2ccdd4bc04ff35U,
0xbddc0c873cd0a7cfU, 0xbe1ea61abdd460c0U, 0xbd56985abe0e66b7U, 0x3d8e8cdf3d87520cU,
0x3d7e17033d3149efU, 0xbd0e39113daad4bbU, 0xbd494faf3d30d7d8U, 0xbdb303abbe3e5d5cU,
0x3e28f4dcbdaabcb5U, 0xbe092a1f3d0a7ecfU, 0x3dcd6771bcdf43faU, 0x3dc60fb3be0e7db7U,
0x3a1e71a4bd48700bU, 0xbce2801e3e2b4dd4U, 0xbd9c3fe7bc9c040bU, 0x37a11ba2bcdcbc6bU,
0xbc6e0a8d3d25924dU, 0x3e3695d2bc67779eU, 0xbbb68c393d204e70U, 0x3d84ba49bdd2e7f2U,
0x3e80071a3dcc269bU, 0x3dfe5b493e138d83U, 0xbe28c307bcfd33baU, 0x3d3378c03e39fcabU,
0x3b8deb6fbd6a34efU, 0x3bc50aaabd706972U, 0x3cc815e43ce834ecU, 0x3d83cb8fbd0032dcU,
0x3dc26fac3e30993aU, 0x3d8446bebe0b9a6dU, 0xbe3776bfbdc5d78dU, 0xbdda7681bdbfea75U,
0xbe581fb83e1c9bf5U, 0xbdabaeacbe31a84aU, 0x3cbff53bbc883256U, 0xbb9fa7243dc1ae46U,
0xbd88b370bccf0b0fU, 0x3d32f6a73e154825U, 0x3da24cd53db67e70U, 0xbd88bc9fbd6e8070U,
0x3e6ea65e3db2c568U, 0xbe171e783df4f692U, 0x3e385a2f3e278263U, 0xbd60e8e4bdd37accU,
0xbe08dcaebe16ccc8U, 0xbd567ea33e3a5e98U, 0xbdf2ec74bdc30242U, 0x3e2aacbe3d4e0f8eU,
0x3db0c2743c6c14ebU, 0x3e37d2e73d21200aU, 0xbd39cec83dcbcd43U, 0xbdd9877f3e0da4e2U,
0xbec944d4bda01abeU, 0x3b151e12bd0afb7bU, 0x3e2984edbdb2d039U, 0xbd9787733cc235f0U,
0xbcfc6a7b3cfa7613U, 0x3dc034b2baf8d964U, 0xbd9cafcebd9826a0U, 0xbdf3506e3c6726d1U,
0x3e3d47563d7f9e52U, 0x3da9959e3cc91fc6U, 0x3d5a0dcd3c8422c5U, 0x3dc821613e62421bU,
0xbda53fdabe8f45f7U, 0x3de227913cb7edcdU, 0xbdff1044be1e70ceU, 0xbd73290ebe1ff0e1U,
0xbb7438a4bd148e5bU, 0x3db6673b3ceb4d4dU, 0x3ded30973ddecb76U, 0xbb4ea528bd368545U,
0xbd8b02a63dd4b21eU, 0xbd8abdf63de454cdU, 0xbd563bc83df01880U, 0x3dc00273bd74f5a1U,
0xbdcf94e0bd6f9deeU, 0x3c20a8543dded8f8U, 0x3c7b304c3dffa0abU, 0xbdb297ce3d922ee0U,
0x3ca2455dbda0d94cU, 0x3c6e7de93e1afd91U, 0xbcaa87143d7892ffU, 0x3ca7a1893d98bb27U,
0xbc1a74babd25442fU, 0x3db6b80ebcdfbb8fU, 0x3caa40c43d81ea4dU, 0x3dcde09d3ce25b37U,
0x3dfd2961bdad11ceU, 0xbccaacb3bc900a12U, 0x3ca503d3bd70782cU, 0x3cb9c9ff3db1f735U,
0xba49cbe4bd389794U, 0x3d0e7aa2bc717c39U, 0xbce7798e3d7d055dU, 0x3b06b9103d0c36bcU,
0xbdbbc6c8bd20ef87U, 0x3e458c333c53ec2fU, 0x3e022f103d254b92U, 0xb9f8f95b3d765ff8U,
0x3d3ed2d73c06e7b6U, 0x3da06a94bc97ac09U, 0x3c499c513db05629U, 0x3defbaa53e76607aU,
0xbd9ad6893c9d667aU, 0x3d0d3590bc267cc2U, 0x3d903fdd3e2b16d2U, 0x3cb87243bc8f420aU,
0xbdf849623d9c543aU, 0xbc884e4cbddb11bfU, 0x3e3ee8923e20b4a6U, 0x3de20263ba191dc3U,
0x3d6bfcf2bda2371fU, 0x3c2e89b23e1615cfU, 0x3dfb2aeb3d129a19U, 0x3d8b650a3e2a290bU,
0x3c4d53583d89ca87U, 0x3e155202bd110d4dU, 0x3e0f8ee2be4f58e9U, 0xbc6e5cd3bc8e6188U,
0xbd1d71ab3d13ad06U, 0xbd434b6d3d7bdcf5U, 0x3db353123ddb166aU, 0xbb0333843dd3b028U,
0x3dd3897fbdc2e762U, 0x3b4dd46e3cd0dc16U, 0xbcce13e73db3c178U, 0x3ce97f703daa87eeU,
0x3e214bff3e21fd93U, 0xbd16123b3d6bf15dU, 0x3cd6d6fb3defa5f1U, 0xbe3916423d815fbeU,
0xbd5ecd4e3b521aeeU, 0xbaaa811abccb0e64U, 0xbd89a9d83ce72f8cU, 0xbd3d3e02be81c5f6U,
0xbe9af979bdc7ed1dU, 0xbd2e390ebe0bc1c1U, 0x3d75df8ebd74f7ceU, 0x3e2604483a9e565cU,
0x3ca12174be51bf5bU, 0xbb4a36e0ba828741U, 0x3e03cd89bd557d57U, 0x3e6a8d363d3b6107U,
0xbdc8998fbddba9bfU, 0xbdbf77c0be6b51ebU, 0xbe3f182fbe132966U, 0x3e0066383d78017fU,
0x3d3d394dbe63d2acU, 0xbdf76dc2be070069U, 0xbdeead5b3caf181eU, 0xbcd78980bde36baeU,
0xbd85af87be17b3beU, 0xbe0a4e273c8a6b5dU, 0xbcf1fa11bcfdd658U, 0x3d3b18d7bdc3c32dU,
0xbe1199bcbd4c4dd4U, 0x3d209417be54fc6aU, 0xbd9161d63d3da564U, 0x3e09a86fbe2c7f13U,
0xbe1135acbdd63dcdU, 0x3d0e5414bd4dcc8dU, 0x3dd67b7cbda01e65U, 0x3cad7f0e3d1a8dc0U,
0x3dd1be223bac86bbU, 0xbb0657c63e00f6f6U, 0x3d8c759abdf89961U, 0xbe22cbcdbdb99cf9U,
0xbe3c891dbe21fb52U, 0x3bec8284bcd785a3U, 0x3df1ef0dbe3a5026U, 0xbd514426bd2c9205U,
0xbe096800be22b34dU, 0x3d0853593d4c99c5U, 0xbdc38b28be2d3b5fU, 0xbd4d575dbe19424eU,
0xbe811322bd498fa5U, 0xbd9c5709bd1cbea7U, 0x3dd55615be968555U, 0x3e40bc3ebe19405aU,
0x3daaedc03dbd4536U, 0xbd2f6e2d3e041d1bU, 0xbdc7386cbe390971U, 0xbd09815b3bdf26beU,
0xbd8a599c3d9c4d8aU, 0xbdca337abcb1fc9cU, 0x3c93d9dcbdf7ffcbU, 0xbdb94083be5739b0U,
0x3b73207e3cc1fb01U, 0x3d0b2dd4be0e269aU, 0xbca101623d717c66U, 0xbd6e729fbe45004dU,
0x3e07e1723d5d25e9U, 0xbde470683dd00a42U, 0xbdb21aa4bd82b062U, 0x3d652dd6bd2bbc12U,
0x3d499f1f3e1c08a2U, 0x3dfa77133af44f10U, 0xbd63245ebd0e4e51U, 0xbd5560033cd6168eU,
0xbdbb18c73d4d6e52U, 0xbd6e5562bdda706fU, 0xbe0f2563bdda2711U, 0x3dadbe843c959eddU,
0x3d3d9768bdb262a8U, 0xbc2f0d8fbdc9cff3U, 0x3cca8679bddb55f3U, 0xbc2ea06abd309c4aU,
0xbc2320a5bde942b8U, 0x3d39de42be2c27b6U, 0xbbe50380be015feaU, 0x3c29417ebc451eb0U,
0xbd8dbc1cbe28a879U, 0x3bdf1796bd4bbe9bU, 0x3b82e08ebcbc6a1cU, 0xbde8a109bc7d1722U,
0xbd2b08e9bc9a1505U, 0xbde71e51bda7efe4U, 0xbe05360c3ca04fd3U, 0xbdcf1b61bd0c345bU,
0xbd91ab86bd3c45f8U, 0xbbafa5f33cef13d4U, 0x3cbb9b12bdff5860U, 0xbde31e683db46d28U,
0xbe41f63c3d3a96ebU, 0x3d45f651bd22d38cU, 0xbdf5ed0abd743210U, 0xbe0810aabd8ac395U,
0xbd18b444bdd5aa1cU, 0xbe0cdf9fbd9ec038U, 0xbd3049b7be0e3927U, 0x3d46a37d3c275f23U,
0xbe984960be238194U, 0xbd18a5ccbdcd5f14U, 0xbe4becc5bced744eU, 0xbe7553d1bc8936daU,
0xbdc56397bb89f3ebU, 0xbe25a966bd471db7U, 0xbc646b053d10351bU, 0x3bf6e0f2bc8323cfU,
0xbd8057dcbe21162eU, 0xbe287c4a3d6e5284U, 0x3d1d182abd9a07efU, 0xbd959b323d0cb229U,
0x3e0df3c7bdab8e46U, 0xbc2b4a5cbabc5073U, 0xbc5415f33c1f8e14U, 0xbd334f9e3e0f99efU,
0xbe0428e1bccd9fd2U, 0xbe54bc453b827034U, 0xbdc9fe99bd69d13fU, 0xbddef1edbdf7ab9eU,
0xbd86113ebe53901bU, 0xbe483349bdcc1fabU, 0xbd29b91abe246893U, 0xbda823ccbd9d88e9U,
0xbdde745cbdef0885U, 0x3de76a8ebe370d34U, 0xbe2de8bebd7b54dbU, 0xbd93fbf2bd77117bU,
0x3de21d0fbc960de4U, 0xbd76fce33c8f056fU, 0xbbdacd96bddad92fU, 0xbe417f7cbc531af4U,
0xbc0e3015bd2f84cdU, 0x3da7b863bd3bd2e2U, 0x3d0bd8c6be0fce91U, 0xbc9fa2ecbd7f16b3U,
0xbd775c5abdcff192U, 0xbdad92f13cdcce22U, 0xbe222d73bbf51030U, 0x39c784b13c507fbaU,
0xbd4e92febe090db5U, 0xbe8571513cb640baU, 0xbea7690fbe6814a6U, 0xbc0e75aebd95e377U,
0xbac534413c171e7aU, 0xbdf5e905bd5770f0U, 0xbe59d720bddaef1fU, 0xbc211bc8bbb4c972U,
0xbd92197d3d0e969bU, 0xbd92570ebe1bcbb5U, 0xbc874fbb3db6cfa3U, 0x3cb93e683d63a835U,
0x3da2e231bd05b7f9U, 0xbe08c4203d854a25U, 0xbbf74c3abd238179U, 0xbd23f2a6bdc1683bU,
0xba8582fa3d62c0ffU, 0x3c9b24fbbe0e1ee3U, 0xbd4eccbbbbc4d802U, 0x3d86b710bbe9fbf9U,
0x3d361e17bd8794bbU, 0xbcb292aabe03b48bU, 0x3da2de39bd826f34U, 0xbe055f2fbe24c97fU,
0xbded0e76be1d28a1U, 0xbe7bd3b0bc684ac6U, 0xbc0aed21be42c348U, 0xbcb27b1ebd4b0b19U,
0xbd6a9e06bdaee0cdU, 0x3cbe924bbdb2cf9eU, 0x3a631794bd8c0263U, 0x3d0dd1433d56b3d5U,
0x3c880e15be688b68U, 0xbc36c728bc777012U, 0x3d704c5e3c921006U, 0x3d07b16abd46179bU,
0xbdd37d4ebc2e256aU, 0x3dc82a9a3cb062cbU, 0xbd2f751e3cfcace8U, 0xbd1e98cbbc5fd45dU,
0x3d31dfd0bdb7c113U, 0x3dcbe98f3c906a45U, 0xbe6f812ebe09341dU, 0x3d98d54abe527412U,
0xbc9e5f68be3e2276U, 0xbe5d9245bcd8f51bU, 0xbd8f65c33d4ffc7fU, 0xbc633656bd2a5bc4U,
0xbd524dffbbfd3e3cU, 0xbe6d8905bdc16074U, 0xbd691beebc5392cdU, 0xbdff6dc13d03057fU,
0x3d6779a4be40c50bU, 0xbd4c401fbd9d6983U, 0xbdede76bbe12f06cU, 0xbd189b0ebc8749b5U,
0xbeb7bbe23d391845U, 0xbdc48051bdaadee2U, 0xbd030e5bbdeb9337U, 0x3cde30aa3dbc6788U,
0x3c91387f3e049fdaU, 0x3e084bfd3ce7d768U, 0xbdc53d3f3ded8618U, 0xbe1b34f03d9a384dU,
0x3d0fdc783de2b858U, 0x3e6a9ea63c017c4fU, 0xbe34982fbd7b2e75U, 0xbe1303b33d6373a3U,
0x3d5ab11a3d41e9ebU, 0x3b1a77b43e84d0a6U, 0xbcef7966bd88c07eU, 0xbcb2e3333e0d795fU,
0xbde900153b8ef37bU, 0xbd5976d3bca37aa4U, 0x3df153e83a69c02cU, 0x3e42ec2c3e0eab6cU,
0x3ba317053e1a6f26U, 0xbce3a1a3be02a0a7U, 0xbc777e70bd6eef56U, 0xbe139c91bd84d765U,
0x3e5a0b3dbdb1e17dU, 0x3db5b3f53c9eaffaU, 0xbd6daec03df9906bU, 0x3df03a003daeca82U,
0xbdfb3c88bc2865e6U, 0x3e6628d53d204837U, 0xbdb2bd8f3c21a622U, 0x3ebce2f1be4c8e7bU,
0xbc1bb3773dc7ce0cU, 0xbcbdca873dc89410U, 0x3e0c68eebd5438e7U, 0x3c4d60f73e7d6a86U,
0xbcd54e08bd997050U, 0x3e6598d93e67c316U, 0x3d7fe5ac3c8518e6U, 0xbc8fee84be6b4c05U,
0x3d9c29be3e2410b6U, 0x3d940159bddbb0faU, 0xbe4aa4283e46da0dU, 0xbd84cdbabd4b4fa0U,
0x3e9471783e91524cU, 0x3ea6d6d0bd6844a9U, 0x3d76da57be50edc1U, 0xbe4f72d83e6650a8U,
0xbd835fcbbe306ebfU, 0x3e28a2993de57b25U, 0x3cfb8d323e7b222cU, 0x3dbd31f9be0cbae6U,
0x3dcf3d7bbdc09b1fU, 0x3ceba150bcdff79cU, 0x3cba5d8c3c10850aU, 0xbd5f28f33db9b8d0U,
0x3d978b343db3556bU, 0x3cffbfc8bd57cbdeU, 0x3e12956bbe1dbe62U, 0xbcb305393d5a1e28U,
0x3d57a1d33d9b3b55U, 0x3e1fd87f3d907ff1U, 0x3e03f8473e6480abU, 0xbd7ebf073ddc2b40U,
0x3e0cb6bf3eaa927dU, 0xbe452db13ea2d32dU, 0x3d830cd9be38fbbeU, 0x3c0919243d285a6cU,
0x3d1a24ff3df44d94U, 0x3e09f7653e021cf6U, 0x3bca9f29bdd86609U, 0x3c82b2153c2b3f03U,
0x3d5615c6be0d1d23U, 0xbd0368b9bdd276d3U, 0xb776597c3df50d06U, 0xbbf383283dcbdef3U,
0xbdc113afbe2f2753U, 0xbdd71f683e1a6d49U, 0x3e00f5b43d8cd5c9U, 0xbc71778abd1d61edU,
0x3d3c0cf43e2d120eU, 0xbd9f0bfdbb6983e5U, 0x3d82b16f3e052090U, 0x3db955a33d3c2afaU,
0x3d599dc93d6c5f82U, 0x3e3f9405bc1a4d98U, 0x3d63c6613df208b8U, 0xbb03c1193d002e85U,
0xbdbec42bbcd3a440U, 0x3d3960e0bdb6107eU, 0xbdb2818d3e44cc12U, 0x3e121fb6bd9a302dU,
0xbd897b953c362456U, 0xbc4a39b83dac7792U, 0xbda1a99a3d8442a9U, 0x3d0a046a3e3169cdU,
0xbe2d82f13e1e1650U, 0x3d9483db3e59212fU, 0x3deeecf1be55853eU, 0xbe4046143da79e96U,
0x3dd052d23dade954U, 0xbd3ee95e3d2bbd6cU, 0xbdedf3a53d196915U, 0x3d1993a63da1190aU,
0xbe383b923dacb742U, 0x3d853db03b1d9091U, 0xbe05676bbe0c3db7U, 0x3cb227f9bd627fc8U,
0x3c93ea2bbdf0dc17U, 0x3e38e03b3c4f8237U, 0xbb9390b43cf49d5fU, 0xbd6f545b3e3eb3a5U,
0x3dc8b524bc05fbdeU, 0x3ccb6480bd6e2edaU, 0xbdb68573bd0f212dU, 0xbd125e633dc735c1U,
0x3d3909933e21f8cfU, 0x3e7a74e93da701adU, 0x3d73cb973e0f1ea7U, 0x3d449a3a3dda54b0U,
0x3e2babd23dff412aU, 0xbc62e3c03bbbac49U, 0x3c73565dbdfa1054U, 0xbd4d3feebd2ae7f3U,
0x3d0e485b3dae8710U, 0x3cd4281f3c7dc31bU, 0xbccc23003e194627U, 0x3b9926453e26e9feU,
0x3aff5f233e3a1d18U, 0x3e34a5313e063719U, 0x3df5b3493c0aa0c4U, 0x3e0c03763cb55900U,
0xbd34cc1abe57213aU, 0xbd0e5335bc416ab2U, 0xbe502b04bd1ade03U, 0x3d45a7e4be44a9c4U,
0xbe58d207bd7d1771U, 0x3e002b683dbcd6b9U, 0x3a7dbf863d789726U, 0xbe349ffa3e80ee55U,
0x3e9059863d77327eU, 0x3c78d6e4bdd73db3U, 0xbdf3cf613eba6c80U, 0xbe3835ce3e8e50c2U,
0x3e02ebbe3ec98296U, 0xbe80b8d3bdc15bccU, 0x3e027fcdbe5aa45cU, 0xbe9e18983ec2361fU,
0xbe103fedbd9a62c0U, 0x3ef040bbbeae946eU, 0xbe2dbe9abe870305U, 0xbe5314a7bd048944U,
0x3d965f3cbe2bc871U, 0xbc0845ffbdb136c4U, 0x3e063dd0bce86f94U, 0x3ee2effebe1de953U,
0x3e208511bd1b5292U, 0xbd88d1653c72246bU, 0xbdccddb1bd7fe1aaU, 0x3debe0533dec337dU,
0x3e9f9776bcbcbab7U, 0xbcf79bff3d863bf6U, 0xbd4115dc3e41193bU, 0x3d3bc2083e95a694U,
0x3cffde543ec00558U, 0xbe59f5013cfcde0dU, 0xbe22bf933ec3a887U, 0xbe005169bc48454cU,
0x3de0a6bbbd4fdda9U, 0x3bb01d77bd497750U, 0xbd722c093e105d95U, 0x3e26fb7d3e05d1f6U,
0x3e198d9fbbd9947cU, 0x3d1d1d74bca8e945U, 0x3dd383e83e0663efU, 0x3e193dfd3e441101U,
0x3e7d6851bdac54fdU, 0xbe174d9abe11c6ebU, 0xbe8fe428bdaf335bU, 0xbdf281e93e8407fbU,
0xbda471703e347ee4U, 0xbe340f053d6bf60bU, 0x3d3b3e103d907297U, 0x3e160127be92693aU,
0xbdfaf40e3dadbc14U, 0xbe648962bd5be4b5U, 0x3b7e24423ef3b4fdU, 0x3e91b9103e807800U,
0x3d0e1a21bce431d7U, 0x3e101a30bd0b843dU, 0xbe1e8ab7be63a4a7U, 0x3ce6ea72bd95d832U,
0xbc8ae1583d00f248U, 0xbe28ebab3d01d5fbU, 0xbe29b224bd78e002U, 0x3e567d323e912a58U,
0xbe3645253e3e08b8U, 0x3e7775d8be21ec9eU, 0xbde24c3e3e3a27dfU, 0xbd5411733d9a1245U,
0x3d21910d38b3b4e4U, 0xbe83e163bdd82435U, 0x3dc20a51bd61834dU, 0x3d8da3a2bdc39b8aU,
0x39369f1a3da12910U, 0x3c9376ecbdea09a2U, 0xbd9331b2bd40202aU, 0x3da428ed3c8bf881U,
0x3d7a346e3e82bde8U, 0x3de8937a3d7e35c0U, 0xbe0afbc73deb292dU, 0xbdb8ff713dc43d04U,
0xbd6b2e1e3d02f34aU, 0x3c9f01c53e05c8cfU, 0x3e024b563e242d6dU, 0x3d9cce303e0e3244U,
0xbc4abc4f3d225db6U, 0xbce5182d3e11dbabU, 0x3e32df123e4fc76aU, 0xbd3f338d3d7a569cU,
0x3d69c8d4bd155256U, 0xbe2758593d202adfU, 0x3d0bf6e2bad7f7d0U, 0xbd3791a33e45e967U,
0xbda339f4bde53f4fU, 0x3cd7e5003ce18715U, 0x3cf0fc903d204eb3U, 0xbdde7be23de7e3d0U,
0xbd28be133d353282U, 0x3c81b5e9bc88089aU, 0xbce86e7b3e239258U, 0x3e2a8bd63e5f8ebcU,
0xbe1f01a83c855ec8U, 0xbd01466d3cd25e7cU, 0x3dd224553e14f8d7U, 0xbd096d8f3da3aefeU,
0xbd824e753dc0cf79U, 0xbce975aebd4a6bf6U, 0x3d96d51a3d6454c4U, 0xbd3630cb3e08814aU,
0x3d781ddcbc7eea20U, 0xbe5c1c373d447eb3U, 0x3e0b8c173dbc13b2U, 0x3d4d40e93d96194bU,
0x3dc57724bbf68249U, 0x3d7ef7fa3ce18412U, 0x3cbe0c0d3dec8030U, 0xbbd87cdebd263f40U,
0x3e5d56b73e5c706cU, 0x3c2b22573dca57ecU, 0x3cd855193e4d4397U, 0x3df8164a3dce3c66U,
0x3c99467f3d7afccbU, 0x3d630917bdb29ab0U, 0x3df832d8bd705517U, 0x3e34980a3dcbd9daU,
0x3dfe0c22be0c58ecU, 0xbd4600b4bc8e692eU, 0xbd660c2e3eb8718cU, 0xbe0f2f663e2e97abU,
0x3dda08b63e86eff4U, 0x3e7b273bbe133f30U, 0xbdc1b08bbcc5e995U, 0xbe53d0b4bea13908U,
0x3d16070dbdecaf1eU, 0xbe253bad3e0a6d67U, 0x3d7b6769bd46c523U, 0xbea41356bef2b8e4U,
0x3cf2a6a73b02b2e4U, 0xbe65b1b2bddb8cbfU, 0xbeaa4bb53e9d7d3eU, 0x3e73628bbe32c1deU,
0xbe12d4dc3c347a1bU, 0xbd0f598c3e8f587cU, 0xbb5d68053e986f3eU, 0x3d47bce83e2f3a67U,
0xbe5f9af8be8f3d8eU, 0x3e7749a3be0f1e2aU, 0xbe968a4b3e3162c2U, 0x3d94f3203df118b5U,
0x3ea4c08dbe4704d9U, 0x3d955c723d832b78U, 0xbcb5a75b3e4c9902U, 0x3ce0611bbe9e6570U,
0x3df1a6e0bdcdf062U, 0x3d983d8dbe48178eU, 0x3e9d9f8fbe26be83U, 0x3dc37d26bda810edU,
0xbe2949a53d9b2250U, 0xbe4a6344be782e07U, 0x3c5d8c843d926b8cU, 0x3f013108bcd8f737U,
0xbe87888cbdc53ba0U, 0x3e9ec765bd1b2799U, 0x3c1d20263d45f6c9U, 0xbd09016d3eb97632U,
0x3cc96038bce883f5U, 0xbe6f70fe3ee1b979U, 0xbdd65aabbe75b02cU, 0x3d238dd63e0559c0U,
0xbda57cca3ddbe9dbU, 0xbd0b4154bd8deb79U, 0x3e31e6143de2282aU, 0x3e7bfdb5bd72c7d4U,
0xbd5882d73e36ef5aU, 0x3cfc486ebe599ec8U, 0x3ed61e1f3d6ef5f6U, 0x3e0bda17bec0b415U,
0x3d1dbae5be93fc37U, 0xbe83a03c3e886e95U, 0x3e022b393e832a20U, 0x3dd010363e76dbfbU,
0xbe6773393c4efcacU, 0x3cb6dd07be15a4a8U, 0x3d0eacaabee79a53U, 0xbd6084713e2d44f5U,
0xbc457caa3dd5a2cfU, 0x3d849a6d3ec384e7U, 0x3d84d0aa3e47b40cU, 0xbc1841073dc037ecU,
0x3ca3a093be42d714U, 0xbee73f05be12f3c7U, 0xbd92d95a3e2363b6U, 0xbcd1480b3e2f9a9dU,
0x3d9b18f83e3ade6eU, 0xbeabff09bebeac5eU, 0x3e219e413e9551d7U, 0xbee72e1d3d96f83eU,
0x3d52af7cbe943181U, 0xbe985ea1bd105cddU, 0x3dcee27e3d39fc0fU, 0x3eb918b3bd67d04aU,
0xbe72a7e5bb84ba89U, 0xbe72deadbe18e19aU, 0xbe4587cdbddb9a94U, 0xbe89c26abd58cb70U,
0xbebf56b33d7743b2U, 0x3d21912dbd2c66b0U, 0xbe9a3552be1266f1U, 0xbed39161bd1e15b2U,
0xbd8798d53e411e0cU, 0xbe2db63b3db3f830U, 0xbe19724e3e2e3486U, 0xbeb064f8be15f2dcU,
0x3e23faec3e31d3f0U, 0x3dc4d0fe3e5ae35fU, 0x3ebcf627be1794d0U, 0x3e6b94b03eab140fU,
0xbc67272e3eb25f9cU, 0x3e00b463be402dceU, 0xbe5bc1843e5c0758U, 0xbce8968d3d969b8eU,
0xbea5d94ebe059e99U, 0xbd743ed7bd808f45U, 0xbe1701b2bd722853U, 0xbdf23f00bb46e5e5U,
0x3da344c13d98f23dU, 0xbe9578c0bcc50eb9U, 0xbe4209bebd19af8dU, 0xbe3798b33e3588f8U,
0xbe5a0b72bec77890U, 0x3d437880bdcc4975U, 0xbdfbcfa13e55e4d9U, 0xbe1b296ebce8bde3U,
0x3d8d63f73d056937U, 0x3ea09cdbbea3bf20U, 0xbe60c02ebec35cb9U, 0x3c593e1d3e5235c8U,
0xbd596660bce15b06U, 0x3ed26f92be9333d7U, 0xbea7eb263acaa0c7U, 0xbe0009b9bbfeda30U,
0xbdee5e3abc186bacU, 0xbca3aaefbe32f32bU, 0x3e9f5a873e534523U, 0xbe3c3b9dbd4310cdU,
0xbdf86d463e382429U, 0x3ce9d5363e9f5a7aU, 0x3e0bd7813da13983U, 0x3d077963bea2330eU,
0xbd776801be800f87U, 0x3eba7c443c9ce8e6U, 0xbe9bf8e93ea55079U, 0x3d4fc3ab3dca8bbcU,
0x3dd11ba43cc43cf3U, 0xbde60997bda82688U, 0x3d14703bbeab3cbfU, 0x3e8711f7bdd84210U,
0x3cac843cbdb5b7d8U, 0x3d88e46dbe273f34U, 0xbdfa2cb83e204aa9U, 0xbcd7b679bca482cbU,
0xbd1b020cbdcf35e4U, 0xbe51a00cbca297b4U, 0x3e4b84ad3ea2876aU, 0x3db70e80bcb3eeecU,
0x3df2beb9bcf2cc64U, 0xbdb7423d3d990652U, 0xbe02083bbe6745caU, 0xbe33853f3df381e2U,
0x3d714fa13dc74661U, 0x3cdb117d3d4ea9dbU, 0x3e3ab4f4baae1b3eU, 0xbe3601bbbd8706fcU,
0x3e8944833d724c72U, 0x3e3f5f13bd2a415bU, 0xbd4518993e0c1060U, 0x3e0eca10bda4d3d5U,
0x3a79a677bb7447d0U, 0x3df5c8c5bad84064U, 0xbd1034baba994516U, 0x3e38fefb3e075017U,
0x3e0838a63de324c3U, 0x3c2d00503dc52df9U, 0x3deb49e43db56ae4U, 0xbccd525bbca253e6U,
0x3a230401be0af4dfU, 0x3e3bee06bc188cfbU, 0xbcbcc070bc2cb419U, 0x3e107c61bd719256U,
0x3c9b1036bd33e31eU, 0xbdbac2f3bcdbb8daU, 0x3e82f0a5bdcc7f30U, 0x3e5265543bba181aU,
0x3e163cddbdaf8e87U, 0xbdc5892cbc6b9d99U, 0x3e3a0b633e390c3bU, 0x3e1657bdbd7c14d7U,
0xba9d7ddc3e105dcdU, 0x3dcb102dbe01e436U, 0x3e2955febd1424cdU, 0x3c0478a73dae0df1U,
0xbd9066c7be8541e9U, 0xbe0d756a3d89e73bU, 0x3e05fb163c540defU, 0x3d6a24803e1eac22U,
0x3d8a6c333da3055eU, 0xbc29cd0f3e240914U, 0x3e234139be39d0f6U, 0xbcd3fb9a3cc803e6U,
0xbd4dd02a3dfffdd0U, 0xbde2d726bd5fb7d7U, 0x3e4d69efbcb769afU, 0x3daf44b1ba08dc2dU,
0x3e2340efbdb9d7fcU, 0x3e94789e3e888dd9U, 0x3e9dad6bbdcfb975U, 0xbb81ae3d3d36dbcfU,
0x3ba6e6243e0c07a6U, 0xbc86ef8cbd17e7efU, 0x3d8f434abdefc3a9U, 0x3e10c460bd969abdU,
0xbd99c72d3e28e381U, 0x3ca178aabc04f8faU, 0x3ece652abc57fffcU, 0x3e7e02eebd49fdffU,
0x3e228881be5a4649U, 0xbd4a0ed93e30fa48U, 0xbd0113793e241762U, 0x3e90526abe8aca8dU,
0xbdb3cbee3e859b49U, 0xbcc9e2693e46c7c5U, 0x3e2d8ba4bdb38e2eU, 0xbe751ae93ccd8e28U,
0x3d7df72bbe455677U, 0x3d2d81b0bce24d5bU, 0xbc0157de3e26817cU, 0xbd6d3936bdb716fcU,
0xbde35b603d9e3141U, 0xbde0dab73d76786bU, 0xbe13ebbf3ed7e7a0U, 0x3c430ad23dbb07fdU,
0xbe62289e3d41a60fU, 0xbe7a59073d9b5233U, 0xbe52f5d6be15b632U, 0xbd491dc73e389455U,
0x3df331873c536386U, 0x3dad57d33d9c635eU, 0x3d75b8013de926ccU, 0xbdb8156d3e387ff5U,
0x3e6a45833e6c9707U, 0xbda79aee3df9907bU, 0xbd2b49c13db8e33eU, 0xbd25588d3cb0cd17U,
0xbcd019c9bd8ae2ddU, 0xbe329f1a3e6e8a22U, 0xbdaee78bbdb7c268U, 0x3c299d71bc7d9034U,
0xbcb7c98cbd7c1136U, 0xbe385cea3e17b413U, 0xbd78ecd13c0f5645U, 0x3c7ad2f1bd62b521U,
0xbdd5c8013e95ed2aU, 0x3d6067ee3db48ef9U, 0xbe0d6acdbc205e69U, 0x3d03ca10be118e0eU,
0x3d96f5433ba8a72bU, 0xbe23d3d7bb80228bU, 0xbda0aef93d93632cU, 0x3c687516be0e7bdbU,
0x3e0605523b79470aU, 0xbd7c3f813dfbb976U, 0x3d918849bbd36c9dU, 0xbeab0cb43d1881e7U,
0x3e44683cbbc7a778U, 0x3c9fdef63e393548U, 0xbdaaf9b7bde004cbU, 0xbd2789e83de94494U,
0xbcaab0113de91ee7U, 0x3c4a363fbbbcbd47U, 0x3e52fecd3e5136e3U, 0xbd8127783e3a25c3U,
0x3d86c41e3ebb4d10U, 0xbdafa0973e12e90cU, 0xbd570ade3d885a2fU, 0xbaaf4277be17510fU,
0xbb852a533db3395bU, 0x3e850bc73cff8671U, 0x3d71d2bdbdf4b7a7U, 0xbd0f6d0d3da6bcffU,
0xbd83f8763e9b199aU, 0xbed45ac83e36a3d0U, 0x3d83745c3e2d6404U, 0x3e0d3d40be4472bfU,
0xbe6ad639bd0c3f50U, 0xbdae2ef4be0629caU, 0xbd12d35bbe4f8fbbU, 0xbececeec3ef055efU,
0x3ec41b2c3e0358c3U, 0xbefa0f83bf0c6265U, 0x3ebc6d4c3d306ad0U, 0x3d04afb8be420ee4U,
0xbea9e4b5bd86719bU, 0x3eb05f89be1c4c31U, 0x3e18e07dbe36f3f6U, 0xbde1d3e6bc09c70eU,
0xbe41fc78be37b5edU, 0x3e90707b3e6d9f31U, 0xbc813e17bf16c4e7U, 0xbe04fd29bec9a4c8U,
0xbd9dd5c6bdaab8f5U, 0x3d62ef62bdb49ef5U, 0x3ec0a97cbe3d77c2U, 0x3e2e08d4badaf728U,
0x3e651140bc911dc0U, 0xbd61bb41be93c9b0U, 0xbc85c6993db272c4U, 0x3e96a4c0be93cc69U,
0x3ece0726bd693e19U, 0x3ea8fc7cbe4720d3U, 0xbc4ad7893d5228f3U, 0xbef76d4dbeb91ea4U,
0x3e765715bd2ae60aU, 0x3f062e353ec043a9U, 0xbdda8f9a3d7f4899U, 0xbc301b3f3ce27dc2U,
0xbda7c2df3e2d07e6U, 0xbd60b8153ead6465U, 0xbd89ba293c24cf5eU, 0xbe921c073ecab756U,
0xbeab9259bf0c8bc6U, 0xbda47c683ee297aeU, 0xbeaec5be3db967fcU, 0x3d9036973d4a68caU,
0x3ee4def53ce62fc9U, 0xbd59225c3e1a6c25U, 0x3eb1fa22bbfcc5bbU, 0x3e6932ccbeb8d2deU,
0x3ed21e7d3e0f7e3aU, 0x3e820812bef73776U, 0x3eda600ebd214112U, 0xbe8838a53d15795fU,
0x3d732ebfbd7bbf62U, 0xbd7778273c95a111U, 0xbe72d2633d39843dU, 0xbdeb8bf93d916900U,
0xbe814c54be4826baU, 0xbd809c6a3ebe92a0U, 0x3e0c0e9e3d3cc3cdU, 0x3ebf66883e6a3857U,
0x3e68a9153ed6bdbaU, 0x3e3a6f113d45bc38U, 0xbe6270aabdd96e33U, 0xbec4169abdb8956dU,
0x3de1619c3d4c5f2aU, 0xbe871efbbd350e22U, 0xbe1a5be73f0908faU, 0xbe57c9c1bef1519eU,
0x3c63a0dc3ece97a6U, 0xbec62e363dee79c5U, 0xbe3410f63ba48c34U, 0xbd9ddc8bbe4aae7fU,
0xbd3e24b7bdd7307eU, 0xbd570a333c2e6bfdU, 0x3c7981f9bc454043U, 0xbe67a8d73e12b120U,
0xbe7806e1be647b6bU, 0x3e8ccb4ebe8db5c9U, 0xbe0990c53d2ce2f1U, 0x3e34ccbcbca893e3U,
0x3e60f13bbe76ddd1U, 0x3ea92fcebe2e2945U, 0xbe213a183d9c43b7U, 0xbd59233cbe772fbbU,
0x3c8df8be3d559c38U, 0x3db6af5c3e86c7faU, 0x3e5266c6bc23de8fU, 0x3d46a7ae3d38a9e6U,
0x3dea4ce83c46cffbU, 0x3d7edaf23dcc12f7U, 0x3de929f93c4cf1e1U, 0xbe191a1abec8f987U,
0x3dc62ccc3e02280dU, 0xbdc56618be37813aU, 0x3e04cbd9bd9effbbU, 0xbcdec9f8be35f9f8U,
0x3dc4082dbdf21827U, 0x3e1170f33d2c9ef3U, 0xbc1bed7ebdf4484cU, 0xbe887355bda8c2dcU,
0x3d62e875be7e92baU, 0xbdf6ef553d8cf51cU, 0xbdbdf0ecbd3a9842U, 0x3de5079ebeb15a0eU,
0x3d3d56f43d911876U, 0x3e01145abd290179U, 0x3ca6abf33e270c8bU, 0x3dab1c71be95382eU,
0x3cced5a1be21312eU, 0xbcfe8a4c3d8f788cU, 0xbe57565f3c554379U, 0x3d9412e53e89b674U,
0xbe3a64c6be3c0ad4U, 0xbe919672be41242dU, 0xbc27471c3d8ae947U, 0xbce5882fbd86a07fU,
0x3d892f2d3c60c3fdU, 0x3e66bc7e3e22f72eU, 0x3e7e8bb03c3fc51bU, 0x3cc244a13dc5a7b6U,
0xbda78bf13db58db6U, 0xbd024996becd2f09U, 0xbe1107e3bec1187bU, 0xbbaa0deebe2ef524U,
0xbbde86cbbd1ad83fU, 0xbd692d68be072a94U, 0x3e08ac633ccc39deU, 0x3d664069be11a19cU,
0xbd246ef9be716835U, 0x3d7785b23c108478U, 0x3e1d38e5bd8b26a1U, 0x3d2fe29abe235be4U,
0x3e12dfab3da7c945U, 0xbdc31c3cbe31fd65U, 0xbe740a213c9cad62U, 0xbea91c143d1eb6b1U,
0x3bd2ab1ebd120833U, 0x3d56d553beafb553U, 0xbe2eead03f0aa13bU, 0x3ef632a63e40d02bU,
0xbea616aebec5cfd3U, 0x3e97b0f93ccc8429U, 0x3c7e66c0be848378U, 0xbe34188c3e35aeddU,
0x3ef5b2a9bdd28738U, 0x3e9fecfcbd9676fcU, 0xbb4c7cd43ca810faU, 0xbde3efbbbd0c712dU,
0x3ecc2b553eaee6a6U, 0xbdc8e9c6bf15803eU, 0xbc49be57be4d59cdU, 0x3c904d49bd80c459U,
0x3e661a33be24cb78U, 0x3e8e58a83b2bb766U, 0x3e51ed70bcab4bb7U, 0x3e80a622bd996fc6U,
0xbe0fe863be254547U, 0x3e4c02ce3ebe3040U, 0x3eae39cabe5bf185U, 0x3eecba97bdfd6cb9U,
0x3eb51764be2e8444U, 0x3b9ccadbbd3066a6U, 0xbe8caf06be6a8551U, 0x3e89b1873e015335U,
0x3ea8bcd03ef07ca0U, 0xbe051ded3e353291U, 0xbbc34f423d14d8f9U, 0x3eb055be3e76f01aU,
0xbe3e314c3e952ff4U, 0x3cc439833e1a8ed5U, 0xbe6d47c23ebc40fcU, 0xbd657207bec69574U,
0xbd92d3973f01ee3cU, 0xbee388b53e5d1114U, 0x3e0f80c83d67ad4cU, 0x3f11cf70bda12a77U,
0x3e1e21dc3ed40b00U, 0x3e9088f13d07ee9eU, 0x3e750f48beb43505U, 0x3ef1dbbc3eb94704U,
0x3ebdbc26be989d8eU, 0x3f08364e3d0b7ecdU, 0xbe5c3188bd99d148U, 0x3da3a02dbdf968b2U,
0xbd622cdd3e1ba631U, 0xbcbea9edbc844359U, 0xbe56b4d23e4b7a42U, 0xbea2531abd71179fU,
0xbd3ad19e3eb39eedU, 0x3df482863de8b6e0U, 0x3ea7e05e3e0a9a8bU, 0x3ebf5ea73eba6309U,
0x3ea59cbe3e498f9cU, 0xbdfac2bdbcfdca80U, 0xbe5035163d4eeb64U, 0xbd9236543e8761a2U,
0xbdd2c2123d90492fU, 0xbe00f1743f20240fU, 0xbde3c056bead257eU, 0xbe845e7d3eda490aU,
0xbef8209d3e051d07U, 0xbe4c3a8e3e20bf8dU, 0xbd8bfa14be675f76U, 0xbd2635eebe0ff08cU,
0xbdee3bf6be3ad51cU, 0xbd9c3cfcbd84c33dU, 0xbcaafde5be1226a5U, 0xbe855b163e0e5533U,
0xbcbf35bdbdabaeaaU, 0xbc252338bde621acU, 0xbdc7cfd0be38002aU, 0xbd9f5cdb3dd05558U,
0xbd3a30e2be85a1b8U, 0xbc882202bdd0cf13U, 0x3b8062ba3d2b5933U, 0xbe476418bd416687U,
0xbd9734763e04e1a4U, 0xbdc81473bdc96108U, 0xbd1000a33d5cb917U, 0xbe078a9abe46fa9aU,
0xbe069b3bbe1c3949U, 0xbb9d70bcbdba39c0U, 0x3c8d8609be33e7c7U, 0xbcceef763d484296U,
0xbe06b439bc96fd77U, 0xbe09fb64be2e15c8U, 0xbd85a499bdb4e2fcU, 0xbbf58237be49cb0bU,
0x3cc25901be2efd29U, 0xbd7c7d9bbd133d39U, 0x3c82f652be207857U, 0x3e36a7adbd9db0c3U,
0xbd7d8b89be2a6e43U, 0xbe1f86f53df93debU, 0x3c697379be02a5b1U, 0xbe3f1bd0bced66e9U,
0xbd9b8e67be1a4e76U, 0x3c7f9880bdc4ceabU, 0x3d1e1a02be221176U, 0x3df8d975be8ee56cU,
0xbe13d470bdad2f95U, 0x3d71596cbb317bacU, 0xbcd638c4bd973d6dU, 0xbe3049a4bda615d7U,
0xbe25173f3c50de2dU, 0xbdfe9876bd86c436U, 0xbdc9adf1bd87f3e3U, 0xbdd38106be3416b6U,
0x3d7e49263d12d6beU, 0xbc9d42b63dbb51d2U, 0xbc4a72cdbcb71eafU, 0xbce2c54dbe145164U,
0xbe49d274be69bff3U, 0x3d582bd1bed03e5fU, 0x3d50b86ebe4786a0U, 0xbe2e0c58bdb162bdU,
0x3d0d43f4bd8f8771U, 0x3d9bfbf23ce4866dU, 0x3daa583dbde9ea40U, 0xbe458bb8be7f6a86U,
0xbd66a8fdbe2d5fd1U, 0x3d5c5d6cbd849ab5U, 0xbbb3691abe618b8eU, 0x3b34bd4cbe895e0fU,
0xbe38673ebe46ca91U, 0xbe274e39bcce9c6cU, 0xbe72b0263d4a9637U, 0x3e39f6a33e9c3f9eU,
0x3dfe32d5bdb830fdU, 0x3da5c5cfbd0922a8U, 0xbe45ae933d2ea2e5U, 0x3d64409cbda3b036U,
0xbe17a8a5bcdc3972U, 0xbd9050113d8c70acU, 0x3d312cf03cb0f01dU, 0x3e2ba700bd2e2672U,
0xbe94f5cc3d977ccbU, 0x3e77a940bc1e8fe3U, 0x3c4140d6bdc653b7U, 0x3beae71d3de607edU,
0x3e1d7174bdecd057U, 0xbe1134483c8fe331U, 0xbbd20d81bd977738U, 0xbdbdfabd3da5c573U,
0x3df1f70e3e1be03bU, 0x3cc182533dbc82deU, 0x3d4b2af43dd71a71U, 0x3d667e863de10e80U,
0xbd9a5cbebd83a416U, 0xbd4f83debdee0460U, 0x3ea1a0dcbc49785dU, 0xbdd1e337bafc081fU,
0x3e2b82ce3e01e876U, 0x3d8a8d10bdbc0474U, 0xbd3355a2be5b1b73U, 0x3e0c1bd6be4cd336U,
0x3e2546dcbd321d5cU, 0x3e345fb5be627689U, 0xbea1989abc9c769bU, 0x3e14db943e204b1cU,
0x3d814a27bcc2ac75U, 0xbc7ef9123e70c682U, 0x3d9cbc96bd34644cU, 0x3dc4192dbcd12feaU,
0x3d7d41dabdb4ff98U, 0xbdb2bd84be11cb70U, 0xbe0013433e0fd39fU, 0xbd3655b3be1952f7U,
0xbe06af333de924a9U, 0xbda208023c04a86fU, 0xbc1dc5873c3f831cU, 0x3e7474ccbc1d24dfU,
0x3da5eda8bba3cb09U, 0x3d99132f3d964714U, 0xbd60ac8d3d2e0a22U, 0x3d910f81bdadc60eU,
0xbbfa02693ca368f0U, 0x3e2bb5afbd0fa9b8U, 0x3e66061c3e7ee76bU, 0x3e533a2dbbff2a68U,
0x3beb9396bcdc5ac3U, 0xbdca8e263da1cd2cU, 0xbe6261e03d6cc197U, 0xbcda6895bc8391f0U,
0x3e21e2923d075c45U, 0xbbc3135b3d661305U, 0x3cbbaceb3d974cffU, 0x3e7341363cc4b34aU,
0x3ea7070e3ce7b668U, 0x3e2bfd96bc9a74f9U, 0x3ca4fed93dabc07aU, 0x3d5952aa3e721c50U,
0xbec8922cbcf9b613U, 0xbd354a0bbddd15b3U, 0x3d41aaa6bdc73bcbU, 0x3e2fd269be8d88a7U,
0xbe0b86f53e5a8914U, 0xbe414e92be52a257U, 0xbeea1f753e5ae12fU, 0xbc33c624be05e875U,
0xbe3d23ecbdd39695U, 0x3cef34b4be5eccdfU, 0x3e34a9543e2949c0U, 0x3d56df94be2a09daU,
0xbe4f4248be516460U, 0xbe5448d63e0ea9cfU, 0xbe35c77bbddd2b3aU, 0x3e270bca3d575185U,
0xbd96117e3ceeae95U, 0xbdcf80dc3e5327ffU, 0xbdba636bbe828045U, 0xbdce5fdc3d9511baU,
0xbdbbde013e2e39cfU, 0x3da4a1cfbe591132U, 0xbd89e8423e4ce020U, 0xbdfd9f213df8eb62U,
0xbe5c0e7ebee49a86U, 0xbdf981913d190e8cU, 0xbd3088bcbe2c1109U, 0x3e1bc54fbe427e5fU,
0x3e0ec0a33de7cfe4U, 0x3c7635a0be85c435U, 0x3da591dcbecc93dfU, 0xbe75c40bbde0ab47U,
0xbdbd7a4d3aa0ab31U, 0x3dd284e2be86424fU, 0xbe661cc5bde77505U, 0xbe1aa451bec094a7U,
0x3cd39916be0bf6e1U, 0x3e03f02fbebb517cU, 0x3e010390bef56992U, 0xbd8ec7b33e060dfaU,
0x3e2a454c3d7acdd0U, 0xbddec21d3da5f402U, 0xbebd60c63e38860aU, 0xbe33b6893d58156cU,
0xbdabd64f3d632796U, 0xbe0c1174be9f47baU, 0xbd1fb4073e8a208aU, 0x3dbcce38bdc4f47eU,
0x3d7f72c53e5a5a72U, 0x3d1f8cb4bd8d7d40U, 0x3e3b8bddbe204223U, 0xbec15441bedff782U,
0x3e1ed038bf0e43bbU, 0x3d8cb6eebe8e34aaU, 0xbe6d7dcb3d8b0f1aU, 0xbd837f403e2afebaU,
0x3e1278f03df97924U, 0x3dacb8afbcab8559U, 0xbe9652ccbec47e94U, 0x3d656880be4ef3ceU,
0x3daf18e3be706191U, 0x3c6f6c02bee6458cU, 0xbd662fe3be33adb6U, 0xbdf43ee7bec8d830U,
0xbe6e684abe2995bfU, 0xbb8fb977bdca74caU, 0xbd902473bdb1bf1fU, 0xbdcf29d1bb09c174U,
0xbeaec0d53d4e43bbU, 0xbd585221bdd0d6e4U, 0xbe4b67f7bdedfc72U, 0x3dc74f31be03d49aU,
0x3d83f7a5be220092U, 0xbe27df97bdff0b68U, 0xbe0a6860bd878a9bU, 0x3e2a8a01be24273bU,
0xbe1a6eb6bd3dff97U, 0xbe196c84be3da887U, 0xbd4e3724be28e758U, 0xbbd1ae0fbd0dbeecU,
0xbc9cd231be85020aU, 0x3d5fe188bdcbf49bU, 0xbda8dbefbe351b45U, 0xbe4afe50bceff30bU,
0xbd05da38bd2f3d19U, 0xbdabab09be1ba790U, 0xbdd42613bdc4d0ecU, 0xbc6b8d7d3c2acc6bU,
0xbda2806bbe4b193dU, 0xbe48f996bd468e90U, 0x3d21a1cabe37bd7bU, 0xbe08d520bdd9f238U,
0xbead19f7bd4c98f6U, 0x3dfe5b973b856defU, 0xbe81a1b83d5ba534U, 0xbdd528203e086fa3U,
0xbe6906133d65938bU, 0x3db19104bdaf0051U, 0xbe17fe64be79cea6U, 0xbe2aa32d3dfa6f9fU,
0xbe8ac7cdbeb354ecU, 0xbe893884bde4c419U, 0xbdbb8d42be19eff9U, 0xbea3ed9b3d974315U,
0x3da47b403e49d4f1U, 0xbd45f292bda8c630U, 0xbd60aa823db30830U, 0xbd7350dabdb98a87U,
0x3db73159be12b73aU, 0xbe43af86bdfe0097U, 0xbe28946ebe226de1U, 0xbdfd702bbce452bbU,
0x3cbe2fadbe4e2958U, 0x3ded9ab13d19ac34U, 0xbd6eea63bb349c0bU, 0xbe88622e3d4327ccU,
0xbe1536523d5c9bc0U, 0xbe8d1323be0ff076U, 0xbe5d933bbd62a131U, 0xbd42e10bbda003dcU,
0xbc6f0533be897845U, 0x3de50823bd31d587U, 0x3d38dc6cbc1123c3U, 0xbe175ab6bdaddde6U,
0xbe6c7338be5e9c59U, 0xbdbe5b293ca764a7U, 0xbe637003bce67a40U, 0xbe8e236ebe0a6757U,
0xbdffa6b9bde75da0U, 0xbe3b4890be11c2c0U, 0xbcb8c9a9be598cc7U, 0xbd05d1523d83aee1U,
0xbcadd0693cc62166U, 0x3dab52b2bdcc24d0U, 0xbc88cc29be055486U, 0xbebab8193de9b8d0U,
0x3ca39e9abe9da720U, 0xbd5ace233da225b4U, 0x3cab441bbd85e7ecU, 0xbdc62173bcf47847U,
0xbd601b3b3dab2cbdU, 0x3d70e1793d7c79a2U, 0x3d0485113dc3c8c4U, 0x3dac4fde3d669343U,
0xbeb838503d028767U, 0xbead3eda3d934aa9U, 0xbd02e4893d5c898fU, 0x3bd730693c3d5e43U,
0x3c823a81bd835eb7U, 0xbcd43180bba8ff6eU, 0x3d9a6cbdbc94c66fU, 0xbcb6774d3d8dae89U,
0x3d124d65bb7b9ac0U, 0xbdbc16043cc9fdf3U, 0xbcb572693dc960bfU, 0xbd97aff33ce50bd5U,
0x3d6846453df9ddd7U, 0xbe4e33b4bd127293U, 0x3da13da8be957bc5U, 0xbd430ecabd3a56b2U,
0xbd296b283ceb9891U, 0xbdb19e0abda41386U, 0xbcba20cfbc2e3e3bU, 0x3cdeba1abd8a69c4U,
0xbd2c064bbdec41b3U, 0x3d6fe6b5bd212ef8U, 0xbeb227bcbe67a946U, 0x3ca5e0eabe1446a1U,
0x3d92ee2bbe04e021U, 0xbdc80b2cbe87342dU, 0x3c90abb4bd833763U, 0x3da363a0bc6cd495U,
0xbcca66c03d5ec309U, 0xbe67a7d93d4f5031U, 0x3c119fc43d090cf6U, 0xbeaf6d1abddcae43U,
0xbda656edbd0735c9U, 0x3d7fe1933c418368U, 0x3de44c93bdba336bU, 0x3db4d4c0bd63a156U,
0xbcf27a8a3c3a0bcbU, 0x3d10a9b4bd5c3ebdU, 0x3df034afbde146b3U, 0x3d4cb587be1bc1fdU,
0xbc618fde3a5b6455U, 0x3a57c1b2bc246226U, 0x3dc506793dd2b16bU, 0xbdbf5eef3c9f90afU,
0xbd589d073dd9718bU, 0xbda07a14bdb23b37U, 0x3d606a57be312d9aU, 0xbd71c9853e4cd869U,
0x3c032290bd33e53fU, 0xbdf0f71cbda33d53U, 0x3a530fdb3d1be1f8U, 0xbc9d8a59bdcc9b36U,
0x3c7bba56bda16a54U, 0xbcad1980be056f68U, 0xbb90476abe11c2f5U, 0xbe38686b3e0f447eU,
0x3e4aee443d95029cU, 0xbe6d1db0be275817U, 0x3d8507bcbc52a616U, 0xbd551a35bd7f3499U,
0xbd7348d53d9d50bbU, 0x3cd3a776bca678b1U, 0xbd0f8e723d4a5694U, 0xbd90dd463bc16851U,
0x3dc989c33db79a06U, 0xbb68cba8be056f62U, 0x3cdd80cabd576c79U, 0x3dde816cbe2ba3a1U,
0xbce370fabd7f5f3fU, 0x3dc2f8963d008d0dU, 0x3ce6da67bcf6d72aU, 0x3de82cb23cda9553U,
0x3d804e613d10cef8U, 0x3b45f55fbd27da91U, 0x3d4d29053e06387dU, 0x3d5eb17bbc8a0bc2U,
0xbe037a32bd8b197fU, 0x3dfb9b353d8d3c3aU, 0xbc1f2e04be0af505U, 0xbe130f233bf2367bU,
0xbcd3b7953d35904eU, 0xbe1ab2703d4de570U, 0xbe0776b6bd9533acU, 0x3d210f263d87ccaeU,
0xbdc3eb90bd0f3c51U, 0xbdb809fb3d99d6a0U, 0xbabd51043dbfeb22U, 0xbe44c2d7bd219855U,
0xbdf12619bda15211U, 0xbd1a1bcb3e224cf4U, 0xbe3621cf3d1b4a1aU, 0x3e2e70aabc23a806U,
0x3d949fdc3e0ddd92U, 0x3ccc69043c2a9d7dU, 0x3d831f5b3dcf778bU, 0x3d42dba2be7319fdU,
0x3d392a86bd285c22U, 0xbe28b4b6bd13b073U, 0x3e1ba6063d1412a4U, 0xb8d65c523d4993b2U,
0x3d8f48cb3d6c62abU, 0x3e194b1d3d2102a6U, 0xbd98fa70bcbd0314U, 0xbe2d20123d4a566cU,
0xbe44b21abe2871c2U, 0xbd07d66e3e30fdf5U, 0x3cee858e3d6f0834U, 0x3e3468aa3a7d5777U,
0x3b1995483dbbd690U, 0xbc4d977c3e331b41U, 0xbe43df79bc73bb91U, 0xbe5b9042bde8249eU,
0xbd91a36e3d1b7d86U, 0xbddf69ae3ded942eU, 0xbdf94e273e0dac52U, 0xbd9f86f9bdacd067U,
0xbbe38f4fbdd909e7U, 0xbe8c6dfbbcd9b8f8U, 0xbeaa288cbe0d749eU, 0xbe999173bdaaac16U,
0x3e861aa03d66b839U, 0x3e6b2e48bdfbafb3U, 0xbdf013f83db30995U, 0x3d34c253be4f962eU,
0xbe47c63f3dba77c5U, 0x3e2801ef3ccec46eU, 0xbe40cf2cbe8937a0U, 0xbd7310253d16e5e1U,
0x3d13ee223cd9137aU, 0x3e25a7023c73e66aU, 0xbd2f9db23d3b463cU, 0xbe9492ca3e0e13feU,
0xbe6feb813dcd1f60U, 0x3d8640c13c0f34d7U, 0xbd057f11bd318157U, 0xbde88b513e2a3e86U,
0x3e51a96ebdb672d0U, 0x3df6c8cf3e6170f7U, 0xbea989663e870375U, 0x3ddb377fbd231796U,
0xbea346bd3e19cef9U, 0xbe14d3ef3e269219U, 0xbe2bf4b1be5b1895U, 0x3c5b578a3cf94d88U,
0xbe560160be0747d6U, 0x3e325c88be2a6654U, 0x3e6c2a093e31171aU, 0xbbd70643bae5bb2aU,
0x3c7d9c68be636c85U, 0xbdafd7033dd7c235U, 0xbb2e857ebdbf8133U, 0x3dcdeb24be4c913aU,
0xbdbe5d9a3da2d47eU, 0xbe82af89be97b5beU, 0x3e6a8e22be509c9cU, 0x3e967cb2bd05ffeeU,
0xbdd1a8d1be3c7455U, 0xbcd3fbc03e1abb68U, 0x3d721e9e3e76ed60U, 0x3e8018b83da3286bU,
0xbe654b673d77500eU, 0xbd06dd963d49353eU, 0xbdfdb1613e8118a5U, 0xbe2bd4d6be53e6e5U,
0x3e410a403e9e2d85U, 0x3ddcfe6cbe615ac7U, 0x3e1d241a3e38f6e1U, 0xbd2e56583e59a2bfU,
0x3e30a4e5be8c8dceU, 0xbed01d09be133abfU, 0x3e860b41be8f1447U, 0x3e646c5dbdfaee5bU,
0xbdc151513e292ceeU, 0x3df005553d82076fU, 0x3e3b3a573e4fa92cU, 0xbe2313e03df91819U,
0xbe493275bd83036aU, 0x3ea396aebea796d2U, 0x3e26220ebde7936bU, 0x3e50e59cbe3e30c5U,
0xbdf94436bd99f315U, 0x3da36dc2bea6c24cU, 0x3d9b1f8ebdf70c77U, 0xbdbd1f3abe3836d7U,
0x3db06add3d2a7cb9U, 0x3d8b49babe750ed9U, 0xbef703a23f02a78eU, 0x3efb74f6bd55f6c7U,
0xbf27474cbf52b81bU, 0x3ebe780b3de48fdfU, 0x3d8bd035bddeed70U, 0xbeed54a23e8c7d98U,
0x3ea45240bdcb1c2dU, 0x3e660733bea74b6aU, 0x3e1f94ec3e2da915U, 0xbe4b59073e9a65f0U,
0x3ed9355e3e4ee394U, 0xbd54ba2bbf10b0ddU, 0x3caabf46bf149847U, 0x3c7e14f73df56c0bU,
0xbd671254be7addc2U, 0x3ecd25f0bdef37afU, 0x3da79a16bd9b8094U, 0x3cc09095be2bc2feU,
0xbd8a7772beb9e9b0U, 0x3dc00fca3e898034U, 0x3ed322cabec2aa41U, 0x3ea8fe36be1108f4U,
0x3ead5b07beb6d0b8U, 0x3d0503eb3ca2980fU, 0xbf1e5d7cbeeaa424U, 0x3ec444a73e24565aU,
0x3ed0027e3eca0fa4U, 0x3c1f9a273dd4d3f5U, 0xbcde71a4bc96562eU, 0x3dc05ccf3e1b08d8U,
0xbd4ed6f53eb7cac0U, 0xbd81483d3d8e4aa1U, 0xbecdf9373efc42c8U, 0xbe9be6ebbf473b2aU,
0xbdd938663ef7aacdU, 0xbeb1a0153cd03f98U, 0x3dbaa4463dd5d9b9U, 0x3edfa86abda95e6eU,
0x3e65e2423ed1c5f2U, 0x3edd65cdbde5a7f3U, 0x3eaf12aebe1bf5aeU, 0x3ee5427e3e738aa7U,
0x3e6c986dbf2a3d39U, 0x3e8a398ebce0e6a2U, 0xbe7f0a82bd889131U, 0x3d55ae143d7bec3cU,
0xbd4378213e2360f0U, 0xbed2dfdebcdc4cf9U, 0xbdee31fc3e77b1c7U, 0xbe2b10433dcbd2f4U,
0xbcfb5aa53eff3086U, 0xbd3de5463d0565f1U, 0x3eb333363eb715ecU, 0x3e81a9303e9fec0bU,
0x3eb0adb63dd99939U, 0xbc86da3d3da0aa96U, 0xbf085e0e3d2581a6U, 0xbcfcbeb83dde9c82U,
0xbb7964543df977a9U, 0xbe06c40b3edda7e6U, 0x3dbd7703bf0a91a1U, 0xbe288ba23eb5ba55U,
0xbeec75c83d5c9d81U, 0xbd3e7c7fbde4d5cdU, 0xbd2bd4f6bd7808e4U, 0xbc0e058c3d9f1feaU,
0xbda1b3f7bca4fdbcU, 0xbe7b0f89bd9fafe2U, 0xbd6542a0be26b3d6U, 0x3bcaec49bde2b80fU,
0x3e13f198bdfa9de1U, 0xbd897489bdc62f87U, 0xbd64197e3d80ef04U, 0x3da8f33bbe0ee1e6U,
0x3e2bd276bcf0ddadU, 0x3dc9bfa1bd7a6fc2U, 0xbdb256b33b9fdc9eU, 0x3aab4a89bdda3e22U,
0x3d91d3d93ce4df72U, 0x3e20712abdeae49dU, 0xbdb386a23cea8b18U, 0xbd36513a3d8691f1U,
0x3d92225f3c8d2cdaU, 0xbddd8d2b3c27c73eU, 0xbe22b7333daa5eceU, 0xbdcc6f963e048bf1U,
0xbe0575abbdc78879U, 0xbca13a483e35aadeU, 0x3d28f736be0da760U, 0xbdeaf44a3d61718fU,
0x3d9a096bbcb5a67bU, 0x3d6e7231bcd757c4U, 0xbde9ede43e1f2b92U, 0xbcab4b94bbbea1e5U,
0x3d66b57f3e0056f2U, 0x3ca3654dbe498011U, 0xbd842f193daa0befU, 0x3dbe82f7bd6ac201U,
0xbe064b0ebc8ff7b4U, 0x3d809e55bdead3e3U, 0x3cca75cd3ac83e72U, 0xbda38a963a91aa4eU,
0x3d9689163c67e8a7U, 0xbe029e9bbd2ca83dU, 0x3d8bd0ef3e4d0192U, 0xbc394903be22891fU,
0xbc61617abd888ae4U, 0xbdad09943d9e9143U, 0xbe66a0693b72ae1cU, 0x3e0fc3a7be1f5de3U,
0x3ddae866bd8296a2U, 0x3d2e1b13bc6cb74eU, 0x3d8535673d8f9943U, 0xbd88bfc6bd79c790U,
0xbacda944bcbc6745U, 0x3e0a74413da4943bU, 0xbd092137bc8ada33U, 0x3e4903febcb0e119U,
0x3db935f2bbebd354U, 0x3d833c2a3b7e1ef4U, 0x3c9fc637bde012aeU, 0x3b1c6971bd42b852U,
0x3b4fe978bda7fb6eU, 0x3dcfd06abc80478bU, 0x3d7714743e3db8aaU, 0xbe2dbb393d3913c2U,
0x3dbf3461bcf3d9c9U, 0x3e10e8a53dd0c896U, 0xbebdc363bd924b27U, 0xbe036660beb65b32U,
0x3d695c76be8940e8U, 0x3d23c4423ca98d5eU, 0xbd1921823e8d052fU, 0xbd9b06e3be551b7bU,
0xbe188d75bce43169U, 0xbda0ac1dbe4d461dU, 0xbdd1b1c13c578ff5U, 0x3da1e29bbe0edc60U,
0xbe8c4e7a3dc77270U, 0xbdebc7f1bd4a82dbU, 0x3e54596dbdf70379U, 0x3d82ea99bc128390U,
0x3c4563edbe1d8bfeU, 0xbc87a14b3df26ed5U, 0xbd0ffcfbbde0ba44U, 0x3e2940313e27ac33U,
0x3cb7adf1be21f7b2U, 0x3e9ee7aa3e3bf1cbU, 0x3e26bff53e602b75U, 0xbe3a6320bd19d9e8U,
0x3e6375f8bc1cb5afU, 0x3cb83113be3b730fU, 0xbdc21ce8bddc99acU, 0xbd5079403a706a59U,
0xbe22b25ebd565b12U, 0xbd3c464dbdb866b7U, 0x3ab976b13bd3d8c4U, 0xbd9d42c33caabc4aU,
0xbe9fb7cebd825eb8U, 0x3eb36517be7c395eU, 0xbe1829933d150361U, 0xbe764ac7be051ea8U,
0x3e54989f3cb563a5U, 0xbd8aabf9bdd5a4f9U, 0xbcc88767be23ed05U, 0x3de4b3df3e868686U,
0xbda9690d3e3d44f7U, 0x3dffc861be4b95dcU, 0x3e38008e3e60568dU, 0x3d376fd2bded0bb1U,
0xbcdf2e053ea5be02U, 0x3ce5fc9ebe10e713U, 0x3e9e2dc6bd0166a4U, 0xbde67299be123f9bU,
0x3e7f5641be673aa3U, 0xbe829a9f3ea67228U, 0x3dc9a0bcbd4cd7f3U, 0x3e5f8ca53e2d09d2U,
0x3bdfb9583cf2f49fU, 0xbd811c9c3cf14debU, 0xbe2b9017beec33fcU, 0xbe6698463d9672eeU,
0x3da07cf13db8dda4U, 0x3d284609be703475U, 0x3dcbcda83de7c712U, 0x3d239a543cc8b579U,
0xbc5338dcbda75ff5U, 0xbdf6440bbe26abd4U, 0x3d5b538f3e4d3cc1U, 0xbe1233bb3d67f27bU,
0x3e00a5743e93036bU, 0xbed89c57bd9e7be4U, 0x3b6e5ae23dbba8b0U, 0xbe64e8d63e153f25U,
0xbe86d497be69531fU, 0xbd69536ebe99d5eeU, 0xbe373eedbdc0c705U, 0xbd14b62c3e305d3fU,
0x3cbff972bd9136d9U, 0xbee9e9d63d85286bU, 0xbea9ff5cbefb3820U, 0xbd0a4e50bec1001bU,
0xbe07d1e5be8160bfU, 0xbd81e2893cfe0d53U, 0xbc1ce707beaf3683U, 0xbea35abb3dabdaaaU,
0xbdc0ac713dc61ac2U, 0x3c4c2ef3be920e84U, 0xbe14fd973b9400c8U, 0xbe8319d6be52f73fU,
0xbd73b2963d2c6967U, 0xbdf75a64bea144bfU, 0xbd33afd1be15591aU, 0xbe70739bbebed830U,
0x3db27e173d3efccbU, 0xbea83854bdb1c2c8U, 0x3e6bb880bdae6cafU, 0xbd8f18e23abfcbfbU,
0xbddeee3bbe6af1f7U, 0xbe0228d33d5d15ddU, 0xbdd35d56be3f525bU, 0xbe0108cfbc8f8257U,
0x3d3f47953d479b31U, 0x3d047e1c3d8022a0U, 0x3e3fb31abe5b95d7U, 0xbec7e38cbdce4f43U,
0xbdbe19c43c146ed3U, 0x3bf82de9bd9eda43U, 0x3e1fc8afbe880e9eU, 0xbf0171d839f94501U,
0xbe2956463e6602e8U, 0xbdb6ce8dbdea19baU, 0x3d2823d1bf0748d8U, 0xbe16b30abf1f2544U,
0x3ced8546bda2adf8U, 0x3e5afdc5bdd57405U, 0xbdb7a349be41bfdeU, 0x3c169127bc0a9c81U,
0xbdfb7ccbbe8b6c3bU, 0xbbcff421bdeca6b0U, 0x3e7574e6bdf11675U, 0xbec3e8893eaaeac8U,
0x3b1dabccbdeb6ba7U, 0xbe6dbc0dbe5a0c1cU, 0x3e090a5f3e507c56U, 0xbced0e06bc97243eU,
0x3e3896463dd8120bU, 0xbb10052b3de297deU, 0xbea14ceebe2c28d3U, 0xbedbe1a1bc4b244aU,
0xbe5380b6be220f91U, 0xbe33c3df3d25c7abU, 0xbe2a1e883e18b61cU, 0xbe7df18a3e7f133eU,
0x3e68e1863e91e7f9U, 0x3e06b5ec3dc1ff6bU, 0xbeadb7993daeb149U, 0xbdb958f6bbd686b3U,
0x3d1734143e0025cdU, 0xbc0a3472be5e8690U, 0x3d23eff2be043e70U, 0x3dfaf7313dbc794fU,
0xbdd946a6bc21f90bU, 0xbd91fe77be060f68U, 0xbd3356453ca668d8U, 0x3e13cc42bd042318U,
0xbd98f14d3d11be52U, 0x3de9cd613d126838U, 0x3be6e0003e052d8bU, 0x3e2a9e9b3d5f5475U,
0xbc0cfda4bcd687aeU, 0xbcb948cd3d744958U, 0x3dcc9f2c3dfcae42U, 0xbaa5d2313e072a63U,
0xbcaad0eabdb798cbU, 0x3d5736d0bd4a3688U, 0xbd354d04bcb666f6U, 0xbcc2f261bca2bf77U,
0xbc099733bdae854eU, 0xbe077c91bd15b16bU, 0xbe0e0eff3d273898U, 0x3be23f653d623930U,
0x3dcf471cbda4380bU, 0xbd18fdf6be58964bU, 0x3da7f96abd9cf725U, 0x3d3086eebda1b9f1U,
0xbd38022cbe8ba07eU, 0xbd20c06abdc0100dU, 0xbc4421cbbc8af2c7U, 0x3db7483cbdb5c43fU,
0x3ca77702bbe3069cU, 0xbd0fcdffbc3b371eU, 0xbe1b141fbb951ab8U, 0xbcab45283caee611U,
0x3da5d7193cc435c7U, 0xbcdc870d3c2e2779U, 0xbdd80a13bd7383d0U, 0x3c6008013e66d70fU,
0xbd88a2893deba67eU, 0x3dc90a9e3d9c1267U, 0xbde6d49dbe095855U, 0x3d1bf8f63d2ee896U,
0x3e3cf0e83d3fffd0U, 0xbe75d569bd863bb9U, 0x3ddb390abe43194dU, 0x3cdb51cbbe37f631U,
0xbda9ba25bd08b31aU, 0x3d178015ba930c9cU, 0xbdd7fe213d305e70U, 0x3dbdbab6be4b4086U,
0x3ddc40b4be5e2fd4U, 0xbe2cb9453dbf03e7U, 0xbca68e4c3d190e63U, 0xbc8c0986be52c3b4U,
0x3d19a598bcd0c08eU, 0xbe17393cbcc5cbc1U, 0xbe100181be03cf5eU, 0xbdf232df3ddfc9dbU,
0x3c9aaf11bdd4ad39U, 0xbadeddb6be50be72U, 0xbd5381edbd86bf8eU, 0x3cb3c9043e29f6e7U,
0x3e183bb83cdb2311U, 0xbde0fbe33dd1ff1cU, 0x3df2c265be0984f5U, 0x3ea9d610bd0a3aa5U,
0xbd9f9d48bd4b05b9U, 0x3d877deb3db275d3U, 0xbe3b57483d99286cU, 0xbcd136f03da1a453U,
0x3d124e35bd4f9ecfU, 0x3ce20a2a3e1d1c2eU, 0x3e096b7cbcf1f9c4U, 0xbc94dd91be46a2e0U,
0xbd9689c03c8b5487U, 0x3d16c9fb3d0d1cf7U, 0xbe8ce4163dc31301U, 0x3bcd0edf3dc722fdU,
0xbd18103abc9a1d9dU, 0xbda7ee403e3ed703U, 0x3d591527bdc504bfU, 0x3c5fd38a3df7bd77U,
0x3de4d9043e1d2d59U, 0xbdad03e43c554551U, 0x3c435703bcf07ef6U, 0x3c9817ce3d7c457fU,
0x3c0a8f863e014508U, 0x3daa8bdebd1df7bbU, 0xbe07f02a3d9e2c2dU, 0x3d17978a3dc563d5U,
0xbd7e4d253c626ca7U, 0x3d7849713d33e1daU, 0x3db9f83dbdfc03a4U, 0xbd7d0b78be2c9a97U,
0x3da1177fbc0e8c80U, 0x3d624a813ce48096U, 0x3cec3c45bde50890U, 0x3d676592bbe067baU,
0x3d164dbc3e083586U, 0xbe41f64d3bbcd3b1U, 0x3e12bebebce1ba47U, 0x3d6635813d503e81U,
0xbc48207c3bc31f6aU, 0xbc646f1abe864c31U, 0xbd3b5bcdbe23e9a3U, 0xbcf6b8173cd2d315U,
0xbde5b3ce3d452051U, 0x3c413cca3e0d2d4cU, 0x3e2d742f3d83bebaU, 0x3c91f7ae3e115f57U,
0x3d9927b93cd19459U, 0xbded7f1ebd31696eU, 0xbd64fe79bd850d1eU, 0x3d37a191bdf53524U,
0x3dc4073e3d367477U, 0x3e23d7803e352cafU, 0xbdba97f2bcf1af90U, 0xbd4034243bb731dbU,
0xbd2df10c3cfdc457U, 0xbb9e710dbcf7fbbeU, 0xbd393bebbd5872f7U, 0x3d6463b7bd98a380U,
0xbdf78fce3de2b250U, 0xbd376410bd6a6886U, 0x3d3434e9be5e5d25U, 0xbcc3594abdfc91c3U,
0x3db0a635bcfd209fU, 0x3dd0f2f7bcb2775aU, 0x3b273cf2bb54058dU, 0x3db5089fbe22a462U,
0xbc3275c13e049f41U, 0x3dbc86b73dd67932U, 0xbe88af3f3e26f04eU, 0x3dbd225abda8a56cU,
0x3e7121bf3ded5790U, 0xb7cf59093d6341e7U, 0x3e539094be13abedU, 0xbecc5c103dd2a201U,
0x3dbf909cbd89b00fU, 0xbd556c1b3d121e13U, 0xbea38fbdbe0bccf3U, 0xbd28bb11be16626aU,
0xbdf125923e5fe47fU, 0xbdc867acbe315204U, 0xbe18e4a7bd0c4570U, 0xbd64b5e83e60a9b0U,
0x3d660bb13da8963eU, 0x3e025c83bd78dd5dU, 0x3a461a26bbb0f216U, 0xbd508b623d9ff77dU,
0x3d9d2261bc21beb5U, 0xbd724340bb2641dfU, 0xbd9cf547be4e3b26U, 0xbd3c59f03b868ebeU,
0x3dff5d51bd8516ebU, 0xbd9d61233ba5d74bU, 0x3d75f325bd5133e3U, 0x3e73f875bd708a2dU,
0xbbc984cf3d2c8024U, 0x3cd075a7be8cc4c8U, 0xbd89a4ffbd43e6c4U, 0xbeef9314bd02b90cU,
0x3df5b2af3d6c2f3bU, 0xbe9935b1bdec1ad4U, 0xbe0b5f5d3db6ebf5U, 0xbe02c30fbde4b1f6U,
0xbe355008bdeb5b68U, 0xbc83d552be294b37U, 0x3df18bc2bdd1f965U, 0xbc94b4f0bd911ff2U,
0xbcb7e7ebbc968f0eU, 0x3e12424c3dc6f8f5U, 0xbe0cfac1bd4edfccU, 0xbd6ccf263a3102a3U,
0xbb951384bdbbf183U, 0xbced09f2bd9b43c9U, 0xbd9bcb70b8d87bdeU, 0xbd85c2e73c052257U,
0x3c64a659bbd13f13U, 0xbd8775d8bdca0384U, 0x3d7764bcbe141c17U, 0x3e088846bd8378dbU,
0x3e1a43b13da75647U, 0xbc81b710bdba8a31U, 0xbceee9dbbd0e1b80U, 0x3e164dc23e05be8dU,
0xbcb2931abdc5b616U, 0xbe014f20bc7f9a06U, 0xbd8aedc53d4d1df7U, 0xbdd14a9f3daddd49U,
0x3d708eebbd8b8ed6U, 0x3de39fd8be96546eU, 0x3df05d533d01069cU, 0xbe7a63aebdb728bbU,
0xbd132be2bd31768bU, 0xbd6cce0abd80bdb8U, 0x3cff98633d3fbe8cU, 0xbd605468bd03ed7cU,
0xbdf6723f3c1cf502U, 0xbe17d4c6be1dfa8fU, 0x3e35ad98be893ec4U, 0xbd4346a23c2ad940U,
0x3d3031f03dd15227U, 0x3e89bee4bdfc29afU, 0xbe0cc6063de11660U, 0x3d59cfd5be0c304bU,
0xbdf0783a3d7dc47aU, 0xbe34d9903e16374eU, 0x3c25bda2be022e5eU, 0xbd4cfaad3e62f089U,
0xbddd9cb6be0991b6U, 0xbe26ec4fbe8cd3e0U, 0xbf01d1863dc7f3ffU, 0x3e045dd6bdc51f98U,
0x3e06e49b3c8ce0bbU, 0xbe00e0f83e438958U, 0xbe5fd753bdaf56cbU, 0x3e2de0723da41f03U,
0xbd0db605be49f04aU, 0xbd875b813d853d8eU, 0xbc4b0fc33d3d1d0dU, 0x3d42d6f2bc98dad3U,
0x3d43cd613ca6b397U, 0xbdb6ff56be75f13cU, 0x3dbf7e63bde2a172U, 0xbd7a9d0fbdabf639U,
0xbd1959653d056e0cU, 0x3d99ac833e50dbb3U, 0xbe8aeb533c85392dU, 0x3e45856ebd7bd11fU,
0xbec4f070be6fd4baU, 0x3e19bef03c4442beU, 0xbe2014b6be055bfeU, 0xbcf799e9bd803c43U,
0xbc8ac1913d8b25d6U, 0x3d59932a3c994459U, 0x3d6b0197bc894236U, 0xbebfcf05bdf0f7d7U,
0xbd93295f3c531d91U, 0xbd1537a3be092b9cU, 0xbdc6c7fc3e1eb3d8U, 0xbe04157cbe7ea099U,
0x3d1dfcce3d1ed04aU, 0xbdebccbbbd30ecb6U, 0x3c858439bd96205bU, 0x3d0db0f4be242c86U,
0x3bb620043dbff1a5U, 0xbc96881fbdd5e785U, 0x3d937e623d844675U, 0x3db78f443e44982eU,
0xbda4364abe007e19U, 0x3d64f992bc1c45dcU, 0x3ddfa9d1ba9f0b9bU, 0xbd897e6ebcb2fcb6U,
0x3c2e15783d1c1e35U, 0x3b741477bcae6acbU, 0xbe81c25f3dca313eU, 0xbe4aa922bde91874U,
0xbd8a2977be5d8a41U, 0x3d59b6fdbe064dfaU, 0xbe40884dbbcfa76cU, 0x3dd5ee8b3cde9c76U,
0xbd8862aebca629d8U, 0x3ce03f53be8422f0U, 0xbe60a14fbd19bf82U, 0x3d938ad8bceb65dcU,
0xbe641aea3da8c090U, 0x3e3ecca83d10c700U, 0x3e0d126a3d8c5cb3U, 0x3eb1c96a3ea72089U,
0x3de815eebe6b1596U, 0x3dfafa6c3db0f6c1U, 0x3de3d7393dcb8230U, 0x3e5946303e8c6d49U,
0x3e88c9c13e28c90bU, 0xbd312f90be9953deU, 0x3e8c1b6c3ea19f8fU, 0x3e6a80113cd6c19aU,
0x3e063c0bbe33e60cU, 0xbee8eaf13e41f021U, 0x3e66886b3d4c291bU, 0x3e0d92b93e4166acU,
0xbf060d50bb638770U, 0xbdd44bbe3e599741U, 0x3e9bf2fa3dbb970dU, 0xbd1d5889bec69f7fU,
0x3d2676b7bbec2b65U, 0x3d8b24ad3e00082dU, 0xbe379242bd91dfc4U, 0xbdc47a5f3deee52fU,
0x3da1ff7d3d5ed353U, 0x3e085747bd8fe168U, 0x3cc36bbc3db41961U, 0xbd82fd113e331416U,
0xbe871be33e353c6eU, 0x3d4dc98abdd756adU, 0x3dbdf1aabe77d176U, 0xbe06f9263cd8bcfbU,
0x3e8f80e83e1c37d8U, 0x3df633b8beb43eb3U, 0xbcc1b2c23e3b1260U, 0x3d2642c43d539efcU,
0x3dac7e4abb2cf1e1U, 0x3b32edb43db53449U, 0xbe019607be138d77U, 0x3d279ef33e34f1d8U,
0x3d09b67d3d660600U, 0x3e11f3873e4cda3dU, 0xbe445800bd6e7bb0U, 0x3de329d4bd0c31d3U,
0x3e512cdd3e449b0eU, 0xbd80254ebdf85ae3U, 0x3db45b0e3d826618U, 0x3ce88486be4cb26eU,
0x3da3c5933ddecaa1U, 0xbe00becc3e66d833U, 0xbce8af483c7a448fU, 0x3e3d2247bdc7bb8eU,
0xbe4041ecbda27d6dU, 0xbdd9d8bb3e3faf5aU, 0x3e3867cd3d964b27U, 0xbcf00c34bdc8c936U,
0x3d41d520bdbdf4a4U, 0xbe569cb0bd0fa134U, 0x3c8f5a9c3c392464U, 0xbd17e76d3dd1fff4U,
0xbe70b385be365033U, 0xbe97914abe295d42U, 0x3db9ddc4be17f096U, 0xbdfc4b293daa36ceU,
0x3dc5d8c8bceed5f5U, 0xbe9f61ed3e1aa82bU, 0x3e65ea413e630001U, 0x3e89baf4bde4afb4U,
0xbd0be6ecbeb126fbU, 0x3d0bd6d83dbeced4U, 0x3de761933d9a3ed1U, 0x3e294e3bbad97c50U,
0xbe05c319bd20de1fU, 0xbdd1da703df5f789U, 0x3d993e67bd4e56feU, 0x3ced56cbbd3733a1U,
0x3d9feb813d0e46c0U, 0xbca8ce853dfdc239U, 0xbe4d5215bdb00386U, 0x3dcd19dbbddf0b88U,
0xbdf5f82d3d1fc991U, 0x3dcae2ffbd9d668aU, 0xbc9046103e65de11U, 0xbcf125d63d8b7b55U,
0xbe0cbda13dc4d770U, 0xbdfee20f3dc428f2U, 0xbd115617be633943U, 0x3ce348d3bd8187dbU,
0x3cdfb1093d2cf439U, 0x3bb666bd3db0f6a1U, 0xbd5325bdbd18189cU, 0x3e4ac0aebcd2d473U,
0x3d89d409bdf92232U, 0x3e373a0c3e06fb6cU, 0x3de4e39bbc15ca93U, 0xbe25d990be05df88U,
0xbd55c788bc82d5f2U, 0x3e40e5e2bc4907a0U, 0xbe077438bd547c22U, 0xbda2b50cbd8c067aU,
0xbe81a6933d77efd4U, 0xbe81c22d3e53808bU, 0xbe8499853e09d5ffU, 0xbd6ac7f13b797dd1U,
0x3ce6b25d3d888c22U, 0xbedfee69be8aa250U, 0xbe05df91bcd0c431U, 0x3d2e7d11be4dca2aU,
0x3e13cdf1bd505c28U, 0xbec965c6bbb87b07U, 0xbdd637173c4f4c87U, 0x3d1f2d45bdab063fU,
0xbedcb5a7bcd77371U, 0x3d92ecdabd58207cU, 0x3c901c48ba6eef08U, 0xbe461dbbbe3b7f52U,
0x3e0e2b8bbdd058b4U, 0xbe64c9463d10f9e8U, 0xbd497c19bebcd50fU, 0x3c84e49c3df71cc5U,
0x3bf322b33d999f8cU, 0xbd4aaf353d193261U, 0xbd95b0dfbc0c2251U, 0xbd5c327a3d928520U,
0xbea0e023bc1a3500U, 0xbe89adf5be42f41eU, 0xbdb3362b3d74ef11U, 0x3d2cfe9cbea0d92bU,
0xbdf2db3e3dab8605U, 0x3ba6811bbcc5086eU, 0x3e092a283d05c64cU, 0xbdf55d56bdf6763fU,
0xbe66eb643b067814U, 0x3d31e50ebdad7182U, 0xbe7efdef3aef02b8U, 0x3d716a833d45c93cU,
0x3cc20a513da893f5U, 0xbdde5b8d3da4e439U, 0x3aeff2b33e15e18eU, 0xbeb083c53e3cd8cdU,
0x3e574378bdd9f79eU, 0xbd8361b5bda7a844U, 0xbdd7bd893e25fc28U, 0x3ca85773bd7f3944U,
0x3af9b0cc3d643a22U, 0xbd1cecebbe81ff94U, 0x3d672a58bdcd910bU, 0xbe0b7d373d93451aU,
0xbd22ec3c3dfbaecfU, 0x3d41c039be08f1b7U, 0x3e3f7e793ca8e420U, 0x3d26dfcbbdaa7b27U,
0xbd4a245dbd80d78fU, 0xbdfdff32baeb63f9U, 0x3e240a9c3e0d5cc5U, 0x3de763983d7482daU,
0x3cd5fd9d3cf6a9b8U, 0x3d04e495bdac0fd6U, 0xbd70591b3e1b2078U, 0xbb122e743df82ce0U,
0xbd5b0aef3c0beac6U, 0x3da753e8bf1e4783U, 0x3e3dfbb6bec93732U, 0xbd730862bc92cae7U,
0x3d4950543ea7040aU, 0x3d966c163db5844cU, 0xbcc53fb6bd8b7882U, 0xbd33b851bd97ca2eU,
0xbe7561a63da2d630U, 0xbe2f7bd33dfb59f0U, 0x3e0ee236bcf7fc25U, 0xbd0a48ef3c4388a4U,
0xbe7da349bd1b5bf8U, 0xbd9558cbbe3cc289U, 0x3cc7959a3d38cd8aU, 0x3e0c6347bceb3e2aU,
0xbec26efd3dbe7683U, 0x3e1f9da1bd8421b5U, 0xbdbe1288be1d3409U, 0xbf09b7a33e22c334U,
0x3e3d713ebe19c488U, 0x3cdf307bbe8260a0U, 0xbe09cf91bbb7e57fU, 0x3d6125f2bc9f9384U,
0xbe2fcd7dbdf99946U, 0xbd961ce5bf1cf918U, 0xbe1d091a3d9d2122U, 0xbd0ebafd3dc20322U,
0xbc7888febd8c5d90U, 0x3e082df9bd0ace71U, 0x3c9a8fbe3d4e2660U, 0xbeda997ebceb035bU,
0xbe39e72bbeb2e60fU, 0xbe7dfdc2bb168cabU, 0xbdedec42be85b75dU, 0x3dfae62f3db613b1U,
0xbe140d293e1dc361U, 0x3daf94a2be106145U, 0xbe1874083d121077U, 0xbe364a7ebdea154aU,
0x3ca227f6bd515c88U, 0xbea762f5bdff7933U, 0x3d8775cf3d7e825dU, 0xbdd449a43dcd30b8U,
0x3d983498bc3f4fd1U, 0x3c235c023ddddc05U, 0xbe3f9ee8be8e00cdU, 0xbe2b81e7bd98fd0bU,
0x3cbafc6fbe0127cdU, 0x3e32f3cabe21b90eU, 0x3e2235b9be01f4f1U, 0xbd2de61f3d7f2509U,
0x3c995b24be1ccc74U, 0x3d5c4be1bd729f8dU, 0xbd909bf3bcb855f1U, 0xbce71dfc3d896aa7U,
0xbd89cb143daa63a6U, 0x3e150f2abc3e879aU, 0x3d8d050d3dfd3837U, 0xbdace2003d4fa0aeU,
0x3b90968dbdcc8e93U, 0x3cb34baa3cfdb281U, 0xbc2ca5773dbf1411U, 0xbdc60afabcea4455U,
0x3d8140293ca7c25eU, 0x3e21a6e0be2824e8U, 0xbe24b83abe2289aaU, 0xbd27de0ebc33671dU,
0xbc87636c3e424aeaU, 0x3ccc4ad1bc217291U, 0xbdf6aff1bd8d9360U, 0x3c201c1f3c8037d6U,
0x3cfc06b03e0d1588U, 0x3ce99ed8bd1c6221U, 0x3c05cbed3dbba8e7U, 0xbdf6f99bbd683100U,
0x3cd96b9ebd81e124U, 0x3d5bddc93d1d87cbU, 0x3df5b4e43dc471b6U, 0x3d81009dbd753964U,
0x3e06cf39bdfbc5e9U, 0xbd6352a03d76ba0dU, 0xbda3723d3c57f7b2U, 0xbdb237bd3db0199bU,
0xbdba486fbdadf9ceU, 0xbd18a5cebcb7a182U, 0x3daa3618bcfefa3dU, 0xbe11cd4dbb485312U,
0x3d8331683d34959dU, 0xbd4f76d73dc29f76U, 0xbd7056e03c1428a4U, 0x3d794ab93e07fde5U,
0x3c83ad343d55b443U, 0x3ca8cefbbca9d29cU, 0xbdef6f55be3beaefU, 0xbd0ce11b3e32bc06U,
0xbd047c03bde191ceU, 0xbd751804bd22b9abU, 0xbd1d3cd13da0ed78U, 0x3d336c80bccf4e6eU,
0xbd4759693c26a8f8U, 0xbb8eb437bd927977U, 0xbcd6cf1a3caa3bb6U, 0x3da36f83bda51799U,
0xbb89f19b3d4cac22U, 0xbcad7417bcc03634U, 0x3a15a0273d9b589aU, 0x3e19fdc33a3cd592U,
0xbd47dea8be0964cbU, 0xbe20d956bda235dfU, 0xbd1be3cdbce8cbf6U, 0x3cb347d23d9f6034U,
0x3c85356d3d739952U, 0xbe413ee63e910473U, 0xbd9070a5bcef53beU, 0xbda4f7bbbc2aa8a6U,
0xbe1dfa5cbe671e1eU, 0x3d052d22bd84c49eU, 0x3e41d33b3dffe1e8U, 0xbe89eb283dac98baU,
0x3d85f01abd9caaa9U, 0xbbc586323d88d63eU, 0xbd5405eabd71bd11U, 0xbe0932b1bcc54aedU,
0x3d675dee3e1ac20bU, 0xbe173fc73d52be8eU, 0xbdf472e43c20de97U, 0xbc46b8b73da808a3U,
0x3caff6ea3c946ac6U, 0x3d7f5b9bbdd9ec31U, 0xbd11c39abdb216d2U, 0xbd28b4dfbe9e51e4U,
0x3dea7519bd04deb0U, 0xbdcaca083d824147U, 0x3d1eda213dee31a2U, 0xbd9b0d8cbeb696b4U,
0x3de71c9bbed2d803U, 0x3e00f1db3b4eff91U, 0x3caf95f53de69d08U, 0xbb0d1e0b3d38c496U,
0xbc95973c3b104179U, 0xbdfbc2b43c287ab7U, 0xbcc5b9923d632fb4U, 0xbdc691503d0159a2U,
0x3db72996bd3e2f50U, 0x3da5adb13ddaf449U, 0xbd8d2d4a3d67eaffU, 0xbc687798bea5de14U,
0x3bd7675b3df2cc70U, 0x3d9ff60f3daebc3eU, 0xbdc27727bcf9bf68U, 0xbc4140ed3c3db1b6U,
0xbe29cb3fbe385516U, 0xbe781b4fbe437b8fU, 0xbc8a0b6dbdaba1d9U, 0xbd26659bbe7c4941U,
0x3e11aee13d998d2cU, 0xbd25b799bd2cad7fU, 0x3e1b3ee63d5a4910U, 0x3ea03bc5be259c18U,
0xbda6427e3c684b97U, 0xbda5e5643c256ab0U, 0x3dbcf2e73db59ce6U, 0xbd65639ebd9604b6U,
0x3d5aa79c3d60b6b4U, 0xbe0f09003a75a9cfU, 0xbdf54ad73d0808edU, 0x3d0d33e2bd440ef4U,
0xbe333de63d2159deU, 0xbdace8e6bc24c19dU, 0x3dccb403bc9732baU, 0x3d0b0279be959bcaU,
0xbe1b4e003de3ab0fU, 0xbc5b5c8cbea65ed9U, 0xbcf127adbd28ad36U, 0xbd3b9a05be8d4004U,
0x3ddd5a6dba296ed9U, 0xbe4f20de3df7f3c1U, 0x3bd7db943d539b0eU, 0x3e2d468fbca5ce6fU,
0xbe16beb7bc665668U, 0x3d909225bdf7c361U, 0x3d52ebb8bdd48dc9U, 0xbdbdc412bd968dbbU,
0x3e0631c1be08f4d9U, 0x3e21f50c3dc3d8e7U, 0x3dfc26aabdd5b0d6U, 0xbe58d0e8bdec783cU,
0xbe6a276c3dc5f7fbU, 0xbc2c1b533d55337cU, 0xbd56f7923d83cb0cU, 0xbdd2722b3d9c84b9U,
0xbd7dc88d3de68ab7U, 0x3b2efec53e080dc3U, 0x3d73abdf3dcbc1f6U, 0xbc57fae33c236291U,
0x3b427d2dbd92a4d8U, 0x3d0af67b3b425d15U, 0x3c38d9d5bd2c2988U, 0xbd42b57cbe052fa4U,
0x3d9a3796bdfbc628U, 0x3d09dd3d3d26cb8fU, 0xbe51ac75be62826cU, 0xbdd2d27bbe1d2775U,
0xbe97c4b13e0566beU, 0x3d1f29973d22767eU, 0xbda137f8bcf6a5ddU, 0x3cf324a63c029be4U,
0xbe4169653da4aa0cU, 0xbd1e6c05bdb5efd7U, 0x3dd5cf5d3d622137U, 0xbe01238b3e63ab4cU,
0x3e144eb53d59cdb6U, 0xbec05968beaba06eU, 0xbf81793f3e88794eU, 0x3d6f8122be659695U,
0xbc4d97b53e9e7124U, 0xbd02ddd83c2a80dbU, 0xbe08ea6f3d4eb954U, 0x3e2085bdbdb528f8U,
0xbdc74a7fbb680ec4U, 0x3dfd5a47bddc1835U, 0x3e6c3eb03e59b081U, 0xbe2e30a83e793e13U,
0xbdb146a03e05b5dcU, 0x3e0aa8223ef5b2faU, 0xbda9f7e9bc7c3a3dU, 0x3ea96724bd82b802U,
0x3e12d1b0bc4ee3d2U, 0x3e3c754a3e5b4d74U, 0xbe93a3c43def2e3aU, 0x3ea12808be03a904U,
0xbe8e72fd3e820cddU, 0xbebe34eb3d8c8accU, 0x3b64741cbe78cafaU, 0xbe0a7624be2d7044U,
0xbd9eaaba3d8bf8d0U, 0x3e9a6b86be8a9c3fU, 0xbf04e4cb3ec92230U, 0x3ccd44cabee2cfbbU,
0xbf61cec03ec706e6U, 0x3e99080f3d0ecd38U, 0xbd00663e3ee985d1U, 0xbddfe03b3e8b81cbU,
0xbd95ab423e0d30e3U, 0xbdd57ce8bc7d1ed1U, 0xbf03a7c6bd556a31U, 0xbe6bf0823d4cb87cU,
0xbeaf1c783d6c1a3eU, 0xbd4c524bbedc5ed6U, 0xbcda4234be6051b3U, 0x3c1d8b533d8b1a22U,
0x3cdb10c7bcfa2496U, 0xbe59eee2be1ce643U, 0x3c7b65433d3ec1e1U, 0x3d8af05ebe139d4cU,
0xbe278e37bd5e9f53U, 0x3c79c4b53c8ff840U, 0x3e0cc1ddbdb4fe39U, 0x3d03b41a3dadf3e1U,
0xbe166702bde67597U, 0xbc68cf18bd01be49U, 0xbe12c49f3d954a18U, 0x3d9a3ae13ce0d45eU,
0xbdbf711bbc066ceeU, 0x3c3c2b01bca0e1acU, 0x3d5d6c4d3e18fa59U, 0xbe2a7522bb4af95cU,
0x3d86d60d3ded8448U, 0xbe8d093cbe936088U, 0xbdc97001bef316c8U, 0x3be0536f3cf31acaU,
0xbd6611b4bcabe4d8U, 0x3d8a3ac3bdd4e8efU, 0x3d916a98bf39c3b3U, 0xbe4ed724bdd568e8U,
0x3d976ff03e249e83U, 0x3e4642af3e0b4d83U, 0x3b9af70f3e3eea7bU, 0xbdaddfddbe7fc802U,
0x3d6d613b3e35f707U, 0x3db15af2bdce62fbU, 0xbb0f0e8b3de1c46bU, 0x3dc26546bdab9bf4U,
0xbe1db417be3b7700U, 0x3d1328a4bd60fd2cU, 0xbe05caf4bd7d3c0dU, 0xbe6194e03d3d2751U,
0x3d32692d3d16f607U, 0x3ce4c8dabe2d3621U, 0xbd816bbabd9da3abU, 0x3d4d9e0dbda88533U,
0xbded6e063e8dfe97U, 0x3d943dc9bd35896cU, 0xbe22c715bcfa1a12U, 0x3c97efed3e130f16U,
0xbd2e6682be0281dbU, 0x3d98398fbe0b28e4U, 0xbdf7fd3a3d6eafd3U, 0xbba6489d3d0b855dU,
0x3d7e67cebc934d7aU, 0x3c0b62573da6691eU, 0x3bef53ccbd63f2fbU, 0xbd9ccfc7bdf5e23aU,
0xbe13f9e53d58fa53U, 0x3e3a6c23be41865bU, 0xbb7322693e4220b7U, 0x3e4f5a75be7c73b5U,
0xbda00eacbd954907U, 0xbda5c866bde90f38U, 0xbcf62bd5be21fc17U, 0xbe41b4463db9e9aaU,
0xbda2cf81be0cbc9eU, 0xbdd0dae43e0af59eU, 0x3d48d90d3e30c983U, 0x3e2881a7bebac127U,
0xbd98f0953d32e2f0U, 0xbc8936b4bd88f86fU, 0xbe0c65023d07b7b1U, 0x3d090844bd327236U,
0x3da251623dfff560U, 0x3d93f0453d616e35U, 0x3daaac9fbbad3fe7U, 0xbe06453abd2b560cU,
0x3bef1e873d6b6689U, 0x3e24573b3e06f77cU, 0x3b2a70233df80d23U, 0xbd8e57c1bdb2c9aeU,
0x3d55913fbcff86d1U, 0xbd1d05403e1ad427U, 0x3c50f2b0bdb833d5U, 0x3e3e3afa3d417ec9U,
0xbd49f606bda2d407U, 0xbc8ac6b0bc7636d5U, 0x3db2233d3d7f24abU, 0xbd0d3d24bda33188U,
0x3daa18f4beaa356dU, 0x3e8b6306bea5c096U, 0x3ec3bebf3dc56781U, 0xbd92fb183eb0fa42U,
0x3ea68dc13ddf3250U, 0xbdae1709bb47547eU, 0x3e425acc3dc5fe83U, 0x3ca8c970be113386U,
0xbcc0f11bbd4d253bU, 0x3e0937653d89112dU, 0x3ded35133bf3af76U, 0x3c2729ac3df72f44U,
0xbd0e8d2abda30913U, 0xbdf503103dc10141U, 0xbe0c15e6bde4a1ebU, 0x3c1dfd81be1cad26U,
0xbd7575fabd9f4d9bU, 0x3d115d0a3e0433c1U, 0x3d13ed63be880b3fU, 0xbde8a7fdbdaf751bU,
0x3da31150bd8fd56bU, 0x3d423a92be3e7578U, 0x3d78023f3d0d8a5dU, 0x3d8e83d03e2bb3f0U,
0xbdead9243d8a0966U, 0xbd9ba0c0be8bed9cU, 0x3d9ff5c53c32265fU, 0xbd570bd73dcd515aU,
0x3c8eebdebd1db39fU, 0x3e580e2fbd32bdbaU, 0xbdb89b46bd596661U, 0x3e02abb33a2444aaU,
0x3dfeb228be6b03afU, 0xbd6f3b4c3c8b9b14U, 0xbe345464be1a3a47U, 0xbd18f9f0bc25dfc4U,
0xbd60580a3c597dd4U, 0x3da318423d29a02bU, 0xbdb3ff11bd3a5117U, 0x3da2633c3e107ff7U,
0x3e28f832bdc8c2eeU, 0x3d94728bbd85af2aU, 0x3e03fe93bddf3fcfU, 0xbb9af3d93d20374cU,
0xbd14e1733d64b039U, 0x3dd61fa5be2f1b05U, 0xbe30a6a7be3fa123U, 0xbd1e60fcbe5435b8U,
0xbe5646b83d244d73U, 0x3ce455bfbd5e1061U, 0xbd81b122bc97a366U, 0xbd87d0743d91994bU,
0xbe6ea92bbe0477e0U, 0xbe0cef8639a85412U, 0x3c1f4a933db21800U, 0x3c196978bdbe5f56U,
0x3c943fa53d90a0b9U, 0xbd476eb6bdb83503U, 0xbe09ac12bd24e40cU, 0x3cc941433dba9696U,
0x3db51bc2bcfc90bdU, 0xbd9cf596bd7f0fb0U, 0x3cd70d13be3a65a9U, 0x3de37030bcb3ad72U,
0xbe378016be92ee37U, 0xbc468b5cbd3efd99U, 0xbdb18177bde98defU, 0xbd98f120bd26ea40U,
0x3cbd8a3c3b7a7b28U, 0x3e34396e3d9635eaU, 0xbe2bdbcb3c9bb776U, 0xbd99b815bdfec8feU,
0xbd832d44bda71ac0U, 0x3dd2a1523e0a967dU, 0xbcc448b53ef7fca3U, 0x3bbed5863e70c659U,
0x3d2dea333d6a95e5U, 0xbd0497cc3e243260U, 0x3d6c2444bd9b62d0U, 0xbe0872f5bf2db1d3U,
0x3d07dc89be2af55dU, 0x3e22ee683e213ebaU, 0xbda0a10bbd57a9d7U, 0xbc0ad79bbd0c9d0cU,
0xbef4e714bd063ab9U, 0x3c29092c3d845a02U, 0x3e883964bd510b82U, 0x3dac4f80bdec6184U,
0x3c473ea2bdd15a30U, 0x3e2bbf14bd2f62b6U, 0xba86a03cbe7e2f26U, 0x3e4a3e60be0b2562U,
0xbc64744f3e1326afU, 0xbd0fa498be8f3eddU, 0xbd191495bd246b72U, 0x3cee955cbdb5a1a6U,
0x3d9fb8c33dda05abU, 0xbe0e12ae3ce7a86aU, 0xbccf23c3bd0a3fc8U, 0xbd88fb9a3eabf950U,
0xbf18d1e4bd8eaad1U, 0xbedf6474be12ce26U, 0x3c393def3bb75431U, 0x3c3b6fa5bf10f658U,
0xbe1803fbbd38f5c9U, 0xbe51fae4be6f32dcU, 0xbdeb524dbd935a27U, 0x3ebe5e95be058e7cU,
0xbe2bcb20bd4f8ee9U, 0x3cb5fbdd3e029f46U, 0x3cf62bc73dc164d6U, 0xbdd981d63e8bdfb2U,
0xbe8f20f3be219c9cU, 0xbc733f7c3cee8999U, 0x3d42bc33bd40fb36U, 0xbbe73da2be03b2beU,
0x3bf6f54bbd381945U, 0x3d4e75293e2bc83cU, 0xbcbb67cbbe0e285eU, 0x3d06b19b3dbde788U,
0xbc8bae9dbde901e2U, 0x3d42f6973c1076cdU, 0x3d55fe713e21d2fcU, 0x3dd872f73dcc0045U,
0x3c03bf033d96e1b6U, 0xbd5d5fda3e09cd33U, 0xbd9c0f18be0e4c38U, 0x3d7273583e45c388U,
0x3d35bc6d3c4003c0U, 0xbd44bcbb3d82383eU, 0x3c9c505c3c345291U, 0x3d8e49c0bd471a8bU,
0xbc75cc113cf58c59U, 0x3b9be7123bb3f862U, 0xbd71704fbdedf0fbU, 0xbdd836363d4ca44bU,
0xbe0749e2bdd555c7U, 0x3e69f8033d3cb6a3U, 0x3bb001de3d7bbbdbU, 0x3e1c5dbcbd2e6509U,
0xbd0b775e39814c63U, 0xbe94388b3e229308U, 0xbbce36d2be27b426U, 0x3d1b6ef63d9b494cU,
0x3e2b93703cd79f18U, 0x3bb4adf93e637532U, 0x3e112106bdad2fa5U, 0x3d227f613dddc27eU,
0x3d4d9f40bc282526U, 0x3d8be4a33bab8019U, 0xbce5cf173dc6e7ceU, 0xbbae3ca93e53d492U,
0xbd107b6dbd8c08a7U, 0x3b0433843c9b4fd6U, 0x3c40be293c091e4cU, 0x3dbfb5ea3e07d5b7U,
0x3ca406fa3bc9faf1U, 0x3d6f70f63db7b03cU, 0xbd40874ebdc33b6fU, 0x3d8ccbe2bdaeda93U,
0x3d5240dd3e4282d6U, 0xbd46ed483e23aa63U, 0xbc04258b3d1f3a28U, 0x3e0eb01dbe371d2cU,
0xbd0ca1b7bdea15c3U, 0xbdf3a7eabb7703e7U, 0x3dbd8a4fbb125565U, 0xbdf531ae3e3c097cU,
0xbe58eff63d8386eeU, 0x3c3e71a1bda0e915U, 0x3d3432f9bdae530cU, 0x3d044c963e4cc2b3U,
0xbe045ec63e6ef0deU, 0x3d03aaecbca30d35U, 0x3daf52e2be14ddefU, 0xbe16319fbe26b2f2U,
0xbe0bc2f23e88834bU, 0xbe0e67133d8c47a6U, 0x3e654a433df8b881U, 0xbe322b173e37d997U,
0x3e237ee53d9d77d6U, 0xbd023ff0be74dd2fU, 0xbd950271be4b716cU, 0x3cc974df3e12ed5aU,
0x3dbc096e3c92ea65U, 0xbebfe993bba58c69U, 0xbb4fc20a3df46f41U, 0xbdbd551fbdf15dd7U,
0xbe5f7b8abd36fdebU, 0x3d34664d3d4ee5b7U, 0x3df6f1eabcfe5470U, 0xbca3d1163de5595cU,
0xbe1805c0bc2c2d4fU, 0xbd8d7d95bdfb1fa9U, 0x3e2b64633e236958U, 0x3df45ebf3d8d6b65U,
0xbe146f923c488e1fU, 0x3d0ddccbbced0acaU, 0x3d7175353e008537U, 0xbe24795b3c436252U,
0x3e12dce23e2d8aacU, 0x3e04deefbe53f665U, 0x3cbf997bbe524693U, 0x3bfc2ec73c9d34faU,
0xbcbe159d3d88a890U, 0x3dda393d3e2ac2eeU, 0x3e03955f3d9c541bU, 0x3ddc27e3bc6fc2e5U,
0xbe3985203ca79c52U, 0x3d7234893d33adf0U, 0x39e02b0abe0b84e2U, 0xbdb390ebbcacb303U,
0xbe76a4f0bc9f9810U, 0x3de1529c3e0aa114U, 0xbdaf826abe55d78fU, 0xbdcf29403d143470U,
0xbd05a0d6bd3efc9eU, 0xbd3b67a93d200a70U, 0xbd2a2c623d9d9ed1U, 0x3ce56d873c0bdc9aU,
0x3d56c1713cf933f6U, 0xb9f0affebe7d10c7U, 0x3e62de903bcd56dfU, 0xbe3ed8723d72d08dU,
0x3d8feaf33e27a12dU, 0x3d93cb2abde2a792U, 0xbe5e31303d8827e2U, 0x3d2cb9cb3e8914c7U,
0xbe2bbdc53dae6228U, 0x3dda0090be1e62c8U, 0xbdf886f3be30083fU, 0x3c36471e3e0344abU,
0xbe84be323e27a4c8U, 0x3e0d2237be975008U, 0x3dc7b8043e121416U, 0x3d2a6103ba7495afU,
0xbd5cc4d8bdfc67d7U, 0xbd96a4e4bdd4d7d6U, 0x3e0097e23d8c190dU, 0xbdffa08fbd04ad52U,
0xbdc625d03dd63f24U, 0x3d1ae68dbe37c894U, 0x3c9670ff3daaa2c0U, 0x3d698e213dea96e9U,
0xbdced93d3dddf689U, 0xbe1bd1853dcb4977U, 0xbc8659e0bed64971U, 0xbe26e0e63cffc29bU,
0xbd424fd5bcb48decU, 0xbde0fdefbccd25b9U, 0xbddc25ee3c43516cU, 0x3d9359333d960541U,
0xbe3a0c033d8c4ae8U, 0xbd59fc433d81ee4fU, 0xbe48ac5d3d7571faU, 0xbdf949333cdabca6U,
0x3d988b8fbcc150d5U, 0x3e2eb91fbd0e9dd0U, 0xbda19f2dbc23b3b7U, 0xbdc80300be0e873aU,
0xbcb6002dbe08870cU, 0xbd7625f23e01dce2U, 0xbd0ae9c5bd201a88U, 0xbdbb6ac5bdb77c4cU,
0x3d80e5d2bd1116f6U, 0xbe1581e6be8d0541U, 0xbe834baabed5305dU, 0xbe0807bcbce5055cU,
0x3d9004613db08af2U, 0xbdcf015fbe2b8f47U, 0x3dbb4779bd67490bU, 0xbc5a6dc0bc8787b9U,
0xbcb091b9bd8e2141U, 0x3daec329beaa0261U, 0x3be94f083e0d3311U, 0xbdb9ded3be6dc307U,
0xbc7c357ebd3b3da0U, 0x3d98381abdeb3b5dU, 0xbe03225ebd8a6223U, 0xbe946a6ebe0c592dU,
0xbe2f7baabe46f3caU, 0x3ca3f12bbdb19822U, 0xbdfdfaccbe3ccb29U, 0xbe35ac94be63371eU,
0xbe1a50ef3dd6778bU, 0xbe78bbc9bea2af66U, 0xbe11f5bcbe1c2a4aU, 0x3e40b83cbe469526U,
0xbd696e893d91b71eU, 0x3c11ded5be685296U, 0x3dc21d483cdb44eaU, 0xbe8005c7be7738d0U,
0xbc877eb7be25336bU, 0xbace08e2bca32ec7U, 0x3c4cb4233ca51164U, 0xbcb205433c846011U,
0xbd76175dbc2ca8c5U, 0x3a5717d03e32793bU, 0x3c92d295bd0b2234U, 0x3ca304b43d2dcaccU,
0x38bfe4983b5f5c40U, 0xbca98156bcec5562U, 0xbd876db6be173fe4U, 0xbd13121cbcc72b32U,
0x3d0643e53ce69a45U, 0x3cef857ebcd022c2U, 0xbc6996763caf5e21U, 0x3d12b5b33cde9149U,
0xbde6b3d8bd4c1fbcU, 0xbdfe81bcbc230703U, 0xbb202dd7bad3de1cU, 0xba0fe092bb332caeU,
0x3c49d3a93bc61ecfU, 0xbdab5354baf6bda6U, 0x3e1521e83b94a8efU, 0x3e2f2015bd988f73U,
0x3a922ae9bbb0b932U, 0xbaf07b90bc0d722cU, 0xbaa56a1fbb4722e4U, 0x3c411d9bbe75316eU,
0xbb7d1d0ebc0b0e33U, 0xbe178cabbda2f392U, 0xbacec7bebb95b595U, 0xbadf6dd93db6b8d4U,
0x3bcac7fc3c84e54cU,
};
ai_handle g_network_weights_table[1 + 2] = {
AI_HANDLE_PTR(AI_MAGIC_MARKER),
AI_HANDLE_PTR(s_network_weights_array_u64),
AI_HANDLE_PTR(AI_MAGIC_MARKER),
};
| 121,806 |
C
| 83.353878 | 85 | 0.879645 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/register_interface.c
|
/**
******************************************************************************
* @file register_interface.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides firmware functions that implement the register access for the MCP protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include "mc_type.h"
#include "string.h"
#include "register_interface.h"
#include "mc_config.h"
#include "mcp.h"
#include "mcp_config.h"
#include "mcpa.h"
#include "mc_configuration_registers.h"
uint8_t RI_SetRegisterGlobal(uint16_t regID, uint8_t typeID, uint8_t *data, uint16_t *size, int16_t dataAvailable)
{
uint8_t retVal = MCP_CMD_OK;
switch(typeID)
{
case TYPE_DATA_8BIT:
{
switch (regID)
{
case MC_REG_STATUS:
{
retVal = MCP_ERROR_RO_REG;
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 1;
break;
}
case TYPE_DATA_16BIT:
{
switch (regID)
{
case MC_REG_BUS_VOLTAGE:
case MC_REG_HEATS_TEMP:
case MC_REG_MOTOR_POWER:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_DAC_USER1:
case MC_REG_DAC_USER2:
break;
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 2;
break;
}
case TYPE_DATA_32BIT:
{
switch (regID)
{
case MC_REG_FAULTS_FLAGS:
{
retVal = MCP_ERROR_RO_REG;
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 4;
break;
}
case TYPE_DATA_STRING:
{
const char_t *charData = (const char_t *)data;
char_t *dummy = (char_t *)data;
retVal = MCP_ERROR_RO_REG;
/* Used to compute String length stored in RXBUFF even if Reg does not exist */
/* It allows to jump to the next command in the buffer */
(void)RI_MovString(charData, dummy, size, dataAvailable);
break;
}
case TYPE_DATA_RAW:
{
uint16_t rawSize = *(uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
/* The size consumed by the structure is the structure size + 2 bytes used to store the size */
*size = rawSize + 2U;
uint8_t *rawData = data; /* rawData points to the first data (after size extraction) */
rawData++;
rawData++;
if (*size > (uint16_t)dataAvailable)
{
/* The decoded size of the raw structure can not match with transmitted buffer, error in buffer
construction */
*size = 0;
retVal = MCP_ERROR_BAD_RAW_FORMAT; /* This error stop the parsing of the CMD buffer */
}
else
{
switch (regID)
{
case MC_REG_APPLICATION_CONFIG:
case MC_REG_MOTOR_CONFIG:
case MC_REG_GLOBAL_CONFIG:
case MC_REG_FOCFW_CONFIG:
{
retVal = MCP_ERROR_RO_REG;
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
}
break;
}
default:
{
retVal = MCP_ERROR_BAD_DATA_TYPE;
*size =0; /* From this point we are not able anymore to decode the RX buffer */
break;
}
}
return (retVal);
}
uint8_t RI_SetRegisterMotor1(uint16_t regID, uint8_t typeID, uint8_t *data, uint16_t *size, int16_t dataAvailable)
{
uint8_t retVal = MCP_CMD_OK;
uint8_t motorID=0;
MCI_Handle_t *pMCIN = &Mci[motorID];
switch(typeID)
{
case TYPE_DATA_8BIT:
{
switch (regID)
{
case MC_REG_STATUS:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_CONTROL_MODE:
{
uint8_t regdata8 = *data;
if ((uint8_t)MCM_TORQUE_MODE == regdata8)
{
MCI_ExecTorqueRamp(pMCIN, MCI_GetTeref(pMCIN), 0);
}
else
{
/* Nothing to do */
}
if ((uint8_t)MCM_SPEED_MODE == regdata8)
{
MCI_ExecSpeedRamp(pMCIN, MCI_GetMecSpeedRefUnit(pMCIN), 0);
}
else
{
/* Nothing to do */
}
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 1;
break;
}
case TYPE_DATA_16BIT:
{
uint16_t regdata16 = *(uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
switch (regID)
{
case MC_REG_SPEED_KP:
{
PID_SetKP(&PIDSpeedHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_SPEED_KI:
{
PID_SetKI(&PIDSpeedHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_SPEED_KD:
{
PID_SetKD(&PIDSpeedHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_Q_KP:
{
PID_SetKP(&PIDIqHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_Q_KI:
{
PID_SetKI(&PIDIqHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_Q_KD:
{
PID_SetKD(&PIDIqHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_D_KP:
{
PID_SetKP(&PIDIdHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_D_KI:
{
PID_SetKI(&PIDIdHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_I_D_KD:
{
PID_SetKD(&PIDIdHandle_M1, (int16_t)regdata16);
break;
}
case MC_REG_BUS_VOLTAGE:
case MC_REG_HEATS_TEMP:
case MC_REG_MOTOR_POWER:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_I_A:
case MC_REG_I_B:
case MC_REG_I_ALPHA_MEAS:
case MC_REG_I_BETA_MEAS:
case MC_REG_I_Q_MEAS:
case MC_REG_I_D_MEAS:
case MC_REG_FLUXWK_BUS_MEAS:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_I_Q_REF:
{
qd_t currComp;
currComp = MCI_GetIqdref(pMCIN);
currComp.q = (int16_t)regdata16;
MCI_SetCurrentReferences(pMCIN,currComp);
break;
}
case MC_REG_I_D_REF:
{
qd_t currComp;
currComp = MCI_GetIqdref(pMCIN);
currComp.d = (int16_t)regdata16;
MCI_SetCurrentReferences(pMCIN,currComp);
break;
}
case MC_REG_V_Q:
case MC_REG_V_D:
case MC_REG_V_ALPHA:
case MC_REG_V_BETA:
case MC_REG_ENCODER_EL_ANGLE:
case MC_REG_ENCODER_SPEED:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_STOPLL_C1:
{
int16_t hC1;
int16_t hC2;
STO_PLL_GetObserverGains(&STO_PLL_M1, &hC1, &hC2);
STO_PLL_SetObserverGains(&STO_PLL_M1, (int16_t)regdata16, hC2);
break;
}
case MC_REG_STOPLL_C2:
{
int16_t hC1;
int16_t hC2;
STO_PLL_GetObserverGains(&STO_PLL_M1, &hC1, &hC2);
STO_PLL_SetObserverGains(&STO_PLL_M1, hC1, (int16_t)regdata16);
break;
}
case MC_REG_STOPLL_KI:
{
PID_SetKI (&(&STO_PLL_M1)->PIRegulator, (int16_t)regdata16);
break;
}
case MC_REG_STOPLL_KP:
{
PID_SetKP (&(&STO_PLL_M1)->PIRegulator, (int16_t)regdata16);
break;
}
case MC_REG_STOPLL_EL_ANGLE:
case MC_REG_STOPLL_ROT_SPEED:
case MC_REG_STOPLL_I_ALPHA:
case MC_REG_STOPLL_I_BETA:
case MC_REG_STOPLL_BEMF_ALPHA:
case MC_REG_STOPLL_BEMF_BETA:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_DAC_USER1:
case MC_REG_DAC_USER2:
break;
case MC_REG_SPEED_KP_DIV:
{
PID_SetKPDivisorPOW2(&PIDSpeedHandle_M1, regdata16);
break;
}
case MC_REG_SPEED_KI_DIV:
{
PID_SetKIDivisorPOW2(&PIDSpeedHandle_M1, regdata16);
break;
}
case MC_REG_SPEED_KD_DIV:
{
PID_SetKDDivisorPOW2(&PIDSpeedHandle_M1, regdata16);
break;
}
case MC_REG_I_D_KP_DIV:
{
PID_SetKPDivisorPOW2(&PIDIdHandle_M1, regdata16);
break;
}
case MC_REG_I_D_KI_DIV:
{
PID_SetKIDivisorPOW2(&PIDIdHandle_M1, regdata16);
break;
}
case MC_REG_I_D_KD_DIV:
{
PID_SetKDDivisorPOW2(&PIDIdHandle_M1, regdata16);
break;
}
case MC_REG_I_Q_KP_DIV:
{
PID_SetKPDivisorPOW2(&PIDIqHandle_M1, regdata16);
break;
}
case MC_REG_I_Q_KI_DIV:
{
PID_SetKIDivisorPOW2(&PIDIqHandle_M1, regdata16);
break;
}
case MC_REG_I_Q_KD_DIV:
{
PID_SetKDDivisorPOW2(&PIDIqHandle_M1, regdata16);
break;
}
case MC_REG_STOPLL_KI_DIV:
{
PID_SetKIDivisorPOW2 (&(&STO_PLL_M1)->PIRegulator,regdata16);
break;
}
case MC_REG_STOPLL_KP_DIV:
{
PID_SetKPDivisorPOW2 (&(&STO_PLL_M1)->PIRegulator,regdata16);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 2;
break;
}
case TYPE_DATA_32BIT:
{
uint32_t regdata32 = *(uint32_t *)data; //cstat !MISRAC2012-Rule-11.3
switch (regID)
{
case MC_REG_FAULTS_FLAGS:
case MC_REG_SPEED_MEAS:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_SPEED_REF:
{
MCI_ExecSpeedRamp(pMCIN,((((int16_t)regdata32) * ((int16_t)SPEED_UNIT)) / (int16_t)U_RPM), 0);
break;
}
case MC_REG_STOPLL_EST_BEMF:
case MC_REG_STOPLL_OBS_BEMF:
{
retVal = MCP_ERROR_RO_REG;
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 4;
break;
}
case TYPE_DATA_STRING:
{
const char_t *charData = (const char_t *)data;
char_t *dummy = (char_t *)data;
retVal = MCP_ERROR_RO_REG;
/* Used to compute String length stored in RXBUFF even if Reg does not exist */
/* It allows to jump to the next command in the buffer */
(void)RI_MovString(charData, dummy, size, dataAvailable);
break;
}
case TYPE_DATA_RAW:
{
uint16_t rawSize = *(uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
/* The size consumed by the structure is the structure size + 2 bytes used to store the size */
*size = rawSize + 2U;
uint8_t *rawData = data; /* rawData points to the first data (after size extraction) */
rawData++;
rawData++;
if (*size > (uint16_t)dataAvailable)
{
/* The decoded size of the raw structure can not match with transmitted buffer, error in buffer
construction */
*size = 0;
retVal = MCP_ERROR_BAD_RAW_FORMAT; /* This error stop the parsing of the CMD buffer */
}
else
{
switch (regID)
{
case MC_REG_APPLICATION_CONFIG:
case MC_REG_MOTOR_CONFIG:
case MC_REG_GLOBAL_CONFIG:
case MC_REG_FOCFW_CONFIG:
{
retVal = MCP_ERROR_RO_REG;
break;
}
case MC_REG_SPEED_RAMP:
{
int32_t rpm;
uint16_t duration;
rpm = *(int32_t *)rawData; //cstat !MISRAC2012-Rule-11.3
duration = *(uint16_t *)&rawData[4]; //cstat !MISRAC2012-Rule-11.3
MCI_ExecSpeedRamp(pMCIN, (int16_t)((rpm * SPEED_UNIT) / U_RPM), duration);
break;
}
case MC_REG_TORQUE_RAMP:
{
uint32_t torque;
uint16_t duration;
torque = *(uint32_t *)rawData; //cstat !MISRAC2012-Rule-11.3
duration = *(uint16_t *)&rawData[4]; //cstat !MISRAC2012-Rule-11.3
MCI_ExecTorqueRamp(pMCIN, (int16_t)torque, duration);
break;
}
case MC_REG_CURRENT_REF:
{
qd_t currComp;
currComp.q = *((int16_t *) rawData); //cstat !MISRAC2012-Rule-11.3
currComp.d = *((int16_t *) &rawData[2]); //cstat !MISRAC2012-Rule-11.3
MCI_SetCurrentReferences(pMCIN, currComp);
break;
}
case MC_REG_ASYNC_UARTA:
{
retVal = MCPA_cfgLog (&MCPA_UART_A, rawData);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
}
break;
}
default:
{
retVal = MCP_ERROR_BAD_DATA_TYPE;
*size =0; /* From this point we are not able anymore to decode the RX buffer */
break;
}
}
return (retVal);
}
uint8_t RI_GetRegisterGlobal(uint16_t regID,uint8_t typeID,uint8_t * data,uint16_t *size,int16_t freeSpace){
uint8_t retVal = MCP_CMD_OK;
switch (typeID)
{
case TYPE_DATA_8BIT:
{
if (freeSpace > 0)
{
switch (regID)
{
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 1;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_16BIT:
{
if (freeSpace >= 2)
{
switch (regID)
{
case MC_REG_DAC_USER1:
case MC_REG_DAC_USER2:
break;
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 2;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_32BIT:
{
if (freeSpace >= 4)
{
switch (regID)
{
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 4;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_STRING:
{
char_t *charData = (char_t *)data;
switch (regID)
{
case MC_REG_FW_NAME:
retVal = RI_MovString (FIRMWARE_NAME ,charData, size, freeSpace);
break;
case MC_REG_CTRL_STAGE_NAME:
{
retVal = RI_MovString (CTL_BOARD ,charData, size, freeSpace);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
*size= 0 ; /* */
break;
}
}
break;
}
case TYPE_DATA_RAW:
{
/* First 2 bytes of the answer is reserved to the size */
uint16_t *rawSize = (uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
uint8_t * rawData = data;
rawData++;
rawData++;
switch (regID)
{
case MC_REG_GLOBAL_CONFIG:
{
*rawSize = (uint16_t)sizeof(GlobalConfig_reg_t);
if (((*rawSize) + 2U) > (uint16_t)freeSpace)
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
else
{
(void)memcpy(rawData, &globalConfig_reg, sizeof(GlobalConfig_reg_t));
}
break;
}
case MC_REG_ASYNC_UARTA:
case MC_REG_ASYNC_UARTB:
case MC_REG_ASYNC_STLNK:
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
/* Size of the answer is size of the data + 2 bytes containing data size */
*size = (*rawSize) + 2U;
break;
}
default:
{
retVal = MCP_ERROR_BAD_DATA_TYPE;
break;
}
}
return (retVal);
}
uint8_t RI_GetRegisterMotor1(uint16_t regID,uint8_t typeID,uint8_t * data,uint16_t *size,int16_t freeSpace) {
uint8_t retVal = MCP_CMD_OK;
uint8_t motorID=0;
MCI_Handle_t *pMCIN = &Mci[motorID];
BusVoltageSensor_Handle_t* BusVoltageSensor= &BusVoltageSensor_M1._Super;
switch (typeID)
{
case TYPE_DATA_8BIT:
{
if (freeSpace > 0)
{
switch (regID)
{
case MC_REG_STATUS:
{
*data = (uint8_t)MCI_GetSTMState(pMCIN);
break;
}
case MC_REG_CONTROL_MODE:
{
*data = (uint8_t)MCI_GetControlMode(pMCIN);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 1;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_16BIT:
{
uint16_t *regdataU16 = (uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
int16_t *regdata16 = (int16_t *) data; //cstat !MISRAC2012-Rule-11.3
if (freeSpace >= 2)
{
switch (regID)
{
case MC_REG_SPEED_KP:
{
*regdata16 = PID_GetKP(&PIDSpeedHandle_M1);
break;
}
case MC_REG_SPEED_KI:
{
*regdata16 = PID_GetKI(&PIDSpeedHandle_M1);
break;
}
case MC_REG_SPEED_KD:
{
*regdata16 = PID_GetKD(&PIDSpeedHandle_M1);
break;
}
case MC_REG_I_Q_KP:
{
*regdata16 = PID_GetKP(&PIDIqHandle_M1);
break;
}
case MC_REG_I_Q_KI:
{
*regdata16 = PID_GetKI(&PIDIqHandle_M1);
break;
}
case MC_REG_I_Q_KD:
{
*regdata16 = PID_GetKD(&PIDIqHandle_M1);
break;
}
case MC_REG_I_D_KP:
{
*regdata16 = PID_GetKP(&PIDIdHandle_M1);
break;
}
case MC_REG_I_D_KI:
{
*regdata16 = PID_GetKI(&PIDIdHandle_M1);
break;
}
case MC_REG_I_D_KD:
{
*regdata16 = PID_GetKD(&PIDIdHandle_M1);
break;
}
case MC_REG_BUS_VOLTAGE:
{
*regdataU16 = VBS_GetAvBusVoltage_V(BusVoltageSensor);
break;
}
case MC_REG_HEATS_TEMP:
{
*regdata16 = NTC_GetAvTemp_C(&TempSensor_M1);
break;
}
case MC_REG_I_A:
{
*regdata16 = MCI_GetIab(pMCIN).a;
break;
}
case MC_REG_I_B:
{
*regdata16 = MCI_GetIab(pMCIN).b;
break;
}
case MC_REG_I_ALPHA_MEAS:
{
*regdata16 = MCI_GetIalphabeta(pMCIN).alpha;
break;
}
case MC_REG_I_BETA_MEAS:
{
*regdata16 = MCI_GetIalphabeta(pMCIN).beta;
break;
}
case MC_REG_I_Q_MEAS:
{
*regdata16 = MCI_GetIqd(pMCIN).q;
break;
}
case MC_REG_I_D_MEAS:
{
*regdata16 = MCI_GetIqd(pMCIN).d;
break;
}
case MC_REG_I_Q_REF:
{
*regdata16 = MCI_GetIqdref(pMCIN).q;
break;
}
case MC_REG_I_D_REF:
{
*regdata16 = MCI_GetIqdref(pMCIN).d;
break;
}
case MC_REG_V_Q:
{
*regdata16 = MCI_GetVqd(pMCIN).q;
break;
}
case MC_REG_V_D:
{
*regdata16 = MCI_GetVqd(pMCIN).d;
break;
}
case MC_REG_V_ALPHA:
{
*regdata16 = MCI_GetValphabeta(pMCIN).alpha;
break;
}
case MC_REG_V_BETA:
{
*regdata16 = MCI_GetValphabeta(pMCIN).beta;
break;
}
case MC_REG_ENCODER_EL_ANGLE:
{
*regdata16 = SPD_GetElAngle ((SpeednPosFdbk_Handle_t*) &ENCODER_M1); //cstat !MISRAC2012-Rule-11.3
break;
}
case MC_REG_ENCODER_SPEED:
{
*regdata16 = SPD_GetS16Speed ((SpeednPosFdbk_Handle_t*) &ENCODER_M1); //cstat !MISRAC2012-Rule-11.3
break;
}
case MC_REG_STOPLL_EL_ANGLE:
{
//cstat !MISRAC2012-Rule-11.3
*regdata16 = SPD_GetElAngle((SpeednPosFdbk_Handle_t *)&STO_PLL_M1);
break;
}
case MC_REG_STOPLL_ROT_SPEED:
{
//cstat !MISRAC2012-Rule-11.3
*regdata16 = SPD_GetS16Speed((SpeednPosFdbk_Handle_t *)&STO_PLL_M1);
break;
}
case MC_REG_STOPLL_I_ALPHA:
{
*regdata16 = STO_PLL_GetEstimatedCurrent(&STO_PLL_M1).alpha;
break;
}
case MC_REG_STOPLL_I_BETA:
{
*regdata16 = STO_PLL_GetEstimatedCurrent(&STO_PLL_M1).beta;
break;
}
case MC_REG_STOPLL_BEMF_ALPHA:
{
*regdata16 = STO_PLL_GetEstimatedBemf(&STO_PLL_M1).alpha;
break;
}
case MC_REG_STOPLL_BEMF_BETA:
{
*regdata16 = STO_PLL_GetEstimatedBemf(&STO_PLL_M1).beta;
break;
}
case MC_REG_STOPLL_C1:
{
int16_t hC1;
int16_t hC2;
STO_PLL_GetObserverGains(&STO_PLL_M1, &hC1, &hC2);
*regdata16 = hC1;
break;
}
case MC_REG_STOPLL_C2:
{
int16_t hC1;
int16_t hC2;
STO_PLL_GetObserverGains(&STO_PLL_M1, &hC1, &hC2);
*regdata16 = hC2;
break;
}
case MC_REG_STOPLL_KI:
{
*regdata16 = PID_GetKI (&(&STO_PLL_M1)->PIRegulator);
break;
}
case MC_REG_STOPLL_KP:
{
*regdata16 = PID_GetKP (&(&STO_PLL_M1)->PIRegulator);
break;
}
case MC_REG_DAC_USER1:
case MC_REG_DAC_USER2:
break;
case MC_REG_SPEED_KP_DIV:
{
*regdataU16 = (uint16_t)PID_GetKPDivisorPOW2(&PIDSpeedHandle_M1);
break;
}
case MC_REG_SPEED_KI_DIV:
{
*regdataU16 = (uint16_t)PID_GetKIDivisorPOW2(&PIDSpeedHandle_M1);
break;
}
case MC_REG_SPEED_KD_DIV:
{
*regdataU16 = PID_GetKDDivisorPOW2(&PIDSpeedHandle_M1);
break;
}
case MC_REG_I_D_KP_DIV:
{
*regdataU16 = PID_GetKPDivisorPOW2(&PIDIdHandle_M1);
break;
}
case MC_REG_I_D_KI_DIV:
{
*regdataU16 = PID_GetKIDivisorPOW2(&PIDIdHandle_M1);
break;
}
case MC_REG_I_D_KD_DIV:
{
*regdataU16 = PID_GetKDDivisorPOW2(&PIDIdHandle_M1);
break;
}
case MC_REG_I_Q_KP_DIV:
{
*regdataU16 = PID_GetKPDivisorPOW2(&PIDIqHandle_M1);
break;
}
case MC_REG_I_Q_KI_DIV:
{
*regdataU16 = PID_GetKIDivisorPOW2(&PIDIqHandle_M1);
break;
}
case MC_REG_I_Q_KD_DIV:
{
*regdataU16 = PID_GetKDDivisorPOW2(&PIDIqHandle_M1);
break;
}
case MC_REG_STOPLL_KI_DIV:
{
*regdataU16 = PID_GetKIDivisorPOW2(&(&STO_PLL_M1)->PIRegulator);
break;
}
case MC_REG_STOPLL_KP_DIV:
{
*regdataU16 = PID_GetKPDivisorPOW2(&(&STO_PLL_M1)->PIRegulator);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 2;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_32BIT:
{
uint32_t *regdataU32 = (uint32_t *)data; //cstat !MISRAC2012-Rule-11.3
int32_t *regdata32 = (int32_t *)data; //cstat !MISRAC2012-Rule-11.3
if (freeSpace >= 4)
{
switch (regID)
{
case MC_REG_FAULTS_FLAGS:
{
*regdataU32 = MCI_GetFaultState(pMCIN);
break;
}
case MC_REG_SPEED_MEAS:
{
*regdata32 = (((int32_t)MCI_GetAvrgMecSpeedUnit(pMCIN) * U_RPM) / SPEED_UNIT);
break;
}
case MC_REG_SPEED_REF:
{
*regdata32 = (((int32_t)MCI_GetMecSpeedRefUnit(pMCIN) * U_RPM) / SPEED_UNIT);
break;
}
case MC_REG_STOPLL_EST_BEMF:
{
*regdata32 = STO_PLL_GetEstimatedBemfLevel(&STO_PLL_M1);
break;
}
case MC_REG_STOPLL_OBS_BEMF:
{
*regdata32 = STO_PLL_GetObservedBemfLevel(&STO_PLL_M1);
break;
}
case MC_REG_MOTOR_POWER:
{
FloatToU32 ReadVal; //cstat !MISRAC2012-Rule-19.2
ReadVal.Float_Val = PQD_GetAvrgElMotorPowerW(pMPM[M1]);
*regdataU32 = ReadVal.U32_Val; //cstat !UNION-type-punning
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
*size = 4;
}
else
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
break;
}
case TYPE_DATA_STRING:
{
char_t *charData = (char_t *)data;
switch (regID)
{
case MC_REG_PWR_STAGE_NAME:
{
retVal = RI_MovString (PWR_BOARD_NAME[motorID], charData, size, freeSpace);
break;
}
case MC_REG_MOTOR_NAME:
{
retVal = RI_MovString (MotorConfig_reg[motorID]->name ,charData, size, freeSpace);
break;
}
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
*size= 0 ; /* */
break;
}
}
break;
}
case TYPE_DATA_RAW:
{
/* First 2 bytes of the answer is reserved to the size */
uint16_t *rawSize = (uint16_t *)data; //cstat !MISRAC2012-Rule-11.3
uint8_t * rawData = data;
rawData++;
rawData++;
switch (regID)
{
case MC_REG_APPLICATION_CONFIG:
{
*rawSize = (uint16_t)sizeof(ApplicationConfig_reg_t);
if (((*rawSize) + 2U) > (uint16_t)freeSpace)
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
else
{
ApplicationConfig_reg_t const *pApplicationConfig_reg = ApplicationConfig_reg[motorID];
(void)memcpy(rawData, (const uint8_t *)pApplicationConfig_reg, sizeof(ApplicationConfig_reg_t));
}
break;
}
case MC_REG_MOTOR_CONFIG:
{
*rawSize = (uint16_t)sizeof(MotorConfig_reg_t);
if (((*rawSize) + 2U) > (uint16_t)freeSpace)
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
else
{
MotorConfig_reg_t const *pMotorConfig_reg = MotorConfig_reg[motorID];
(void)memcpy(rawData, (const uint8_t *)pMotorConfig_reg, sizeof(MotorConfig_reg_t));
}
break;
}
case MC_REG_FOCFW_CONFIG:
{
*rawSize = (uint16_t)sizeof(FOCFwConfig_reg_t);
if (((*rawSize) + 2U) > (uint16_t)freeSpace)
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
else
{
FOCFwConfig_reg_t const *pFOCConfig_reg = FOCConfig_reg[motorID];
(void)memcpy(rawData, (const uint8_t *)pFOCConfig_reg, sizeof(FOCFwConfig_reg_t));
}
break;
}
case MC_REG_SCALE_CONFIG:
{
*rawSize = 12;
if ((*rawSize) +2U > (uint16_t)freeSpace)
{
retVal = MCP_ERROR_NO_TXSYNC_SPACE;
}
else
{
memcpy(rawData, &scaleParams_M1, sizeof(ScaleParams_t) );
}
break;
}
case MC_REG_SPEED_RAMP:
{
int32_t *rpm = (int32_t *)rawData; //cstat !MISRAC2012-Rule-11.3
uint16_t *duration = (uint16_t *)&rawData[4]; //cstat !MISRAC2012-Rule-11.3
*rpm = (((int32_t)MCI_GetLastRampFinalSpeed(pMCIN) * U_RPM) / (int32_t)SPEED_UNIT);
*duration = MCI_GetLastRampFinalDuration(pMCIN);
*rawSize = 6;
break;
}
case MC_REG_TORQUE_RAMP:
{
int16_t *torque = (int16_t *)rawData; //cstat !MISRAC2012-Rule-11.3
uint16_t *duration = (uint16_t *)&rawData[2]; //cstat !MISRAC2012-Rule-11.3
*rawSize = 4;
*torque = MCI_GetLastRampFinalTorque(pMCIN);
*duration = MCI_GetLastRampFinalDuration(pMCIN) ;
break;
}
case MC_REG_CURRENT_REF:
{
uint16_t *iqref = (uint16_t *)rawData; //cstat !MISRAC2012-Rule-11.3
uint16_t *idref = (uint16_t *)&rawData[2]; //cstat !MISRAC2012-Rule-11.3
*rawSize = 4;
*iqref = (uint16_t)MCI_GetIqdref(pMCIN).q;
*idref = (uint16_t)MCI_GetIqdref(pMCIN).d;
break;
}
case MC_REG_ASYNC_UARTA:
case MC_REG_ASYNC_UARTB:
case MC_REG_ASYNC_STLNK:
default:
{
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
/* Size of the answer is size of the data + 2 bytes containing data size */
*size = (*rawSize) + 2U;
break;
}
default:
{
retVal = MCP_ERROR_BAD_DATA_TYPE;
break;
}
}
return (retVal);
}
uint8_t RI_MovString(const char_t *srcString, char_t *destString, uint16_t *size, int16_t maxSize)
{
uint8_t retVal = MCP_CMD_OK;
const char_t *tempsrcString = srcString;
char_t *tempdestString = destString;
*size= 1U ; /* /0 is the min String size */
while ((*tempsrcString != (char_t)0) && (*size < (uint16_t)maxSize))
{
*tempdestString = *tempsrcString;
tempdestString++;
tempsrcString++;
*size = *size + 1U;
}
if (*tempsrcString != (char_t)0)
{ /* Last string char must be 0 */
retVal = MCP_ERROR_STRING_FORMAT;
}
else
{
*tempdestString = (int8_t)0;
}
return (retVal);
}
uint8_t RI_GetIDSize(uint16_t dataID)
{
uint8_t typeID = ((uint8_t)dataID) & TYPE_MASK;
uint8_t result;
switch (typeID)
{
case TYPE_DATA_8BIT:
{
result = 1;
break;
}
case TYPE_DATA_16BIT:
{
result = 2;
break;
}
case TYPE_DATA_32BIT:
{
result = 4;
break;
}
default:
{
result=0;
break;
}
}
return (result);
}
__weak uint8_t RI_GetPtrReg(uint16_t dataID, void **dataPtr)
{
uint8_t retVal = MCP_CMD_OK;
static uint16_t nullData16=0;
#ifdef NULL_PTR_CHECK_REG_INT
if (MC_NULL == dataPtr)
{
retVal = MCP_CMD_NOK;
}
else
{
#endif
MCI_Handle_t *pMCIN = &Mci[0];
uint16_t regID = dataID & REG_MASK;
uint8_t typeID = ((uint8_t)dataID) & TYPE_MASK;
switch (typeID)
{
case TYPE_DATA_16BIT:
{
switch (regID)
{
case MC_REG_I_A:
{
*dataPtr = &(pMCIN->pFOCVars->Iab.a);
break;
}
case MC_REG_I_B:
{
*dataPtr = &(pMCIN->pFOCVars->Iab.b);
break;
}
case MC_REG_I_ALPHA_MEAS:
{
*dataPtr = &(pMCIN->pFOCVars->Ialphabeta.alpha);
break;
}
case MC_REG_I_BETA_MEAS:
{
*dataPtr = &(pMCIN->pFOCVars->Ialphabeta.beta);
break;
}
case MC_REG_I_Q_MEAS:
{
*dataPtr = &(pMCIN->pFOCVars->Iqd.q);
break;
}
case MC_REG_I_D_MEAS:
{
*dataPtr = &(pMCIN->pFOCVars->Iqd.d);
break;
}
case MC_REG_I_Q_REF:
{
*dataPtr = &(pMCIN->pFOCVars->Iqdref.q);
break;
}
case MC_REG_I_D_REF:
{
*dataPtr = &(pMCIN->pFOCVars->Iqdref.d);
break;
}
case MC_REG_V_Q:
{
*dataPtr = &(pMCIN->pFOCVars->Vqd.q);
break;
}
case MC_REG_V_D:
{
*dataPtr = &(pMCIN->pFOCVars->Vqd.d);
break;
}
case MC_REG_V_ALPHA:
{
*dataPtr = &(pMCIN->pFOCVars->Valphabeta.alpha);
break;
}
case MC_REG_V_BETA:
{
*dataPtr = &(pMCIN->pFOCVars->Valphabeta.beta);
break;
}
case MC_REG_ENCODER_SPEED:
{
*dataPtr = &((&ENCODER_M1)->_Super.hAvrMecSpeedUnit);
break;
}
case MC_REG_ENCODER_EL_ANGLE:
{
*dataPtr = &((&ENCODER_M1)->_Super.hElAngle);
break;
}
case MC_REG_STOPLL_ROT_SPEED:
{
*dataPtr = &((&STO_PLL_M1)->_Super.hAvrMecSpeedUnit);
break;
}
case MC_REG_STOPLL_EL_ANGLE:
{
*dataPtr = &((&STO_PLL_M1)->_Super.hElAngle);
break;
}
#ifdef NOT_IMPLEMENTED /* Not yet implemented */
case MC_REG_STOPLL_I_ALPHA:
case MC_REG_STOPLL_I_BETA:
break;
#endif
case MC_REG_STOPLL_BEMF_ALPHA:
{
*dataPtr = &((&STO_PLL_M1)->hBemf_alfa_est);
break;
}
case MC_REG_STOPLL_BEMF_BETA:
{
*dataPtr = &((&STO_PLL_M1)->hBemf_beta_est);
break;
}
default:
{
*dataPtr = &nullData16;
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
break;
}
default:
{
*dataPtr = &nullData16;
retVal = MCP_ERROR_UNKNOWN_REG;
break;
}
}
#ifdef NULL_PTR_CHECK_REG_INT
}
#endif
return (retVal);
}
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 36,418 |
C
| 23.102581 | 114 | 0.454391 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_api.c
|
/**
******************************************************************************
* @file mc_api.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file implements the high level interface of the Motor Control SDK.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCIAPI
*/
#include "mc_interface.h"
#include "mc_api.h"
#include "mc_config.h"
#include "mcp.h"
/** @addtogroup MCSDK
* @{
*/
/**
* @defgroup CAI Application Programming Interface
* @brief Interface for Motor Control applications using the classic SDK
*
* @{
*/
/** @defgroup MCIAPI Motor Control API
*
* @brief High level Programming Interface of the Motor Control SDK
*
* This interface allows for performing basic operations on the motor(s) driven by an
* Motor Control SDK based application. With it, motors can be started and stopped, speed or
* torque ramps can be programmed and executed and information on the state of the motors can
* be retrieved, among others.
*
* This interface consists in functions that target a specific motor, indicated in their name.
* These functions aims at being the main interface used by an Application to control motors.
*
* The current Motor Control API can cope with up to 2 motors.
* @{
*/
/**
* @brief Initiates the start-up procedure for Motor 1
*
* If the state machine of Motor 1 is in #IDLE state, the command is immediately
* executed. Otherwise the command is discarded. The Application can check the
* return value to know whether the command was executed or discarded.
*
* One of the following commands must be executed before calling MC_StartMotor1()
* in order to set a torque or a speed reference:
*
* - MC_ProgramSpeedRampMotor1()
* - MC_ProgramTorqueRampMotor1()
* - MC_SetCurrentReferenceMotor1()
*
* Failing to do so results in an unpredictable behaviour.
*
* If the offsets of the current measurement circuitry offsets are not known yet,
* an offset calibration procedure is executed to measure them prior to acutally
* starting up the motor.
*
* @note The MCI_StartMotor1 command only triggers the execution of the start-up
* procedure (or eventually the offset calibration procedure) and returns
* immediately after. It is not blocking the execution of the application until
* the motor is indeed running in steady state. If the application needs to wait
* for the motor to be running in steady state, the application has to check the
* state machine of the motor and verify that the #RUN state has been reached.
* Note also that if the startup sequence fails the #RUN state may never be reached.
*
* @retval returns true if the command is successfully executed, false otherwise.
*/
__weak bool MC_StartMotor1(void)
{
return (MCI_StartMotor(pMCI[M1]));
}
/**
* @brief Initiates the stop procedure for Motor 1.
*
* If the state machine is in any state but the #ICLWAIT, #IDLE, FAULT_NOW and
* #FAULT_OVER states, the command is immediately executed. Otherwise, it is
* discarded. The Application can check the return value to know whether the
* command was executed or discarded.
*
* @note The MC_StopMotor1() command only triggers the stop motor procedure
* and then returns. It is not blocking the application until the motor is indeed
* stopped. To know if it has stopped, the application can query the motor's state
* machine and check if the #IDLE state has been reached.
*
* @retval returns true if the command is successfully executed, false otherwise.
*/
__weak bool MC_StopMotor1(void)
{
return (MCI_StopMotor(pMCI[M1]));
}
/**
* @brief Programs a speed ramp for Motor 1 for later or immediate execution.
*
* A speed ramp is a linear change from the current speed reference to the @p hFinalSpeed
* target speed in the given @p hDurationms time.
*
* Invoking the MC_ProgramSpeedRampMotor1() function programs a new speed ramp
* with the provided parameters. The programmed ramp is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the ramp is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another ramp - whether a
* speed or a torque one - or if another buffered command is programmed before the
* current one has completed, the latter replaces the former.
*
* @note A ramp cannot reverse the rotation direction if the Application is using
* sensorless motor control techniques. If the sign of the hFinalSpeed parameter
* differs from that of the current speed, the ramp will not complete and a Speed
* Feedback error (#MC_SPEED_FDBK) will occur when the rotation speed is about to
* reach 0 rpm.
*
* @param hFinalSpeed Mechanical rotor speed reference at the end of the ramp.
* Expressed in the unit defined by #SPEED_UNIT.
* @param hDurationms Duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the speed
* value.
*/
__weak void MC_ProgramSpeedRampMotor1(int16_t hFinalSpeed, uint16_t hDurationms)
{
MCI_ExecSpeedRamp(pMCI[M1], hFinalSpeed, hDurationms);
}
/**
* @brief Programs a speed ramp for Motor 1 for later or immediate execution.
*
* A speed ramp is a linear change from the current speed reference to the @p FinalSpeed
* target speed in the given @p hDurationms time.
*
* Invoking the MC_ProgramSpeedRampMotor1() function programs a new speed ramp
* with the provided parameters. The programmed ramp is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the ramp is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another ramp - whether a
* speed or a torque one - or if another buffered command is programmed before the
* current one has completed, the latter replaces the former.
*
* @note A ramp cannot reverse the rotation direction if the Application is using
* sensorless motor control techniques. If the sign of the hFinalSpeed parameter
* differs from that of the current speed, the ramp will not complete and a Speed
* Feedback error (#MC_SPEED_FDBK) will occur when the rotation speed is about to
* reach 0 rpm.
*
* @param FinalSpeed Mechanical rotor speed reference at the end of the ramp.
* Expressed in rpm.
* @param hDurationms Duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the speed
* value.
*/
__weak void MC_ProgramSpeedRampMotor1_F(float_t FinalSpeed, uint16_t hDurationms)
{
MCI_ExecSpeedRamp_F(pMCI[M1], FinalSpeed, hDurationms);
}
/**
* @brief Programs a torque ramp for Motor 1 for later or immediate execution.
*
* A torque ramp is a linear change from the current torque reference to the @p hFinalTorque
* target torque reference in the given @p hDurationms time.
*
* Invoking the MC_ProgramTorqueRampMotor1() function programs a new torque ramp
* with the provided parameters. The programmed ramp is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the ramp is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another ramp - whether a
* torque or a speed one - or if another buffered command is programmed before the
* current one has completed, the latter replaces the former.
*
* @note A ramp cannot reverse the rotation direction if the Application is using
* sensorless motor control techniques. If the sign of the hFinalTorque parameter
* differs from that of the current torque, the ramp will not complete and a Speed
* Feedback error (#MC_SPEED_FDBK) will occur when the rotation speed is about to
* reach 0 rpm.
*
* @param hFinalTorque Mechanical motor torque reference at the end of the ramp.
* This value represents actually the Iq current expressed in digit.
* @param hDurationms Duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the torque
* value.
*/
__weak void MC_ProgramTorqueRampMotor1(int16_t hFinalTorque, uint16_t hDurationms)
{
MCI_ExecTorqueRamp(pMCI[M1], hFinalTorque, hDurationms);
}
/**
* @brief Programs a torque ramp for Motor 1 for later or immediate execution.
*
* A torque ramp is a linear change from the current torque reference to the @p FinalTorque
* target torque reference in the given @p hDurationms time.
*
* Invoking the MC_ProgramTorqueRampMotor1() function programs a new torque ramp
* with the provided parameters. The programmed ramp is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the ramp is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another ramp - whether a
* torque or a speed one - or if another buffered command is programmed before the
* current one has completed, the latter replaces the former.
*
* @note A ramp cannot reverse the rotation direction if the Application is using
* sensorless motor control techniques. If the sign of the FinalTorque parameter
* differs from that of the current torque, the ramp will not complete and a Speed
* Feedback error (#MC_SPEED_FDBK) will occur when the rotation speed is about to
* reach 0 rpm.
*
* @param FinalTorque Mechanical motor torque reference at the end of the ramp.
* This value represents actually the Iq current expressed in Ampere.
* @param hDurationms Duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the torque
* value.
*/
__weak void MC_ProgramTorqueRampMotor1_F(float_t FinalTorque, uint16_t hDurationms)
{
MCI_ExecTorqueRamp_F(pMCI[M1], FinalTorque, hDurationms);
}
/**
* @brief Programs the current reference to Motor 1 for later or immediate execution.
*
* The current reference to consider is made of the $I_d$ and $I_q$ current components.
*
* Invoking the MC_SetCurrentReferenceMotor1() function programs a current reference
* with the provided parameters. The programmed reference is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the command is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another buffered command is
* programmed before the current one has completed, the latter replaces the former.
*
* @param Iqdref current reference in the Direct-Quadratic reference frame. Expressed
* in the qd_t format.
*/
__weak void MC_SetCurrentReferenceMotor1(qd_t Iqdref)
{
MCI_SetCurrentReferences(pMCI[M1], Iqdref);
}
/**
* @brief Programs the current reference to Motor 1 for later or immediate execution.
*
* The current reference to consider is made of the $I_d$ and $I_q$ current components.
*
* Invoking the MC_SetCurrentReferenceMotor1_F() function programs a current reference
* with the provided parameters. The programmed reference is executed immediately if
* Motor 1's state machine is in the #RUN states. Otherwise, the command is buffered
* and will be executed when the state machine reaches any of the aforementioned state.
*
* The Application can check the status of the command with the MC_GetCommandStateMotor1()
* to know whether the last command was executed immediately or not.
*
* Only one command can be buffered at any given time. If another buffered command is
* programmed before the current one has completed, the latter replaces the former.
*
* @param IqdRef current reference in the Direct-Quadratic reference frame. Expressed
* in the qd_f_t format.
*/
__weak void MC_SetCurrentReferenceMotor1_F(qd_f_t IqdRef)
{
MCI_SetCurrentReferences_F(pMCI[M1], IqdRef);
}
/**
* @brief Returns the status of the last buffered command for Motor 1.
*
* The status can be one of the following values:
* - #MCI_BUFFER_EMPTY: no buffered command is currently programmed.
* - #MCI_COMMAND_NOT_ALREADY_EXECUTED: A command has been buffered but the conditions for its
* execution have not occurred yet. The command is still in the buffer, pending execution.
* - #MCI_COMMAND_EXECUTED_SUCCESSFULLY: the last buffered command has been executed successfully.
* In this case calling this function resets the command state to #MCI_BUFFER_EMPTY.
* - #MCI_COMMAND_EXECUTED_UNSUCCESSFULLY: the buffered command has been executed unsuccessfully.
* In this case calling this function resets the command state to #MCI_BUFFER_EMPTY.
*/
__weak MCI_CommandState_t MC_GetCommandStateMotor1(void)
{
return (MCI_IsCommandAcknowledged(pMCI[M1]));
}
/**
* @brief Stops the execution of the on-going speed ramp for Motor 1, if any.
*
* If a speed ramp is currently being executed, it is immediately stopped, the rotation
* speed of Motor 1 is maintained to its current value and true is returned. If no speed
* ramp is on-going, nothing is done and false is returned.
*
* @deprecated This function is deprecated and should not be used anymore. It will be
* removed in a future version of the MCSDK. Use MC_StopRampMotor1() instead.
*/
__weak bool MC_StopSpeedRampMotor1(void)
{
return (MCI_StopSpeedRamp(pMCI[M1]));
}
/**
* @brief Stops the execution of the on-going ramp for Motor 1, if any.
*
* If a ramp is currently being executed, it is immediately stopped, the torque or the speed
* of Motor 1 is maintained to its current value.
*/
__weak void MC_StopRampMotor1(void)
{
MCI_StopRamp(pMCI[M1]);
}
/**
* @brief Returns true if the last ramp submited for Motor 1 has completed, false otherwise
*/
__weak bool MC_HasRampCompletedMotor1(void)
{
return (MCI_RampCompleted(pMCI[M1]));
}
/**
* @brief Returns the current mechanical rotor speed reference set for Motor 1, expressed in the unit defined by #SPEED_UNIT
*/
__weak int16_t MC_GetMecSpeedReferenceMotor1(void)
{
return (MCI_GetMecSpeedRefUnit(pMCI[M1]));
}
/**
* @brief Returns the current mechanical rotor speed reference set for Motor 1, expressed in rpm.
*/
__weak float_t MC_GetMecSpeedReferenceMotor1_F(void)
{
return (MCI_GetMecSpeedRef_F(pMCI[M1]));
}
/**
* @brief Returns the last computed average mechanical rotor speed for Motor 1, expressed in the unit defined by #SPEED_UNIT
*/
__weak int16_t MC_GetMecSpeedAverageMotor1(void)
{
return (MCI_GetAvrgMecSpeedUnit(pMCI[M1]));
}
#define S16ToRAD 10430.37835f /* 2^16/2Pi */
/**
* @brief Returns the last computed average mechanical rotor speed from auxiliary sensor for Motor 1, expressed in the unit defined by #SPEED_UNIT
*/
__weak int16_t MC_GetMecAuxiliarySpeedAverageM1(void)
{
return (SPD_GetAvrgMecSpeedUnit(&STO_PLL_M1._Super));
}
/**
* @brief Returns the last computed average mechanical rotor speed from auxiliary sensor for Motor 1, expressed in RPM
*/
__weak float_t MC_GetMecAuxiliarySpeedAvgM1_F(void)
{
int16_t returnValue;
returnValue = (SPD_GetAvrgMecSpeedUnit(&STO_PLL_M1._Super) * U_RPM) / SPEED_UNIT;
return ((float_t)returnValue);
}
/**
* @brief Returns the electrical angle of the rotor from auxiliary sensor of Motor 1, in DDP format
*/
__weak int16_t MC_GetAuxiliaryElAngledppMotor1(void)
{
return (SPD_GetElAngle(&STO_PLL_M1._Super));
}
/**
* @brief Returns the electrical angle of the rotor from auxiliary sensor of Motor 1, expressed in radians
*/
__weak float_t MC_GetAuxiliaryElAngleMotor1_F(void)
{
return (((float_t)SPD_GetElAngle(&STO_PLL_M1._Super)) / S16ToRAD);
}
/**
* @brief Returns the last computed average mechanical rotor speed for Motor 1, expressed in rpm.
*/
__weak float_t MC_GetAverageMecSpeedMotor1_F(void)
{
return (MCI_GetAvrgMecSpeed_F(pMCI[M1]));
}
/**
* @brief Returns the final speed of the last ramp programmed for Motor 1 if this ramp was a speed ramp, 0 otherwise.
*/
__weak int16_t MC_GetLastRampFinalSpeedMotor1(void)
{
return (MCI_GetLastRampFinalSpeed(pMCI[M1]));
}
/**
* @brief Returns the final speed of the last ramp programmed for Motor 1 if this ramp was a speed ramp, 0 otherwise.
*/
__weak float_t MC_GetLastRampFinalSpeedM1_F(void)
{
return (MCI_GetLastRampFinalSpeed_F(pMCI[M1]));
}
/**
* @brief Returns the Control Mode used for Motor 1 (either Speed or Torque)
*/
__weak MC_ControlMode_t MC_GetControlModeMotor1(void)
{
return (MCI_GetControlMode(pMCI[M1]));
}
/**
* @brief Returns the rotation direction imposed by the last command on Motor 1
*
* The last command is either MC_ProgramSpeedRampMotor1(), MC_ProgramTorqueRampMotor1() or
* MC_SetCurrentReferenceMotor1().
*
* The function returns -1 if the sign of the final speed, the final torque or the Iq current
* reference component of the last command is negative. Otherwise, 1 is returned.
*
* @note if no such command has ever been submitted, 1 is returned as well.
*/
__weak int16_t MC_GetImposedDirectionMotor1(void)
{
return (MCI_GetImposedMotorDirection(pMCI[M1]));
}
/**
* @brief Returns true if the speed sensor used for Motor 1 is reliable, false otherwise
*/
__weak bool MC_GetSpeedSensorReliabilityMotor1(void)
{
return (MCI_GetSpdSensorReliability(pMCI[M1]));
}
/**
* @brief returns the amplitude of the phase current injected in Motor 1
*
* The returned amplitude (0-to-peak) is expressed in s16A unit. To convert it to amperes, use the following formula:
*
* @f[
* I_{Amps} = \frac{ I_{s16A} \times V_{dd}}{ 65536 \times R_{shunt} \times A_{op} }
* @f]
*
*/
__weak int16_t MC_GetPhaseCurrentAmplitudeMotor1(void)
{
return (MCI_GetPhaseCurrentAmplitude(pMCI[M1]));
}
/**
* @brief returns the amplitude of the phase voltage applied to Motor 1
*
* The returned amplitude (0-to-peak) is expressed in s16V unit. To convert it to volts, use the following formula:
*
* @f[
* U_{Volts} = \frac{ U_{s16V} \times V_{bus}}{ \sqrt{3} \times 32768 }
* @f]
*
*/
__weak int16_t MC_GetPhaseVoltageAmplitudeMotor1(void)
{
return (MCI_GetPhaseVoltageAmplitude(pMCI[M1]));
}
/**
* @brief returns Ia and Ib current values for Motor 1 in ab_t format
*/
__weak ab_t MC_GetIabMotor1(void)
{
return (MCI_GetIab(pMCI[M1]));
}
/**
* @brief returns Ia and Ib current values for Motor 1 in ab_f_t format
*/
__weak ab_f_t MC_GetIabMotor1_F(void)
{
return (MCI_GetIab_F(pMCI[M1]));
}
/**
* @brief returns Ialpha and Ibeta current values for Motor 1 in alphabeta_t format
*/
__weak alphabeta_t MC_GetIalphabetaMotor1(void)
{
return (MCI_GetIalphabeta(pMCI[M1]));
}
/**
* @brief returns Iq and Id current values for Motor 1 in qd_t format
*/
__weak qd_t MC_GetIqdMotor1(void)
{
return (MCI_GetIqd(pMCI[M1]));
}
/**
* @brief returns Iq and Id current values for Motor 1 in float_t type
*/
__weak qd_f_t MC_GetIqdMotor1_F(void)
{
return (MCI_GetIqd_F(pMCI[M1]));
}
/**
* @brief returns Iq and Id reference current values for Motor 1 in qd_t format
*/
__weak qd_t MC_GetIqdrefMotor1(void)
{
return (MCI_GetIqdref(pMCI[M1]));
}
/**
* @brief returns Iq and Id reference current values for Motor 1 in float_t type
*/
__weak qd_f_t MC_GetIqdrefMotor1_F(void)
{
return (MCI_GetIqdref_F(pMCI[M1]));
}
/**
* @brief returns Vq and Vd voltage values for Motor 1 in qd_t format
*/
__weak qd_t MC_GetVqdMotor1(void)
{
return (MCI_GetVqd(pMCI[M1]));
}
/**
* @brief returns Valpha and Vbeta voltage values for Motor 1 in alphabeta_t format
*/
__weak alphabeta_t MC_GetValphabetaMotor1(void)
{
return (MCI_GetValphabeta(pMCI[M1]));
}
/**
* @brief returns the electrical angle of the rotor of Motor 1, in DDP format
*/
__weak int16_t MC_GetElAngledppMotor1(void)
{
return (MCI_GetElAngledpp(pMCI[M1]));
}
/**
* @brief returns the electrical torque reference for Motor 1
*/
__weak int16_t MC_GetTerefMotor1(void)
{
return (MCI_GetTeref(pMCI[M1]));
}
/**
* @brief returns the electrical torque reference for Motor 1
*/
__weak float_t MC_GetTerefMotor1_F(void)
{
return (MCI_GetTeref_F(pMCI[M1]));
}
/**
* @brief re-initializes Iq and Id references to their default values for Motor 1
*
* The default values for the Iq and Id references are coming from the Speed
* or the Torque controller depending on the control mode.
*
* @see SpeednTorqCtrl for more details.
*/
__weak void MC_Clear_IqdrefMotor1(void)
{
MCI_Clear_Iqdref(pMCI[M1]);
}
/**
* @brief Acknowledge a Motor Control fault that occured on Motor 1
*
* This function informs Motor 1's state machine that the Application has taken
* the error condition that occured into account. If no error condition exists when
* the function is called, nothing is done and false is returned. Otherwise, true is
* returned.
*/
__weak bool MC_AcknowledgeFaultMotor1(void)
{
return (MCI_FaultAcknowledged(pMCI[M1]));
}
/**
* @brief Returns a bit-field showing non acknowledged faults that occurred on Motor 1.
*
* This function returns a 16 bit fields containing the Motor Control faults
* that have occurred on Motor 1 since its state machine moved to the #FAULT_NOW state.
*
* See @ref fault_codes "Motor Control Faults" for a list of
* of all possible faults codes.
*/
__weak uint16_t MC_GetOccurredFaultsMotor1(void)
{
return (MCI_GetOccurredFaults(pMCI[M1]));
}
/**
* @brief returns a bitfield showing all current faults on Motor 1
*
* This function returns a 16 bit fields containing the Motor Control faults
* that are currently active.
*
* See @ref fault_codes "Motor Control Faults" for a list of
* of all possible faults codes.
*/
__weak uint16_t MC_GetCurrentFaultsMotor1(void)
{
return (MCI_GetCurrentFaults(pMCI[M1]));
}
/**
* @brief returns the current state of Motor 1 state machine
*/
__weak MCI_State_t MC_GetSTMStateMotor1(void)
{
return (MCI_GetSTMState(pMCI[M1]));
}
/**
* @brief Sets the polarization offset values to use for Motor 1
*
* The Motor Control algorithm relies on a number of current and voltage measures. The hardware
* parts that make these measurements need to be characterized at least once in the course of
* product life, prior to its first activation. This characterization consists in measuring the
* voltage presented to the ADC channels when either no current flows into the phases of the motor
* or no voltage is applied to them. This characterization is named polarization offsets measurement
* and its results are the polarization offsets.
*
* The Motor Control Firmware can performs this polarization offsets measurement procedure which
* results in a number of offset values that the application can store in a non volatile memory and
* then set into the Motor Control subsystem at power-on or after a reset.
*
* The application uses this function to set the polarization offset values that the Motor Control
* subsystem is to use in the current session. This function can only be used when the state machine
* of the motor is in the #IDLE state in which case it returns #MC_SUCCESS. Otherwise, it does nothing
* and returns the #MC_WRONG_STATE_ERROR error code.
*
* The Motor Control subsystem needs to know the polarization offsets before the motor can be controlled.
* The MC_SetPolarizationOffsetsMotor1() function provides a way to set these offsets. Alternatively, the
* application can either:
*
* * Execute the polarization offsets measurement procedure with a call to
* MC_StartPolarizationOffsetsMeasurementMotor1() after a reset or a power on;
* * Start the motor control with the MC_StartWithPolarizationMotor1() that will execute the procedure
* before actually starting the motor, on the first time it is called after a reset or a power on.
*
* When this function completes successfully, the state of the polarization offsets measurement procedure
* is set to #COMPLETED. See MC_GetPolarizationState().
*
* @param PolarizationOffsets an pointer on a structure containing the offset values
*/
bool MC_SetPolarizationOffsetsMotor1(PolarizationOffsets_t * PolarizationOffsets)
{
return (MCI_SetCalibratedOffsetsMotor(pMCI[M1], PolarizationOffsets));
}
/**
* @brief Returns the polarization offset values measured or set for Motor 1
*
* See MC_SetPolarizationOffsetsMotor1() for more details.
*
* If the Motor Control Firmware knows the polarization offset values, they are copied into the
* @p PolarizationOffsets structure and #MC_SUCCESS is returned. Otherwise, nothing is done and
* #MC_NO_POLARIZATION_OFFSETS_ERROR is returned.
*
* @param PolarizationOffsets an pointer on the structure into which the polarization offsets will be
* copied
* @return #MC_SUCCESS if calibration data were present and could be copied into @p PolarizationOffsets,
* #MC_NO_POLARIZATION_OFFSETS_ERROR otherwise.
*/
bool MC_GetPolarizationOffsetsMotor1(PolarizationOffsets_t * PolarizationOffsets)
{
return (MCI_GetCalibratedOffsetsMotor(pMCI[M1], PolarizationOffsets));
}
/**
* @brief Starts the polarization offsets measurement procedure.
*
* See MC_SetPolarizationOffsetsMotor1() for more details.
*
* If the Motor Control Firmware is in the #IDLE state, the procedure is started, the state machine
* of the motor switches to #OFFSET_CALIB and #MC_SUCCESS is returned. Otherwise, nothing is done
* and the #MC_WRONG_STATE_ERROR error code is returned.
*
* The polarization offsets measurement procedure is only triggered by this function and it is has not
* completed when this function returns. The application can use the MC_GetPolarizationState()
* function to query the state of the procedure.
*
* @see MC_GetPolarizationState()
*/
bool MC_StartPolarizationOffsetsMeasurementMotor1(void)
{
return (MCI_StartOffsetMeasurments(pMCI[M1]));
}
/**
* @brief This method is used to get the average measured motor power
* expressed in watt for Motor 1.
* @retval float_t The average measured motor power expressed in watt.
*/
__weak float_t MC_GetAveragePowerMotor1_F(void)
{
return (PQD_GetAvrgElMotorPowerW(pMPM[M1]));
}
/**
* @brief Not implemented MC_Profiler function.
* */ //cstat !MISRAC2012-Rule-2.7 !RED-unused-param !MISRAC2012-Rule-2.7 !MISRAC2012-Rule-8.13
__weak uint8_t MC_ProfilerCommand(uint16_t rxLength, uint8_t *rxBuffer, int16_t txSyncFreeSpace, uint16_t *txLength, uint8_t *txBuffer)
{
return (MCP_CMD_UNKNOWN);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 28,263 |
C
| 36.091863 | 146 | 0.722606 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mcp_config.c
|
/**
******************************************************************************
* @file mcp_config.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides configuration information of the MCP protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include "parameters_conversion.h"
#include "usart_aspep_driver.h"
#include "aspep.h"
#include "mcp.h"
#include "mcpa.h"
#include "mcp_config.h"
static uint8_t MCPSyncTxBuff[MCP_TX_SYNCBUFFER_SIZE] __attribute__((aligned(4))); //cstat !MISRAC2012-Rule-1.4_a
static uint8_t MCPSyncRXBuff[MCP_RX_SYNCBUFFER_SIZE] __attribute__((aligned(4))); //cstat !MISRAC2012-Rule-1.4_a
/* Asynchronous buffer dedicated to UART_A */
static uint8_t MCPAsyncBuffUARTA_A[MCP_TX_ASYNCBUFFER_SIZE_A] __attribute__((aligned(4))); //cstat !MISRAC2012-Rule-1.4_a
static uint8_t MCPAsyncBuffUARTA_B[MCP_TX_ASYNCBUFFER_SIZE_A] __attribute__((aligned(4))); //cstat !MISRAC2012-Rule-1.4_a
/* Buffer dedicated to store pointer of data to be streamed over UART_A */
static void *dataPtrTableA[MCPA_OVER_UARTA_STREAM];
static void *dataPtrTableBuffA[MCPA_OVER_UARTA_STREAM];
static uint8_t dataSizeTableA[MCPA_OVER_UARTA_STREAM];
static uint8_t dataSizeTableBuffA[MCPA_OVER_UARTA_STREAM]; /* buffered version of dataSizeTableA */
MCP_user_cb_t MCP_UserCallBack[MCP_USER_CALLBACK_MAX];
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MCP
* @{
*/
static UASPEP_Handle_t UASPEP_A =
{
.USARTx = USARTA,
.rxDMA = DMA_RX_A,
.txDMA = DMA_TX_A,
.rxChannel = DMACH_RX_A,
.txChannel = DMACH_TX_A,
};
ASPEP_Handle_t aspepOverUartA =
{
._Super =
{
.fGetBuffer = &ASPEP_getBuffer,
.fSendPacket = &ASPEP_sendPacket,
.fRXPacketProcess = &ASPEP_RXframeProcess,
},
.HWIp = &UASPEP_A,
.Capabilities =
{
.DATA_CRC = 0U,
.RX_maxSize = (MCP_RX_SYNC_PAYLOAD_MAX >> 5U) - 1U,
.TXS_maxSize = (MCP_TX_SYNC_PAYLOAD_MAX >> 5U) - 1U,
.TXA_maxSize = (MCP_TX_ASYNC_PAYLOAD_MAX_A >> 6U),
.version = 0x0U,
},
.syncBuffer =
{
.buffer = MCPSyncTxBuff,
},
.asyncBufferA =
{
.buffer = MCPAsyncBuffUARTA_A,
},
.asyncBufferB =
{
.buffer = MCPAsyncBuffUARTA_B,
},
.rxBuffer = MCPSyncRXBuff,
.fASPEP_HWInit = &UASPEP_INIT,
.fASPEP_HWSync = &UASPEP_IDLE_ENABLE,
.fASPEP_receive = &UASPEP_RECEIVE_BUFFER,
.fASPEP_send = &UASPEP_SEND_PACKET,
.liid = 0,
};
MCP_Handle_t MCP_Over_UartA =
{
.pTransportLayer = (MCTL_Handle_t *)&aspepOverUartA, //cstat !MISRAC2012-Rule-11.3
};
MCPA_Handle_t MCPA_UART_A =
{
.pTransportLayer = (MCTL_Handle_t *) &aspepOverUartA, //cstat !MISRAC2012-Rule-11.3
.dataPtrTable = dataPtrTableA,
.dataPtrTableBuff = dataPtrTableBuffA,
.dataSizeTable = dataSizeTableA,
.dataSizeTableBuff = dataSizeTableBuffA,
.nbrOfDataLog = MCPA_OVER_UARTA_STREAM,
};
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 3,465 |
C
| 27.409836 | 121 | 0.618182 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Src/mc_interface.c
|
/**
******************************************************************************
* @file mc_interface.c
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides firmware functions that implement the features
* of the MC Interface component of the Motor Control SDK:
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCInterface
*/
/* Includes ------------------------------------------------------------------*/
#include "mc_math.h"
#include "speed_torq_ctrl.h"
#include "mc_interface.h"
#include "motorcontrol.h"
#define ROUNDING_OFF
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup CAI
* @{
*/
/** @defgroup MCInterface Motor Control Interface
* @brief MC Interface component of the Motor Control SDK
*
* This interface allows for performing basic operations on the motor driven by a
* Motor Control SDK based application. With it, motors can be started and stopped, speed or
* torque ramps can be programmed and executed and information on the state of the motor can
* be retrieved, among others.
*
* These functions aims at being the main interface used by an application to control the motor.
*
* @{
*/
/* Private macros ------------------------------------------------------------*/
#define round(x) ((x)>=0?(int32_t)((x)+0.5):(int32_t)((x)-0.5))
/* Functions -----------------------------------------------*/
/**
* @brief Initializes all the object variables, usually it has to be called
* once right after object creation. It is also used to assign the
* state machine object, the speed and torque controller, and the FOC
* drive object to be used by MC Interface.
* @param pHandle pointer on the component instance to initialize.
* @param pSTC the speed and torque controller used by the MCI.
* @param pFOCVars pointer to FOC vars to be used by MCI.
* @param pPosCtrl pointer to the position controller to be used by the MCI
* (only present if position control is enabled)
* @param pPWMHandle pointer to the PWM & current feedback component to be used by the MCI.
*/
__weak void MCI_Init(MCI_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, pFOCVars_t pFOCVars,
PWMC_Handle_t *pPWMHandle )
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
pHandle->pSTC = pSTC;
pHandle->pFOCVars = pFOCVars;
pHandle->pPWM = pPWMHandle;
/* Buffer related initialization */
pHandle->lastCommand = MCI_NOCOMMANDSYET;
pHandle->hFinalSpeed = 0;
pHandle->hFinalTorque = 0;
pHandle->hDurationms = 0;
pHandle->CommandState = MCI_BUFFER_EMPTY;
pHandle->DirectCommand = MCI_NO_COMMAND;
pHandle->State = IDLE;
pHandle->CurrentFaults = MC_NO_FAULTS;
pHandle->PastFaults = MC_NO_FAULTS;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Programs a motor speed ramp
*
* @param pHandle Pointer on the component instance to operate on.
* @param hFinalSpeed The value of mechanical rotor speed reference at the
* end of the ramp expressed in the unit defined by #SPEED_UNIT.
* @param hDurationms The duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the
* value.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
*
* @sa MCI_ExecSpeedRamp_F
*/
__weak void MCI_ExecSpeedRamp(MCI_Handle_t *pHandle, int16_t hFinalSpeed, uint16_t hDurationms)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
pHandle->lastCommand = MCI_CMD_EXECSPEEDRAMP;
pHandle->hFinalSpeed = hFinalSpeed;
pHandle->hDurationms = hDurationms;
pHandle->CommandState = MCI_COMMAND_NOT_ALREADY_EXECUTED;
pHandle->LastModalitySetByUser = MCM_SPEED_MODE;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Programs a motor speed ramp
*
* @param pHandle Pointer on the component instance to operate on.
* @param FinalSpeed is the value of mechanical rotor speed reference at the
* end of the ramp expressed in RPM.
* @param hDurationms the duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the
* value.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
*
* @sa MCI_ExecSpeedRamp
*/
__weak void MCI_ExecSpeedRamp_F(MCI_Handle_t *pHandle, const float_t FinalSpeed, uint16_t hDurationms)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
int16_t hFinalSpeed = (((int16_t)FinalSpeed * (int16_t)SPEED_UNIT) / (int16_t)U_RPM);
MCI_ExecSpeedRamp(pHandle, hFinalSpeed, hDurationms);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Programs a motor torque ramp
*
* @param pHandle Pointer on the component instance to work on.
* @param hFinalTorque is the value of motor torque reference at the end of
* the ramp. This value represents actually the $I_q$ current expressed in
* digit.
* To convert current expressed in Amps to current expressed in digit
* is possible to use the formula:
* Current (digit) = [Current(Amp) * 65536 * Rshunt * Aop] / Vdd micro.
* @param hDurationms the duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the
* value.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
*
* @sa MCI_ExecTorqueRamp_F
*/
__weak void MCI_ExecTorqueRamp(MCI_Handle_t *pHandle, int16_t hFinalTorque, uint16_t hDurationms)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
pHandle->lastCommand = MCI_CMD_EXECTORQUERAMP;
pHandle->hFinalTorque = hFinalTorque;
pHandle->hDurationms = hDurationms;
pHandle->CommandState = MCI_COMMAND_NOT_ALREADY_EXECUTED;
pHandle->LastModalitySetByUser = MCM_TORQUE_MODE;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Programs a motor torque ramp
*
* @param pHandle Pointer on the component instance to work on.
* @param FinalTorque is the value of motor torque reference at the end of
* the ramp. This value represents actually the $I_q$ current expressed in
* Ampere.
* Here the formula for conversion from current in Ampere to digit:
* I(s16) = [i(Amp) * 65536 * Rshunt * Aop] / Vdd_micro.
* @param hDurationms the duration of the ramp expressed in milliseconds. It
* is possible to set 0 to perform an instantaneous change in the
* value.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
*
* @sa MCI_ExecTorqueRamp
*/
__weak void MCI_ExecTorqueRamp_F(MCI_Handle_t *pHandle, const float_t FinalTorque, uint16_t hDurationms)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
int16_t hFinalTorque = (int16_t)(FinalTorque * (int16_t)CURRENT_CONV_FACTOR);
MCI_ExecTorqueRamp(pHandle, hFinalTorque, hDurationms);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Sets the motor current references $I_q$ and $I_d$ directly.
*
* @param pHandle Pointer on the component instance to work on.
* @param Iqdref current references on qd reference frame in qd_t format.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
@sa MCI_SetCurrentReferences_F
*/
__weak void MCI_SetCurrentReferences(MCI_Handle_t *pHandle, qd_t Iqdref)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
pHandle->lastCommand = MCI_CMD_SETCURRENTREFERENCES;
pHandle->Iqdref.q = Iqdref.q;
pHandle->Iqdref.d = Iqdref.d;
pHandle->CommandState = MCI_COMMAND_NOT_ALREADY_EXECUTED;
pHandle->LastModalitySetByUser = MCM_TORQUE_MODE;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Sets the motor current references $I_q$ and $I_d$ directly.
*
* @param pHandle Pointer on the component instance to work on.
* @param IqdRef current (A) references on qd reference frame in qd_f_t format.
*
* This command is executed immediately if the target motor's state machine is in
* the #RUN state. Otherwise, it is buffered and its execution is delayed until This
* state is reached.
*
* Users can check the status of the command by calling the MCI_IsCommandAcknowledged()
* function.
@sa MCI_SetCurrentReferences
*/
__weak void MCI_SetCurrentReferences_F(MCI_Handle_t *pHandle, qd_f_t IqdRef)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
qd_t iqDrefTemp;
iqDrefTemp.d = (int16_t)((int16_t)IqdRef.d * (int16_t)CURRENT_CONV_FACTOR);
iqDrefTemp.q = (int16_t)((int16_t)IqdRef.q * (int16_t)CURRENT_CONV_FACTOR);
MCI_SetCurrentReferences(pHandle, iqDrefTemp);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Initiates a motor startup procedure
*
* @param pHandle Handle on the target motor interface structure
* @retval Returns true if the command is successfully executed;
* returns false otherwise
*
* If the state machine of target the motor is in #IDLE state the command is
* executed instantaneously otherwise it is discarded. Users can check
* the return value of the function to get its status. The state of the motor
* can be queried with the MCI_GetSTMState() function.
*
* Before calling MCI_StartMotor() it is mandatory to execute one of the
* following commands, in order to set a torque or a speed reference
* otherwise the behavior of the motor when it reaches the #RUN state will
* be unpredictable:
* - MCI_ExecSpeedRamp
* - MCI_ExecTorqueRamp
* - MCI_SetCurrentReferences
*
* If the offsets of the current measurement circuitry offsets are not known yet,
* an offset calibration procedure is executed to measure them prior to acutally
* starting up the motor.
*
* @note The MCI_StartMotor command only triggers the execution of the start-up
* procedure (or eventually the offset calibration procedure) and returns
* immediately after. It is not blocking the execution of the application until
* the motor is indeed running in steady state. If the application needs to wait
* for the motor to be running in steady state, the application has to check the
* state machine of the motor and verify that the #RUN state has been reached.
* Note also that if the startup sequence fails the #RUN state may never be reached.
*/
__weak bool MCI_StartMotor(MCI_Handle_t *pHandle)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ((IDLE == MCI_GetSTMState(pHandle)) &&
(MC_NO_FAULTS == MCI_GetOccurredFaults(pHandle)) &&
(MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)))
{
pHandle->DirectCommand = MCI_START;
pHandle->CommandState = MCI_COMMAND_NOT_ALREADY_EXECUTED;
retVal = true;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief Initiates a motor startup procedure preceded by an offset
* calibration procedure
*
* @param pHandle Handle on the target motor interface structure
* @retval Returns true if the command is successfully executed;
* returns false otherwise
*
* If the state machine of target the motor is in #IDLE state the command is
* executed instantaneously otherwise it is discarded. Users can check
* the return value of the function to get its status. The state of the motor
* can be queried with the MCI_GetSTMState() function.
*
* Before calling MCI_StartMotor() it is mandatory to execute one of the
* following commands, in order to set a torque or a speed reference
* otherwise the behavior of the motor when it reaches the #RUN state will
* be unpredictable:
* - MCI_ExecSpeedRamp
* - MCI_ExecTorqueRamp
* - MCI_SetCurrentReferences
*
* Whether the current measurement circuitry offsets are known or not, an
* offset calibration procedure is executed to (re)measure them. Once it has
* completed, the start up procedure of the motor is executed.
*
* @note The MCI_StartMotor command only triggers the execution of the start-up
* procedure (or eventually the offset calibration procedure) and returns
* immediately after. It is not blocking the execution of the application until
* the motor is indeed running in steady state. If the application needs to wait
* for the motor to be running in steady state, the application has to check the
* state machine of the motor and verify that the #RUN state has been reached.
* Note also that if the startup sequence fails the #RUN state may never be reached.
*/
__weak bool MCI_StartWithPolarizationMotor(MCI_Handle_t* pHandle)
{
bool retVal = true;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ((IDLE == MCI_GetSTMState(pHandle)) &&
(MC_NO_FAULTS == MCI_GetOccurredFaults(pHandle)) &&
(MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)))
{
pHandle->DirectCommand = MCI_START;
pHandle->CommandState = MCI_COMMAND_NOT_ALREADY_EXECUTED;
pHandle->pPWM->offsetCalibStatus = false;
retVal = false;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief This is a user command used to begin the phase offset calibration
* procedure. If the state machine is in IDLE state the command is executed
* instantaneously otherwise the command is discarded. User must take
* care of this possibility by checking the return value.\n
* <B>Note:</B> The MCI_StartOffsetMeasurments command is used to begin phase
* offset calibration procedure moving the state machine from IDLE state to
* OFFSET_CALIB. The command MCI_StartOffsetMeasurments is not blocking
* the execution of project until the measurments are done; to do this, the user
* have to check the state machine and verify that the IDLE state (or
* any other state) has been reached.
* @param pHandle Pointer on the component instance to work on.
* @retval bool It returns true if the command is successfully executed
* otherwise it return false.
*/
__weak bool MCI_StartOffsetMeasurments(MCI_Handle_t *pHandle)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ((IDLE == MCI_GetSTMState(pHandle)) &&
(MC_NO_FAULTS == MCI_GetOccurredFaults(pHandle)) &&
(MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)))
{
pHandle->DirectCommand = MCI_MEASURE_OFFSETS;
pHandle->pPWM->offsetCalibStatus = false;
retVal = true;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief Gets the phase current measurement offset values
*
* The offset values are written in the PolarizationOffsets structure provided that they
* have been previously provided for the Motor Control subsystem or measured by it.
*
* If the offset have not previously been provided to the Motor Control subsystem or
* if it has not measured them the function returns false and nothing is written in the
* PolarizationOffsets structure.
*
* @param pHandle Pointer on the component instance to work on.
* @param PolarizationOffsets Pointer on ploarization offset structure in which offsets will be written
* @retval returns true if the command is successfully executed; returns false otherwise.
*/
__weak bool MCI_GetCalibratedOffsetsMotor(MCI_Handle_t *pHandle, PolarizationOffsets_t *PolarizationOffsets)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if (pHandle->pPWM->offsetCalibStatus == true)
{
PWMC_GetOffsetCalib(pHandle->pPWM, PolarizationOffsets);
retVal = true;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return(retVal);
}
/**
* @brief Sets the phase current measurement offset values
*
* If the state machine is in IDLE state the command is executed
* instantaneously otherwise the command is discarded. User must take
* care of this possibility by checking the return value.
*
* @note The MCI_SetCalibratedOffsetsMotor command is used to set the phase
* offset values . The command MCI_SetCalibratedOffsetsMotor is not blocking
* the execution of project until the measurments are done; to do this, the user
* have to check the state machine and verify that the IDLE state (or
* any other state) has been reached.
*
* @param pHandle Pointer on the component instance to work on.
* @param PolarizationOffsets Pointer on ploarization offset structure that contains phase A,
* and C values.
* @retval Returns true if the command is successfully executed
* otherwise it return false.
*/
__weak bool MCI_SetCalibratedOffsetsMotor(MCI_Handle_t *pHandle, PolarizationOffsets_t *PolarizationOffsets)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ((IDLE == MCI_GetSTMState(pHandle)) &&
(MC_NO_FAULTS == MCI_GetOccurredFaults(pHandle)) &&
(MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)))
{
PWMC_SetOffsetCalib(pHandle->pPWM, PolarizationOffsets);
pHandle->pPWM->offsetCalibStatus = true;
retVal = true;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return(retVal);
}
/**
* @brief Initiates the stop procedure for a motor
*
* If the state machine is in any state but the #ICLWAIT, #IDLE, #FAULT_NOW and
* #FAULT_OVER states, the command is immediately executed. Otherwise, it is
* discarded. The Application can check the return value to know whether the
* command was executed or discarded.
*
* @note The MCI_StopMotor() command only triggers the stop motor procedure
* and then returns. It is not blocking the application until the motor is indeed
* stopped. To know if it has stopped, the application can query the motor's state
* machine and check if the #IDLE state has been reached.
*
* @param pHandle Pointer on the component instance to work on.
* @retval returns true if the command is successfully executed, false otherwise.
*/
__weak bool MCI_StopMotor(MCI_Handle_t *pHandle)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
bool status;
MCI_State_t State;
State = MCI_GetSTMState(pHandle);
if ((IDLE == State) || (ICLWAIT == State))
{
status = false;
}
else
{
status = true;
}
if ((MC_NO_FAULTS == MCI_GetOccurredFaults(pHandle)) &&
(MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)) &&
(status == true))
{
pHandle->DirectCommand = MCI_STOP;
retVal = true;
}
else
{
/* Reject the command as the condition are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief Acknowledges Motor Control faults that occurred on the target motor 1.
*
* This function must be called before the motor can be started again when a fault
* condition has occured. It clears the faults status and resets the state machine
* of the target motor to the #IDLE state provided that there is no active fault
* condition anymore.
*
* If the state machine of the target motor is in the #FAULT_OVER state, the function
* clears the list of past faults, transitions to the #IDLE state and returns true.
* Otherwise, it oes nothing and returns false.
*
* @param pHandle Pointer on the target motor drive structure.
*/
__weak bool MCI_FaultAcknowledged(MCI_Handle_t *pHandle)
{
bool reVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ((FAULT_OVER == MCI_GetSTMState(pHandle)) && (MC_NO_FAULTS == MCI_GetCurrentFaults(pHandle)))
{
pHandle->PastFaults = MC_NO_FAULTS;
pHandle->DirectCommand = MCI_ACK_FAULTS;
reVal = true;
}
else
{
/* Reject the command as the conditions are not met */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (reVal);
}
/**
* @brief It clocks both HW and SW faults processing and update the state
* machine accordingly with hSetErrors, hResetErrors and present state.
* Refer to State_t description for more information about fault states.
* @param pHandle pointer of type STM_Handle_t
* @param hSetErrors Bit field reporting faults currently present
* @param hResetErrors Bit field reporting faults to be cleared
*/
__weak void MCI_FaultProcessing(MCI_Handle_t *pHandle, uint16_t hSetErrors, uint16_t hResetErrors)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
/* Set current errors */
pHandle->CurrentFaults = (pHandle->CurrentFaults | hSetErrors ) & (~hResetErrors);
pHandle->PastFaults |= hSetErrors;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief This is usually a method managed by task. It must be called
* periodically in order to check the status of the related pSTM object
* and eventually to execute the buffered command if the condition
* occurs.
* @param pHandle Pointer on the component instance to work on.
*/
__weak void MCI_ExecBufferedCommands(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if ( pHandle->CommandState == MCI_COMMAND_NOT_ALREADY_EXECUTED )
{
bool commandHasBeenExecuted = false;
switch (pHandle->lastCommand)
{
case MCI_CMD_EXECSPEEDRAMP:
{
pHandle->pFOCVars->bDriveInput = INTERNAL;
STC_SetControlMode(pHandle->pSTC, MCM_SPEED_MODE);
commandHasBeenExecuted = STC_ExecRamp(pHandle->pSTC, pHandle->hFinalSpeed, pHandle->hDurationms);
break;
}
case MCI_CMD_EXECTORQUERAMP:
{
pHandle->pFOCVars->bDriveInput = INTERNAL;
STC_SetControlMode(pHandle->pSTC, MCM_TORQUE_MODE);
commandHasBeenExecuted = STC_ExecRamp(pHandle->pSTC, pHandle->hFinalTorque, pHandle->hDurationms);
break;
}
case MCI_CMD_SETCURRENTREFERENCES:
{
pHandle->pFOCVars->bDriveInput = EXTERNAL;
pHandle->pFOCVars->Iqdref = pHandle->Iqdref;
commandHasBeenExecuted = true;
break;
}
default:
break;
}
if (commandHasBeenExecuted)
{
pHandle->CommandState = MCI_COMMAND_EXECUTED_SUCCESSFULLY;
}
else
{
pHandle->CommandState = MCI_COMMAND_EXECUTED_UNSUCCESSFULLY;
}
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief Returns information about the state of the last buffered command.
* @param pHandle Pointer on the component instance to work on.
* @retval The state of the last buffered command
*
* The state returned by this function can be one of the following codes:
* - #MCI_BUFFER_EMPTY if no buffered command has been called.
* - #MCI_COMMAND_NOT_ALREADY_EXECUTED if the buffered command
* condition has not already occurred.
* - #MCI_COMMAND_EXECUTED_SUCCESSFULLY if the buffered command has
* been executed successfully. In this case calling this function resets
* the command state to #MCI_BUFFER_EMPTY.
* - #MCI_COMMAND_EXECUTED_UNSUCCESSFULLY if the buffered command has
* been executed unsuccessfully. In this case calling this function
* resets the command state to #MCI_BUFFER_EMPTY.
*/
__weak MCI_CommandState_t MCI_IsCommandAcknowledged(MCI_Handle_t *pHandle)
{
MCI_CommandState_t retVal;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
retVal = MCI_COMMAND_EXECUTED_UNSUCCESSFULLY;
}
else
{
#endif
retVal = pHandle->CommandState;
if ((MCI_COMMAND_EXECUTED_SUCCESSFULLY == retVal) || (MCI_COMMAND_EXECUTED_UNSUCCESSFULLY == retVal) )
{
pHandle->CommandState = MCI_BUFFER_EMPTY;
}
else
{
/* Nothing to do */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief It returns information about the state of the related pSTM object.
* @param pHandle Pointer on the component instance to work on.
* @retval State_t It returns the current state of the related pSTM object.
*/
__weak MCI_State_t MCI_GetSTMState(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? FAULT_NOW : pHandle->State);
#else
return (pHandle->State);
#endif
}
/**
* @brief Returns the list of non-acknowledged faults that occured on the target motor
*
* This function returns a bitfield indicating the faults that occured since the state machine
* of the target motor has been moved into the #FAULT_NOW state.
*
* Possible error codes are listed in the @ref fault_codes "Fault codes" section.
*
* @param pHandle Pointer on the target motor drive structure.
* @retval uint16_t 16 bit fields with information about the faults
* historically occurred since the state machine has been moved into
*/
__weak uint16_t MCI_GetOccurredFaults(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? MC_SW_ERROR : (uint16_t)pHandle->PastFaults);
#else
return ((uint16_t)pHandle->PastFaults);
#endif
}
/**
* @brief Returns the list of faults that are currently active on the target motor
*
* This function returns a bitfield that indicates faults that occured on the Motor
* Control subsystem for the target motor and that are still active (the conditions
* that triggered the faults returned are still true).
*
* Possible error codes are listed in the @ref fault_codes "Fault codes" section.
*
* @param pHandle Pointer on the target motor drive structure.
*/
__weak uint16_t MCI_GetCurrentFaults(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? MC_SW_ERROR : (uint16_t)pHandle->CurrentFaults);
#else
return ((uint16_t)pHandle->CurrentFaults);
#endif
}
/**
* @brief Returns the lists of current and past faults that occurred on the target motor
*
* This function returns two bitfields containing information about the faults currently
* present and the faults occurred since the state machine has been moved into the #FAULT_NOW
* state.
*
* These two bitfields are 16 bits wide each and are concatenated into the 32-bit data. The
* 16 most significant bits contains the status of the current faults while that of the
* past faults is in the 16 least significant bits.
*
* @sa MCI_GetOccurredFaults, MCI_GetCurrentFaults
*
* @param pHandle Pointer on the target motor drive structure.
*/
__weak uint32_t MCI_GetFaultState(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
uint32_t LocalFaultState;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
LocalFaultState = MC_SW_ERROR | (MC_SW_ERROR << 16);
}
else
{
#endif
LocalFaultState = (uint32_t)(pHandle->PastFaults);
LocalFaultState |= (uint32_t)(pHandle->CurrentFaults) << 16;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (LocalFaultState);
}
/**
* @brief It returns the modality of the speed and torque controller.
* @param pHandle Pointer on the component instance to work on.
* @retval MC_ControlMode_t It returns the modality of STC. It can be one of
* these two values: MCM_TORQUE_MODE or MCM_SPEED_MODE.
*/
__weak MC_ControlMode_t MCI_GetControlMode(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? MCM_TORQUE_MODE : pHandle->LastModalitySetByUser);
#else
return (pHandle->LastModalitySetByUser);
#endif
}
/**
* @brief It returns the motor direction imposed by the last command
* (MCI_ExecSpeedRamp, MCI_ExecTorqueRamp or MCI_SetCurrentReferences).
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t It returns 1 or -1 according the sign of hFinalSpeed,
* hFinalTorque or Iqdref.q of the last command.
*/
__weak int16_t MCI_GetImposedMotorDirection(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
int16_t retVal = 1;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
switch (pHandle->lastCommand)
{
case MCI_CMD_EXECSPEEDRAMP:
{
if (pHandle->hFinalSpeed < 0)
{
retVal = -1;
}
else
{
/* Nothing to do */
}
break;
}
case MCI_CMD_EXECTORQUERAMP:
{
if (pHandle->hFinalTorque < 0)
{
retVal = -1;
}
else
{
/* Nothing to do */
}
break;
}
case MCI_CMD_SETCURRENTREFERENCES:
{
if (pHandle->Iqdref.q < 0)
{
retVal = -1;
}
else
{
/* Nothing to do */
}
break;
}
default:
break;
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief It returns information about the last ramp final speed sent by the
* user expressed in the unit defined by #SPEED_UNIT.
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t last ramp final speed sent by the user expressed in
* the unit defined by #SPEED_UNIT.
*/
__weak int16_t MCI_GetLastRampFinalSpeed(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
int16_t retVal = 0;
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
retVal = pHandle->hFinalSpeed;
}
return (retVal);
#else
return (pHandle->hFinalSpeed);
#endif
}
/**
* @brief It returns information about the last ramp final torque sent by the
* user .This value represents actually the Iq current expressed in
* digit.
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t last ramp final torque sent by the user expressed in digit
*/
__weak int16_t MCI_GetLastRampFinalTorque(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
int16_t retVal = 0;
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
retVal = pHandle->hFinalTorque;
}
return (retVal);
#else
return (pHandle->hFinalTorque);
#endif
}
/**
* @brief It returns information about the last ramp Duration sent by the
* user .
* @param pHandle Pointer on the component instance to work on.
* @retval uint16_t last ramp final torque sent by the user expressed in digit
*/
__weak uint16_t MCI_GetLastRampFinalDuration(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
uint16_t retVal = 0;
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
retVal = pHandle->hDurationms;
}
return (retVal);
#else
return (pHandle->hDurationms);
#endif
}
/**
* @brief It returns last ramp final speed expressed in rpm.
* @param pHandle Pointer on the component instance to work on.
* @retval float_t last ramp final speed sent by the user expressed in rpm.
*/
__weak float_t MCI_GetLastRampFinalSpeed_F(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
float_t reVal = 0.0f;
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
reVal = (((float_t)pHandle->hFinalSpeed * (float_t)U_RPM) / (float_t)SPEED_UNIT);
}
return (reVal);
}
/**
* @brief Check if the settled speed or torque ramp has been completed.
* @param pHandle Pointer on the component instance to work on.
* @retval bool It returns true if the ramp is completed, false otherwise.
*/
__weak bool MCI_RampCompleted(MCI_Handle_t *pHandle)
{
bool retVal = false;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
if (RUN == MCI_GetSTMState(pHandle))
{
retVal = STC_RampCompleted(pHandle->pSTC);
}
else
{
/* Nothing to do */
}
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (retVal);
}
/**
* @brief Stop the execution of speed ramp.
* @param pHandle Pointer on the component instance to work on.
* @retval bool It returns true if the command is executed, false otherwise.
*
* @deprecated This function is deprecated and should not be used anymore. It will be
* removed in a future version of the MCSDK. Use MCI_StopRamp() instead.
*/
__weak bool MCI_StopSpeedRamp(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? false : STC_StopSpeedRamp(pHandle->pSTC));
#else
return (STC_StopSpeedRamp(pHandle->pSTC));
#endif
}
/**
* @brief Stop the execution of ongoing ramp.
* @param pHandle Pointer on the component instance to work on.
*/
__weak void MCI_StopRamp(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
STC_StopRamp(pHandle->pSTC);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @brief It returns speed sensor reliability with reference to the sensor
* actually used for reference frame transformation
* @param pHandle Pointer on the component instance to work on.
* @retval bool It returns true if the speed sensor utilized for reference
* frame transformation and (in speed control mode) for speed
* regulation is reliable, false otherwise
*/
__weak bool MCI_GetSpdSensorReliability(MCI_Handle_t *pHandle)
{
bool status;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
status = false;
}
else
{
#endif
SpeednPosFdbk_Handle_t *SpeedSensor = STC_GetSpeedSensor(pHandle->pSTC);
status = SPD_Check(SpeedSensor);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (status);
}
/**
* @brief Returns the last computed average mechanical speed, expressed in
* the unit defined by #SPEED_UNIT and related to the sensor actually
* used by FOC algorithm
* @param pHandle Pointer on the component instance to work on.
*/
__weak int16_t MCI_GetAvrgMecSpeedUnit(MCI_Handle_t *pHandle)
{
int16_t temp_speed;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
temp_speed = 0;
}
else
{
#endif
SpeednPosFdbk_Handle_t * SpeedSensor = STC_GetSpeedSensor(pHandle->pSTC);
temp_speed = SPD_GetAvrgMecSpeedUnit(SpeedSensor);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (temp_speed);
}
/**
* @brief Returns the last computed average mechanical speed, expressed in rpm
* and related to the sensor actually used by FOC algorithm.
* @param pHandle Pointer on the component instance to work on.
*/
__weak float_t MCI_GetAvrgMecSpeed_F(MCI_Handle_t *pHandle)
{
float_t returnAvrgSpeed;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
returnAvrgSpeed = 0.0f;
}
else
{
#endif
SpeednPosFdbk_Handle_t *SpeedSensor = STC_GetSpeedSensor(pHandle->pSTC);
returnAvrgSpeed = (((float_t)SPD_GetAvrgMecSpeedUnit(SpeedSensor) * (float_t)U_RPM) / (float_t)SPEED_UNIT);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (returnAvrgSpeed);
}
/**
* @brief Returns the current mechanical rotor speed reference expressed in the unit defined by #SPEED_UNIT
*
* @param pHandle Pointer on the component instance to work on.
*
*/
__weak int16_t MCI_GetMecSpeedRefUnit(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? 0 : STC_GetMecSpeedRefUnit(pHandle->pSTC));
#else
return (STC_GetMecSpeedRefUnit(pHandle->pSTC));
#endif
}
/**
* @brief Returns the current mechanical rotor speed reference expressed in rpm.
*
* @param pHandle Pointer on the component instance to work on.
*
*/
__weak float_t MCI_GetMecSpeedRef_F(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? 0.0f :
(((float_t)STC_GetMecSpeedRefUnit(pHandle->pSTC) * (float_t)U_RPM) / (float_t)SPEED_UNIT));
#else
return ((((float_t)STC_GetMecSpeedRefUnit(pHandle->pSTC) * (float_t)U_RPM) / (float_t)SPEED_UNIT));
#endif
}
/**
* @brief It returns stator current Iab in ab_t format
* @param pHandle Pointer on the component instance to work on.
* @retval ab_t Stator current Iab
*/
__weak ab_t MCI_GetIab(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
ab_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.a = 0;
tempVal.b = 0;
}
else
{
tempVal = pHandle->pFOCVars->Iab;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Iab);
#endif
}
__weak ab_f_t MCI_GetIab_F(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
ab_f_t iab;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
iab.a = 0.0f;
iab.b = 0.0f;
}
else
{
#endif
iab.a = (float_t)((float_t)pHandle->pFOCVars->Iab.a * pHandle->pScale->current);
iab.b = (float_t)((float_t)pHandle->pFOCVars->Iab.b * pHandle->pScale->current);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (iab);
}
/**
* @brief It returns stator current Ialphabeta in alphabeta_t format
* @param pHandle Pointer on the component instance to work on.
* @retval alphabeta_t Stator current Ialphabeta
*/
__weak alphabeta_t MCI_GetIalphabeta(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
alphabeta_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.alpha = 0;
tempVal.beta = 0;
}
else
{
tempVal = pHandle->pFOCVars->Ialphabeta;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Ialphabeta);
#endif
}
/**
* @brief It returns stator current Iqd in qd_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_t Stator current Iqd
*/
__weak qd_t MCI_GetIqd(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
qd_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.q = 0;
tempVal.d = 0;
}
else
{
tempVal = pHandle->pFOCVars->Iqd;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Iqd);
#endif
}
/**
* @brief It returns stator current Iqd in float_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_f_t Stator current Iqd (in Ampere)
*/
__weak qd_f_t MCI_GetIqd_F(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
qd_f_t iqd;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
iqd.d = 0.0f;
iqd.q = 0.0f;
}
else
{
#endif
iqd.d = (float_t)((float_t)pHandle->pFOCVars->Iqd.d * pHandle->pScale->current);
iqd.q = (float_t)((float_t)pHandle->pFOCVars->Iqd.q * pHandle->pScale->current);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (iqd);
}
/**
* @brief It returns stator current IqdHF in qd_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_t Stator current IqdHF if HFI is selected as main
* sensor. Otherwise it returns { 0, 0}.
*/
__weak qd_t MCI_GetIqdHF(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
qd_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.q = 0;
tempVal.d = 0;
}
else
{
tempVal = pHandle->pFOCVars->IqdHF;
}
return (tempVal);
#else
return (pHandle->pFOCVars->IqdHF);
#endif
}
/**
* @brief It returns stator current Iqdref in qd_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_t Stator current Iqdref
*/
__weak qd_t MCI_GetIqdref(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
qd_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.q = 0;
tempVal.d = 0;
}
else
{
tempVal = pHandle->pFOCVars->Iqdref;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Iqdref);
#endif
}
/**
* @brief It returns stator current Iqdref in float_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_f_t Stator current Iqdref (in Ampere)
*/
__weak qd_f_t MCI_GetIqdref_F(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
qd_f_t iqdref;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
iqdref.d = 0.0f;
iqdref.q = 0.0f;
}
else
{
#endif
iqdref.d = (float_t)((float_t)pHandle->pFOCVars->Iqdref.d * pHandle->pScale->current);
iqdref.q = (float_t)((float_t)pHandle->pFOCVars->Iqdref.q * pHandle->pScale->current);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (iqdref);
}
/**
* @brief It returns stator current Vqd in qd_t format
* @param pHandle Pointer on the component instance to work on.
* @retval qd_t Stator current Vqd
*/
__weak qd_t MCI_GetVqd(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
qd_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.q = 0;
tempVal.d = 0;
}
else
{
tempVal = pHandle->pFOCVars->Vqd;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Vqd);
#endif
}
/**
* @brief It returns stator current Valphabeta in alphabeta_t format
* @param pHandle Pointer on the component instance to work on.
* @retval alphabeta_t Stator current Valphabeta
*/
__weak alphabeta_t MCI_GetValphabeta(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
alphabeta_t tempVal;
if (MC_NULL == pHandle)
{
tempVal.alpha = 0;
tempVal.beta = 0;
}
else
{
tempVal = pHandle->pFOCVars->Valphabeta;
}
return (tempVal);
#else
return (pHandle->pFOCVars->Valphabeta);
#endif
}
/**
* @brief It returns the rotor electrical angle actually used for reference
* frame transformation
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t Rotor electrical angle in dpp format
*/
__weak int16_t MCI_GetElAngledpp(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? 0 : pHandle->pFOCVars->hElAngle);
#else
return (pHandle->pFOCVars->hElAngle);
#endif
}
/**
* @brief It returns the reference electrical torque, fed to derived class for
* Iqref and Idref computation
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t Teref
*/
__weak int16_t MCI_GetTeref(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? 0 : pHandle->pFOCVars->hTeref);
#else
return (pHandle->pFOCVars->hTeref);
#endif
}
/**
* @brief It returns the reference electrical torque.
* @param pHandle Pointer on the component instance to work on.
* @retval float_t Teref
*/
__weak float_t MCI_GetTeref_F(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
#ifdef NULL_PTR_CHECK_MC_INT
return ((MC_NULL == pHandle) ? 0.0f : ((float_t)pHandle->pFOCVars->hTeref * (float_t)pHandle->pScale->current));
#else
return ((float_t)(pHandle->pFOCVars->hTeref * pHandle->pScale->current));
#endif
}
/**
* @brief It returns the motor phase current amplitude (0-to-peak) in s16A
* To convert s16A into Ampere following formula must be used:
* Current(Amp) = [Current(s16A) * Vdd micro] / [65536 * Rshunt * Aop]
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t Motor phase current (0-to-peak) in s16A
*/
__weak int16_t MCI_GetPhaseCurrentAmplitude(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
alphabeta_t Local_Curr;
int16_t wAux;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
wAux = 0;
}
else
{
#endif
Local_Curr = pHandle->pFOCVars->Ialphabeta;
wAux = MCM_Modulus(Local_Curr.alpha, Local_Curr.beta);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (wAux);
}
/**
* @brief It returns the applied motor phase voltage amplitude (0-to-peak) in
* s16V. To convert s16V into Volts following formula must be used:
* PhaseVoltage(V) = [PhaseVoltage(s16A) * Vbus(V)] /[sqrt(3) *32767]
* @param pHandle Pointer on the component instance to work on.
* @retval int16_t Motor phase voltage (0-to-peak) in s16V
*/
__weak int16_t MCI_GetPhaseVoltageAmplitude(MCI_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13
{
int16_t temp_wAux;
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
temp_wAux = 0;
}
else
{
#endif
alphabeta_t Local_Voltage;
int32_t wAux1;
int32_t wAux2;
Local_Voltage = pHandle->pFOCVars->Valphabeta;
wAux1 = (int32_t)(Local_Voltage.alpha) * Local_Voltage.alpha;
wAux2 = (int32_t)(Local_Voltage.beta) * Local_Voltage.beta;
wAux1 += wAux2;
wAux1 = MCM_Sqrt(wAux1);
if (wAux1 > INT16_MAX)
{
wAux1 = (int32_t)INT16_MAX;
}
temp_wAux = (int16_t)wAux1;
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
return (temp_wAux);
}
/**
* @brief It re-initializes Iqdref variables with their default values.
* @param pHandle Pointer on the component instance to work on.
*/
__weak void MCI_Clear_Iqdref(MCI_Handle_t *pHandle)
{
#ifdef NULL_PTR_CHECK_MC_INT
if (MC_NULL == pHandle)
{
/* Nothing to do */
}
else
{
#endif
pHandle->pFOCVars->Iqdref = STC_GetDefaultIqdref(pHandle->pSTC);
#ifdef NULL_PTR_CHECK_MC_INT
}
#endif
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 47,844 |
C
| 27.926844 | 114 | 0.666479 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_tasks.h
|
/**
******************************************************************************
* @file mc_tasks.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file implementes tasks definition.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCTasks
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MCTASKS_H
#define MCTASKS_H
/* Includes ------------------------------------------------------------------*/
#include "mc_parameters.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup MCSDK
* @{
*/
/** @defgroup MCTasks Motor Control Tasks
*
* @brief Motor Control subsystem configuration and operation routines.
*
* @{
*/
/* Initializes the Motor subsystem core according to user defined parameters */
void MCboot(MCI_Handle_t *pMCIList[NBR_OF_MOTORS]);
/* Runs all the Tasks of the Motor Control cockpit */
void MC_RunMotorControlTasks(void);
/* Executes the Medium Frequency Task functions for each drive instance */
void MC_Scheduler(void);
/* Executes safety checks (e.g. bus voltage and temperature) for all drive instances */
void TSK_SafetyTask(void);
/* Executes the Motor Control duties that require a high frequency rate and a precise timing */
uint8_t TSK_HighFrequencyTask(void);
void UI_HandleStartStopButton_cb(void);
/* Reserves FOC execution on ADC ISR half a PWM period in advance */
void TSK_DualDriveFIFOUpdate(uint8_t Motor);
/* Puts the Motor Control subsystem in in safety conditions on a Hard Fault */
void TSK_HardwareFaultTask(void);
/* Locks GPIO pins used for Motor Control to prevent accidental reconfiguration */
void mc_lock_pins(void);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* MCTASKS_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 2,397 |
C
| 28.243902 | 95 | 0.587818 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/pwm_curr_fdbk.h
|
/**
******************************************************************************
* @file pwm_curr_fdbk.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains all definitions and functions prototypes for the
* PWM & Current Feedback component of the Motor Control SDK.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup pwm_curr_fdbk
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PWMNCURRFDBK_H
#define PWMNCURRFDBK_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
/* Exported defines ------------------------------------------------------------*/
#define SECTOR_1 0U
#define SECTOR_2 1U
#define SECTOR_3 2U
#define SECTOR_4 3U
#define SECTOR_5 4U
#define SECTOR_6 5U
/* @brief Used in calculation of Ia, Ib and Ic
*
* See function PWMC_CalcPhaseCurrentsEst
*/
#define SQRT3FACTOR ((uint16_t)0xDDB4) /* = (16384 * 1.732051 * 2)*/
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup pwm_curr_fdbk
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @brief PWM & Current Sensing component handle type */
typedef struct PWMC_Handle PWMC_Handle_t;
/**
* @brief Pointer on callback functions used by PWMC components
*
* This type is needed because the actual functions to use can change at run-time.
*
* See the following items:
* - PWMC_Handle::pFctSwitchOffPwm
* - PWMC_Handle::pFctSwitchOnPwm
* - PWMC_Handle::pFctCurrReadingCalib
* - PWMC_Handle::pFctRLDetectionModeEnable
* - PWMC_Handle::pFctRLDetectionModeDisable
*
*
*/
typedef void (*PWMC_Generic_Cb_t)(PWMC_Handle_t *pHandle);
/**
* @brief Pointer on the function provided by the PMWC component instance to get the phase current.
*
* This type is needed because the actual function to use can change at run-time
* (See PWMC_Handle::pFctGetPhaseCurrents).
*
*/
typedef void (*PWMC_GetPhaseCurr_Cb_t)(PWMC_Handle_t *pHandle, ab_t *Iab);
/**
* @brief Pointer on the function provided by the PMWC component instance to set low sides ON.
*
* This type is needed because the actual function to use can change at run-time
* (See PWMC_Handle::pFctTurnOnLowSides).
*
*/
typedef void (*PWMC_TurnOnLowSides_Cb_t)(PWMC_Handle_t *pHandle, const uint32_t ticks);
/**
* @brief Pointer on the function provided by the PMWC component instance to set the reference
* voltage for the over current protection.
*
* This type is needed because the actual function to use can change at run-time
* (See PWMC_Handle::pFctOCPSetReferenceVoltage).
*
*/
typedef void (*PWMC_SetOcpRefVolt_Cb_t)(PWMC_Handle_t *pHandle, uint16_t hDACVref);
/**
* @brief Pointer on the functions provided by the PMWC component instance to set the ADC sampling
* point for each sectors.
*
* This type is needed because the actual function to use can change at run-time. See:
* - PWMC_Handle::pFctSetADCSampPointSect1
* - PWMC_Handle::pFctSetADCSampPointSect2
* - PWMC_Handle::pFctSetADCSampPointSect3
* - PWMC_Handle::pFctSetADCSampPointSect4
* - PWMC_Handle::pFctSetADCSampPointSect5
* - PWMC_Handle::pFctSetADCSampPointSect6
*
*/
typedef uint16_t (*PWMC_SetSampPointSectX_Cb_t)(PWMC_Handle_t *pHandle);
/**
* @brief Pointer on the function provided by the PMWC component instance to set the PWM duty cycle
* in RL detection mode.
*
* This type is needed because the actual function to use can change at run-time
* (See PWMC_Handle::pFctRLDetectionModeSetDuty).
*
*/
typedef uint16_t (*PWMC_RLDetectSetDuty_Cb_t)(PWMC_Handle_t *pHandle, uint16_t hDuty);
/**
* @brief Pointer on the function provided by the PMWC component instance to set the calibrated offsets
* in RL detection mode.
*
* This type is needed because the actual function to use can change at run-time
* (See PWMC_Handle::pFctSetOffsetCalib).
*
*/
typedef void (*PWMC_SetOffsetCalib_Cb_t)(PWMC_Handle_t *pHandle, PolarizationOffsets_t *offsets);
/**
* @brief Pointer on the function provided by the PMWC component instance to get the calibrated offsets
* in RL detection mode.
*
* This type is needed because the actual function to use can change at run-time
*/
typedef void (*PWMC_GetOffsetCalib_Cb_t)(PWMC_Handle_t *pHandle, PolarizationOffsets_t *offsets);
/**
* @brief This structure is used to handle the data of an instance of the PWM & Current Feedback component
*
*/
struct PWMC_Handle
{
/** @{ */
PWMC_GetPhaseCurr_Cb_t
pFctGetPhaseCurrents; /**< Pointer on the function the component instance uses to retrieve phase currents. */
PWMC_Generic_Cb_t
pFctSwitchOffPwm; /**< Pointer on the function the component instance uses to switch PWM off. */
PWMC_Generic_Cb_t
pFctSwitchOnPwm; /**< Pointer on the function the component instance uses to switch PWM on. */
PWMC_Generic_Cb_t
pFctCurrReadingCalib; /**< Pointer on the fct the component instance uses to calibrate the current reading ADC(s). */
PWMC_TurnOnLowSides_Cb_t
pFctTurnOnLowSides; /**< Pointer on the function the component instance uses to turn low sides on. */
PWMC_SetSampPointSectX_Cb_t
pFctSetADCSampPointSectX; /**< Pointer on the function the component instance uses to set the ADC sampling point. */
PWMC_SetOcpRefVolt_Cb_t
pFctOCPSetReferenceVoltage; /**< Pointer on the fct the component instance uses to set the over current ref voltage. */
PWMC_Generic_Cb_t
pFctRLDetectionModeEnable; /**< Pointer on the function the component instance uses to enable RL detection mode. */
PWMC_Generic_Cb_t
pFctRLDetectionModeDisable; /**< Pointer on the function the component instance uses to disable RL detection mode. */
PWMC_RLDetectSetDuty_Cb_t
pFctRLDetectionModeSetDuty; /**< Pointer on the fct the component instance uses to set the PWM duty cycle in RL
detection mode. */
PWMC_Generic_Cb_t
pFctRLTurnOnLowSidesAndStart; /**< Pointer on the function the component instance uses to turn on low side and start. */
PWMC_SetOffsetCalib_Cb_t
pFctSetOffsetCalib; /**< Pointer on the fct the component instance uses to set the calibrated offsets. */
PWMC_GetOffsetCalib_Cb_t
pFctGetOffsetCalib; /**< Pointer on the fct the component instance uses to get the calibrated offsets. */
/** @} */
int32_t LPFIqBuf; /**< Low Pass Filter buffer used for averaged @f$ I_q @f$ value computation. */
int32_t LPFIdBuf; /**< Low Pass Filter Buffer used for averaged @f$ I_d @f$ value computation. */
GPIO_TypeDef * pwm_en_u_port; /*!< Channel 1N (low side) GPIO output */
GPIO_TypeDef * pwm_en_v_port; /*!< Channel 2N (low side) GPIO output*/
GPIO_TypeDef * pwm_en_w_port; /*!< Channel 3N (low side) GPIO output */
uint16_t pwm_en_u_pin; /*!< Channel 1N (low side) GPIO output pin. */
uint16_t pwm_en_v_pin; /*!< Channel 2N (low side) GPIO output pin. */
uint16_t pwm_en_w_pin; /*!< Channel 3N (low side) GPIO output pin. */
uint16_t hT_Sqrt3; /**< Constant used by PWM algorithm (@f$\sqrt{3}@f$). */
uint16_t CntPhA; /**< PWM Duty cycle for phase A. */
uint16_t CntPhB; /**< PWM Duty cycle for phase B. */
uint16_t CntPhC; /**< PWM Duty cycle for phase C. */
uint16_t SWerror; /**< Contains status about SW error. */
uint16_t lowDuty;
uint16_t midDuty;
uint16_t highDuty;
uint16_t HighDutyStored; /**< Discontinuous PWM Store current Highest Duty for recovering. */
uint16_t OffCalibrWaitTimeCounter; /**< Counter to wait fixed time before motor
current measurement offset calibration. */
int16_t Ia; /**< Last @f$I_{a}@f$ measurement. */
int16_t Ib; /**< Last @f$I_{b}@f$ measurement. */
int16_t Ic; /**< Last @f$I_{c}@f$ measurement. */
int16_t IaEst; /**< Estimated @f$I_{a}@f$ based on averaged @f$ I_q @f$,@f$ I_d @f$ values and used when @f$I_{a}@f$ current is not available. */
int16_t IbEst; /**< Estimated @f$I_{b}@f$ based on averaged @f$ I_q @f$,@f$ I_d @f$ values and used when @f$I_{b}@f$ current is not available. */
int16_t IcEst; /**< Estimated @f$I_{c}@f$ based on averaged @f$ I_q @f$,@f$ I_d @f$ values and used when @f$I_{c}@f$ current is not available. */
int16_t LPFIqd_const; /**< Low pass filter constant (averaging coeficient). */
uint16_t DTTest; /**< Reserved. */
uint16_t PWMperiod; /**< PWM period expressed in timer clock cycles unit:
* @f$hPWMPeriod = TimerFreq_{CLK} / F_{PWM}@f$ */
uint16_t DTCompCnt; /**< Half of Dead time expressed
* in timer clock cycles unit:
* @f$hDTCompCnt = (DT_s \cdot TimerFreq_{CLK})/2@f$ */
uint16_t Ton; /**< Reserved. */
uint16_t Toff; /**< Reserved. */
uint8_t Motor; /**< Motor reference number. */
uint8_t AlignFlag; /**< Phase current 0 is reliable, 1 is not. */
uint8_t Sector; /**< Space vector sector number. */
LowSideOutputsFunction_t LowSideOutputs; /*!< Low side or enabling signals generation method are defined here. */
bool TurnOnLowSidesAction; /**< True if TurnOnLowSides action is active,
false otherwise. */
bool DPWM_Mode; /**< Discontinuous PWM mode activation. */
bool RLDetectionMode; /**< True if enabled, false if disabled. */
bool offsetCalibStatus; /**< True if offset calibration completed, false otherwise. */
bool OverCurrentFlag; /* This flag is set when an overcurrent occurs.*/
bool OverVoltageFlag; /* This flag is set when an overvoltage occurs.*/
bool driverProtectionFlag; /* This flag is set when a driver protection occurs.*/
bool BrakeActionLock; /* This flag is set to avoid that brake action is interrupted.*/
volatile bool useEstCurrent; /**< Estimated current flag. */
bool SingleShuntTopology; /*!< This flag is set when Single Shunt topology is used */
};
/**
* @brief Current reading calibration definition.
*/
typedef enum
{
CRC_START, /**< Initializes the current reading calibration. */
CRC_EXEC /**< Executes the current reading calibration. */
} CRCAction_t;
/* Returns the phase current of the motor as read by the ADC (in s16A unit). */
void PWMC_GetPhaseCurrents(PWMC_Handle_t *pHandle, ab_t *Iab);
/* Converts input voltages @f$ V_{\alpha} @f$ and @f$ V_{\beta} @f$ into PWM duty cycles
* and feed them to the inverter. */
uint16_t PWMC_SetPhaseVoltage(PWMC_Handle_t *pHandle, alphabeta_t Valfa_beta);
/* Switches PWM generation off, inactivating the outputs. */
void PWMC_SwitchOffPWM(PWMC_Handle_t *pHandle);
/* Enables PWM generation on the proper Timer peripheral. */
void PWMC_SwitchOnPWM(PWMC_Handle_t *pHandle);
/* Calibrates ADC current conversions by reading the offset voltage
* present on ADC pins when no motor current is flowing in. */
bool PWMC_CurrentReadingCalibr(PWMC_Handle_t *pHandle, CRCAction_t action);
/* Switches power stage Low Sides transistors on. */
void PWMC_TurnOnLowSides(PWMC_Handle_t *pHandle, uint32_t ticks);
/* Sets the calibrated @p offsets for each of the phases in the @p pHandle handler. In case
* of single shunt only phase A is relevant. */
void PWMC_SetOffsetCalib(PWMC_Handle_t *pHandle, PolarizationOffsets_t *offsets);
/* Gets the calibrated @p offsets for each of the phases in the @p pHandle handler. In case
* of single shunt only phase A is relevant. */
void PWMC_GetOffsetCalib(PWMC_Handle_t *pHandle, PolarizationOffsets_t *offsets);
/* Manages HW overcurrent protection. */
void *PWMC_OCP_Handler(PWMC_Handle_t *pHandle);
/* Manages driver protection. */
void *PWMC_DP_Handler(PWMC_Handle_t *pHandle);
/* Manages HW overvoltage protection. */
void *PWMC_OVP_Handler(PWMC_Handle_t *pHandle, TIM_TypeDef *TIMx);
/* Checks if a fault (OCP, DP or OVP) occurred since last call. */
uint16_t PWMC_IsFaultOccurred(PWMC_Handle_t *pHandle);
/* Sets the over current threshold through the DAC reference voltage. */
void PWMC_OCPSetReferenceVoltage(PWMC_Handle_t *pHandle, uint16_t hDACVref);
/* Retrieves the satus of TurnOnLowSides action. */
bool PWMC_GetTurnOnLowSidesAction(const PWMC_Handle_t *pHandle);
/* Enables Discontinuous PWM mode using the @p pHandle PWMC component. */
void PWMC_DPWM_ModeEnable(PWMC_Handle_t *pHandle);
/* Disables Discontinuous PWM mode using the @p pHandle PWMC component. */
void PWMC_DPWM_ModeDisable(PWMC_Handle_t *pHandle);
/* Returns the status of the Discontinuous PWM Mode stored in the @p pHandle PWMC component. */
bool PWMC_GetDPWM_Mode(PWMC_Handle_t *pHandle);
/* Enables the RL detection mode by calling the function in @p pHandle PWMC component. */
void PWMC_RLDetectionModeEnable(PWMC_Handle_t *pHandle);
/* Disables the RL detection mode by calling the function in @p pHandle PWMC component. */
void PWMC_RLDetectionModeDisable(PWMC_Handle_t *pHandle);
/* Sets the PWM duty cycle to apply in the RL Detection mode. */
uint16_t PWMC_RLDetectionModeSetDuty(PWMC_Handle_t *pHandle, uint16_t hDuty);
/* Turns on low sides switches and starts ADC triggerin. */
void PWMC_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHandle);
/* Sets the aligned motor flag. */
void PWMC_SetAlignFlag(PWMC_Handle_t *pHandle, uint8_t flag);
/* Sets the Callback that the PWMC component shall invoke to get phases current. */
void PWMC_RegisterGetPhaseCurrentsCallBack(PWMC_GetPhaseCurr_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to switch PWM generation off. */
void PWMC_RegisterSwitchOffPwmCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to switch PWM generation on. */
void PWMC_RegisterSwitchonPwmCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to execute a calibration of the current sensing system. */
void PWMC_RegisterReadingCalibrationCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to turn low sides on. */
void PWMC_RegisterTurnOnLowSidesCallBack(PWMC_TurnOnLowSides_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to compute ADC sampling point. */
void PWMC_RegisterSampPointSectXCallBack(PWMC_SetSampPointSectX_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to set the reference voltage for the overcurrent
* protection. */
void PWMC_RegisterOCPSetRefVoltageCallBack(PWMC_SetOcpRefVolt_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to enable the R/L detection mode. */
void PWMC_RegisterRLDetectionModeEnableCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to disable the R/L detection mode. */
void PWMC_RegisterRLDetectionModeDisableCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Sets the Callback that the PWMC component shall invoke to set the duty cycle for the R/L detection mode */
void PWMC_RegisterRLDetectionModeSetDutyCallBack(PWMC_RLDetectSetDuty_Cb_t pCallBack, PWMC_Handle_t *pHandle);
/* Used to clear variables in CPWMC. */
void PWMC_Clear(PWMC_Handle_t *pHandle);
/* Converts input currents components Iqd into estimated currents Ia, Ib and Ic. */
void PWMC_CalcPhaseCurrentsEst(PWMC_Handle_t *pHandle, qd_t Iqd, int16_t hElAngledpp);
/* Converts input voltage components @f$ V_{\alpha} @f$ and @f$ V_{\beta} @f$ into duty cycles
* and feed them to the inverter with overmodulation function. */
uint16_t PWMC_SetPhaseVoltage_OVM(PWMC_Handle_t *pHandle, alphabeta_t Valfa_beta);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* PWMNCURRFDBK_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 18,081 |
C
| 48.135869 | 175 | 0.631381 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/register_interface.h
|
/**
******************************************************************************
* @file register_interface.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides firmware registers definitions used by MCP protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef REGISTER_INTERFACE_H
#define REGISTER_INTERFACE_H
#include "mcp.h"
#include "mc_type.h"
#include "mc_parameters.h"
/*
MCP_ID definition :
| Element Identifier 10 bits | Type | Motor #|
| | | |
|15|14|13|12|11|10|09|08|07|06|05|04|03|02|01|00|
Type definition :
0 Reserved
1 8-bit data
2 16-bit data
3 32-bit data
4 Character string
5 Raw Structure
6 Reserved
7 Reserved
*/
#define MCP_ID_SIZE 2U /* Number of byte */
#define MCP_ID_SIZE_16B 1U /* Number of 16bits word */
#define ELT_IDENTIFIER_POS 6U
#define TYPE_POS 3U
#define TYPE_MASK 0x38U
#define MOTOR_MASK 0x7U
#define REG_MASK 0xFFF8U
#define EXTRACT_MOTORID(dataID) ((dataID -1U) & MOTOR_MASK)
#define TYPE_DATA_SEG_END (0U << TYPE_POS)
#define TYPE_DATA_8BIT (1U << TYPE_POS)
#define TYPE_DATA_16BIT (2U << TYPE_POS)
#define TYPE_DATA_32BIT (3U << TYPE_POS)
#define TYPE_DATA_STRING (4U << TYPE_POS)
#define TYPE_DATA_RAW (5U << TYPE_POS)
#define TYPE_DATA_FLAG (6U << TYPE_POS)
#define TYPE_DATA_SEG_BEG (7U << TYPE_POS)
/* TYPE_DATA_8BIT registers definition */
#define MC_REG_STATUS ((1U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_CONTROL_MODE ((2U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_RUC_STAGE_NBR ((3U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_PFC_STATUS ((13U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_PFC_ENABLED ((14U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_CHECK ((15U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_STATE ((16U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_STEPS ((17U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_PP ((18U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_FOC_REP_RATE ((19U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_SC_COMPLETED ((20U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_POSITION_CTRL_STATE ((21U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_POSITION_ALIGN_STATE ((22U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_HT_STATE ((23U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_HT_PROGRESS ((24U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_HT_PLACEMENT ((25U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_HT_MECH_WANTED_DIRECTION ((26U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_FAST_DEMAG ((27U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_QUASI_SYNCH ((28U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
#define MC_REG_PB_CHARACTERIZATION ((29U << ELT_IDENTIFIER_POS) | TYPE_DATA_8BIT)
/* TYPE_DATA_16BIT registers definition */
#define MC_REG_SPEED_KP ((2U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SPEED_KI ((3U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SPEED_KD ((4U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KP ((6U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KI ((7U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KD ((8U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KP ((10U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KI ((11U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KD ((12U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_C1 ((13U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_C2 ((14U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_C1 ((15U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_C2 ((16U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_KI ((17U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_KP ((18U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_KP ((19U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_KI ((20U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_BUS ((21U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_BUS_VOLTAGE ((22U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_HEATS_TEMP ((23U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_DAC_OUT1 ((25U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_DAC_OUT2 ((26U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_DAC_OUT3 ((27 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_BUS_MEAS ((30U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_A ((31U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_B ((32U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_ALPHA_MEAS ((33U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_BETA_MEAS ((34U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_MEAS ((35U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_MEAS ((36U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_REF ((37U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_REF ((38U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_V_Q ((39U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_V_D ((40U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_V_ALPHA ((41U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_V_BETA ((42U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_ENCODER_EL_ANGLE ((43 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_ENCODER_SPEED ((44 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_EL_ANGLE ((45U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_ROT_SPEED ((46U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_I_ALPHA ((47U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_I_BETA ((48U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_BEMF_ALPHA ((49U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_BEMF_BETA ((50U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_EL_ANGLE ((51 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_ROT_SPEED ((52 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_I_ALPHA ((53 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_I_BETA ((54 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_BEMF_ALPHA ((55 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOCORDIC_BEMF_BETA ((56 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_DAC_USER1 ((57U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_DAC_USER2 ((58U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_HALL_EL_ANGLE ((59 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_HALL_SPEED ((60 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FF_VQ ((62U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FF_VD ((63U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FF_VQ_PIOUT ((64U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FF_VD_PIOUT ((65U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_DCBUS_REF ((66U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_DCBUS_MEAS ((67U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_ACBUS_FREQ ((68U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_ACBUS_RMS ((69U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KP ((70U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KI ((71U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KD ((72U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KP ((73U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KI ((74U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KD ((75U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_STARTUP_DURATION ((76U << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SC_PWM_FREQUENCY ((77 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KP ((78 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KI ((79 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KD ((80 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SPEED_KP_DIV ((81 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SPEED_KI_DIV ((82 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_SPEED_KD_DIV ((83 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KP_DIV ((84 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KI_DIV ((85 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_D_KD_DIV ((86 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KP_DIV ((87 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KI_DIV ((88 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_I_Q_KD_DIV ((89 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KP_DIV ((90 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KI_DIV ((91 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_POSITION_KD_DIV ((92 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KP_DIV ((93 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KI_DIV ((94 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_I_KD_DIV ((95 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KP_DIV ((96 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KI_DIV ((97 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PFC_V_KD_DIV ((98 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_KI_DIV ((99 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STOPLL_KP_DIV ((100 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_KP_DIV ((101 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FLUXWK_KI_DIV ((102 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_STARTUP_CURRENT_REF ((105 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_PULSE_VALUE ((106 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_FOC_VQREF ((107 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_BEMF_ZCR ((108 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_BEMF_U ((109 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_BEMF_V ((110 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_BEMF_W ((111 << ELT_IDENTIFIER_POS) | TYPE_DATA_16BIT)
#define MC_REG_OVERVOLTAGETHRESHOLD ((112U << ELT_IDENTIFIER_POS)| TYPE_DATA_16BIT )
#define MC_REG_UNDERVOLTAGETHRESHOLD ((113U << ELT_IDENTIFIER_POS)| TYPE_DATA_16BIT )
/* TYPE_DATA_32BIT registers definition */
#define MC_REG_FAULTS_FLAGS ((0 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SPEED_MEAS ((1 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SPEED_REF ((2 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_STOPLL_EST_BEMF ((3 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_STOPLL_OBS_BEMF ((4 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_STOCORDIC_EST_BEMF ((5 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_STOCORDIC_OBS_BEMF ((6 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_FF_1Q ((7 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_FF_1D ((8 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_FF_2 ((9 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT) /* To check shifted by >> 16*/
#define MC_REG_PFC_FAULTS ((40 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_CURRENT_POSITION ((41 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_RS ((91 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_LS ((92 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_KE ((93 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_VBUS ((94 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_MEAS_NOMINALSPEED ((95 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_CURRENT ((96 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_SPDBANDWIDTH ((97 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_LDLQRATIO ((98 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_NOMINAL_SPEED ((99 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_CURRBANDWIDTH ((100 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_J ((101 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_F ((102 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_MAX_CURRENT ((103 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_STARTUP_SPEED ((104 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_SC_STARTUP_ACC ((105 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_RESISTOR_OFFSET ((116 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_MOTOR_POWER ((109 << ELT_IDENTIFIER_POS) | TYPE_DATA_32BIT)
#define MC_REG_FW_NAME ((0U << ELT_IDENTIFIER_POS) | TYPE_DATA_STRING)
#define MC_REG_CTRL_STAGE_NAME ((1U << ELT_IDENTIFIER_POS) | TYPE_DATA_STRING)
#define MC_REG_PWR_STAGE_NAME ((2U << ELT_IDENTIFIER_POS) | TYPE_DATA_STRING)
#define MC_REG_MOTOR_NAME ((3U << ELT_IDENTIFIER_POS) | TYPE_DATA_STRING)
#define MC_REG_GLOBAL_CONFIG ((0U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_MOTOR_CONFIG ((1U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_APPLICATION_CONFIG ((2U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_FOCFW_CONFIG ((3U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_SCALE_CONFIG ((4U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_SPEED_RAMP ((6U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_TORQUE_RAMP ((7U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_REVUP_DATA ((8U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW) /* Configure all steps*/
#define MC_REG_CURRENT_REF ((13U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_POSITION_RAMP ((14U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_ASYNC_UARTA ((20U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_ASYNC_UARTB ((21U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_ASYNC_STLNK ((22U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_HT_HEW_PINS ((28U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_HT_CONNECTED_PINS ((29U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_HT_PHASE_SHIFT ((30U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_BEMF_ADC_CONFIG ((31U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
#define MC_REG_BEMF_ONTIME_ADC_CONFIG ((32U << ELT_IDENTIFIER_POS) | TYPE_DATA_RAW)
uint8_t RI_SetRegisterGlobal(uint16_t regID, uint8_t typeID, uint8_t *data, uint16_t *size, int16_t dataAvailable);
uint8_t RI_SetRegisterMotor1(uint16_t regID, uint8_t typeID,uint8_t *data, uint16_t *size, int16_t dataAvailable);
uint8_t RI_GetRegisterGlobal(uint16_t regID, uint8_t typeID, uint8_t * data, uint16_t *size, int16_t freeSpace);
uint8_t RI_GetRegisterMotor1(uint16_t regID, uint8_t typeID, uint8_t * data, uint16_t *size, int16_t freeSpace);
uint8_t RI_MovString(const char_t * srcString, char_t * destString, uint16_t *size, int16_t maxSize);
uint8_t RI_GetPtrReg(uint16_t dataID, void **dataPtr);
uint8_t RI_GetIDSize(uint16_t dataID);
#endif /* REGISTER_INTERFACE_H */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 18,797 |
C
| 70.204545 | 117 | 0.584029 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_perf.h
|
/**
******************************************************************************
* @file mc_perf.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief Execution time measurement definitions
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MC_PERF_H
#define MC_PERF_H
typedef enum
{
MEASURE_TSK_HighFrequencyTaskM1,
MEASURE_TSK_MediumFrequencyTaskM1,
/* Others functions to measure to be added here. */
} MC_PERF_FUNCTIONS_LIST_t;
/* Define max number of traces according to the list defined in MC_PERF_FUNCTIONS_LIST_t */
#define MC_PERF_NB_TRACES 2U
/* DWT (Data Watchpoint and Trace) registers, only exists on ARM Cortex with a DWT unit */
/* The DWT is usually implemented in Cortex-M3 or higher, but not on Cortex-M0(+) (ie not present on G0) */
typedef struct
{
uint32_t StartMeasure;
uint32_t DeltaTimeInCycle;
uint32_t min;
uint32_t max;
} Perf_Handle_t;
typedef struct
{
bool BG_Task_OnGoing;
uint32_t AccHighFreqTasksCnt;
Perf_Handle_t MC_Perf_TraceLog[MC_PERF_NB_TRACES];
} MC_Perf_Handle_t;
void MC_Perf_Measure_Init(MC_Perf_Handle_t *pHandle);
void MC_Perf_Clear(MC_Perf_Handle_t *pHandle,uint8_t bMotor);
void MC_Perf_Measure_Start(MC_Perf_Handle_t *pHandle, uint8_t i);
void MC_BG_Perf_Measure_Start(MC_Perf_Handle_t *pHandle, uint8_t i);
void MC_Perf_Measure_Stop(MC_Perf_Handle_t *pHandle, uint8_t i);
void MC_BG_Perf_Measure_Stop(MC_Perf_Handle_t *pHandle, uint8_t i);
float_t MC_Perf_GetCPU_Load(const MC_Perf_Handle_t *pHandle);
float_t MC_Perf_GetMaxCPU_Load(const MC_Perf_Handle_t *pHandle);
float_t MC_Perf_GetMinCPU_Load(const MC_Perf_Handle_t *pHandle);
#endif /* MC_PERF_H */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 2,284 |
C
| 35.269841 | 107 | 0.620841 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mcp_config.h
|
/**
******************************************************************************
* @file mcp_config.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides configuration definition of the MCP protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MCP_CONFIG_H
#define MCP_CONFIG_H
#include "mcp.h"
#include "aspep.h"
#include "mcpa.h"
#define USARTA USART2
#define DMA_RX_A DMA1
#define DMA_TX_A DMA1
#define DMACH_RX_A LL_DMA_CHANNEL_1
#define DMACH_TX_A LL_DMA_CHANNEL_2
#define MCP_USER_CALLBACK_MAX 2U
#define MCP_TX_SYNC_PAYLOAD_MAX 128U
#define MCP_RX_SYNC_PAYLOAD_MAX 128U
#define MCP_TX_SYNCBUFFER_SIZE (MCP_TX_SYNC_PAYLOAD_MAX+ASPEP_HEADER_SIZE+ASPEP_DATACRC_SIZE)
#define MCP_RX_SYNCBUFFER_SIZE (MCP_RX_SYNC_PAYLOAD_MAX+ASPEP_DATACRC_SIZE) // ASPEP_HEADER_SIZE is not stored in the RX buffer.
#define MCP_TX_ASYNC_PAYLOAD_MAX_A 2048U
#define MCP_TX_ASYNCBUFFER_SIZE_A (MCP_TX_ASYNC_PAYLOAD_MAX_A+ASPEP_HEADER_SIZE+ASPEP_DATACRC_SIZE)
#define MCPA_OVER_UARTA_STREAM 10
extern ASPEP_Handle_t aspepOverUartA;
extern MCP_Handle_t MCP_Over_UartA;
extern MCPA_Handle_t MCPA_UART_A;
extern MCP_user_cb_t MCP_UserCallBack[MCP_USER_CALLBACK_MAX];
#endif /* MCP_CONFIG_H */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 1,844 |
C
| 33.166666 | 128 | 0.613341 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_type.h
|
/**
******************************************************************************
* @file mc_type.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief Motor Control SDK global types definitions
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MC_Type
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MC_TYPE_H
#define MC_TYPE_H
/* Includes ------------------------------------------------------------------*/
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MC_Type Motor Control types
* @{
*/
#include <mc_stm_types.h>
/* char definition to match Misra Dir 4.6 typedefs that indicate size and
* signedness should be used in place ofthe basic numerical types */
typedef int8_t char_t;
#ifndef _MATH
typedef float float_t;
#endif
/** @name Macros to use bit banding capability */
/** @{ */
#define BB_REG_BIT_SET(regAddr,bit_number) *(uint32_t *) (0x42000000+(((uint32_t)regAddr - 0x40000000 )<<5)\
+ (bit_number <<2)) = (uint32_t)(0x1u)
#define BB_REG_BIT_CLR(regAddr,bit_number) (*(uint32_t *) (0x42000000+(((uint32_t)regAddr - 0x40000000)<<5)\
+ (bit_number <<2)) = (uint32_t)(0x0u))
#define BB_REG_BIT_READ(regAddr,bit_number) (*(uint32_t *) (0x42000000+(((uint32_t)regAddr - 0x40000000)<<5)\
+ (bit_number <<2)) )
/** @} */
/** @brief Not initialized pointer */
#define MC_NULL (void *)(0x0)
/** @name Motor identification macros */
/** @{ */
#define M1 (uint8_t)(0x0) /*!< Motor 1.*/
#define M2 (uint8_t)(0x1) /*!< Motor 2.*/
#define M_NONE (uint8_t)(0xFF) /*!< None motor.*/
/** @} */
/**
* @anchor fault_codes
* @name Fault codes
* The symbols below define the codes associated to the faults that the
* Motor Control subsystem can raise.
* @{ */
#define MC_NO_ERROR ((uint16_t)0x0000) /**< @brief No error. */
#define MC_NO_FAULTS ((uint16_t)0x0000) /**< @brief No error. */
#define MC_DURATION ((uint16_t)0x0001) /**< @brief Error: FOC rate to high. */
#define MC_OVER_VOLT ((uint16_t)0x0002) /**< @brief Error: Software over voltage. */
#define MC_UNDER_VOLT ((uint16_t)0x0004) /**< @brief Error: Software under voltage. */
#define MC_OVER_TEMP ((uint16_t)0x0008) /**< @brief Error: Software over temperature. */
#define MC_START_UP ((uint16_t)0x0010) /**< @brief Error: Startup failed. */
#define MC_SPEED_FDBK ((uint16_t)0x0020) /**< @brief Error: Speed feedback. */
#define MC_OVER_CURR ((uint16_t)0x0040) /**< @brief Error: Emergency input (Over current). */
#define MC_SW_ERROR ((uint16_t)0x0080) /**< @brief Software Error. */
#define MC_DP_FAULT ((uint16_t)0x0400) /**< @brief Error Driver protection fault. */
/** @}*/
/** @name Dual motor Frequency comparison definition */
/** @{ */
#define SAME_FREQ 0U
#define HIGHER_FREQ 1U
#define LOWER_FREQ 2U
#define HIGHEST_FREQ 1U
#define LOWEST_FREQ 2U
/** @} */
/** @name Error codes */
/** @{ */
#define MC_SUCCESS ((uint32_t)(0u)) /**< Success. The function executed successfully. */
#define MC_WRONG_STATE_ERROR ((uint32_t)(1u)) /**< The state machine of the motor is not in a suitable state. */
#define MC_NO_POLARIZATION_OFFSETS_ERROR ((uint32_t)(2u)) /**< Polarization offsets are needed but missing */
/** @} */
/** @brief Return type of API functions that return a status */
typedef uint32_t MC_RetStatus_t;
/**
* @brief union type definition for u32 to Float conversion and vice versa
*/
//cstat -MISRAC2012-Rule-19.2
typedef union _FLOAT_U32_
{
uint32_t U32_Val;
float Float_Val;
} FloatToU32;
//cstat +MISRAC2012-Rule-19.2
/**
* @brief Two components q, d type definition
*/
typedef struct
{
int16_t q;
int16_t d;
} qd_t;
/**
* @brief Two components q, d in float type
*/
typedef struct
{
float q;
float d;
} qd_f_t;
/**
* @brief Two components a,b type definition
*/
typedef struct
{
int16_t a;
int16_t b;
} ab_t;
/**
* @brief Two components a,b in float type
*/
typedef struct
{
float a;
float b;
} ab_f_t;
/**
* @brief Two components alpha, beta type definition
*/
typedef struct
{
int16_t alpha;
int16_t beta;
} alphabeta_t;
/* ACIM definitions start */
typedef struct
{
float fS_Component1;
float fS_Component2;
} Signal_Components;
/**
* @brief Two components type definition
*/
typedef struct
{
int16_t qVec_Component1;
int16_t qVec_Component2;
} Vector_s16_Components;
/* ACIM definitions end */
/**
* @brief SensorType_t type definition, it's used in BusVoltageSensor and TemperatureSensor component parameters
* structures to specify whether the sensor is real or emulated by SW.
*/
typedef enum
{
REAL_SENSOR, VIRTUAL_SENSOR
} SensorType_t;
/**
* @brief DOutputState_t type definition, it's used by DOUT_SetOutputState method of DigitalOutput class to specify
* the required output state.
*/
typedef enum
{
INACTIVE, ACTIVE
} DOutputState_t;
/**
* @brief DrivingMode_t type definition, it's used by Bemf_ADC class to specify the driving mode type.
*/
typedef enum
{
VM, /**< @brief Voltage mode. */
CM /**< @brief Current mode. */
} DrivingMode_t;
/**
* @brief Specifies the control modality of the motor.
*/
typedef enum
{
MCM_OBSERVING_MODE = 0, /**< @brief All transistors are opened in order to let the motor spin freely and
* observe Bemf thanks to phase voltage measurements.
*
* Only relevant when HSO is used.
*/
MCM_OPEN_LOOP_VOLTAGE_MODE, /**< @brief Open loop, duty cycle set as reference. */
MCM_OPEN_LOOP_CURRENT_MODE, /**< @brief Open loop, q & d currents set as reference. */
MCM_SPEED_MODE, /**< @brief Closed loop, Speed mode.*/
MCM_TORQUE_MODE, /**< @brief Closed loop, Torque mode.*/
MCM_PROFILING_MODE, /**< @brief FW is configured to execute the motor profiler feature.
*
* Only relevant when HSO is used.
*/
MCM_SHORTED_MODE, /**< @brief Low sides are turned on.
*
* Only relevant when HSO is used.
*/
MCM_POSITION_MODE, /**< @brief Closed loop, sensored position control mode. */
MCM_MODE_NUM /**< @brief Number of modes in enum. */
} MC_ControlMode_t;
/**
* @brief Structure type definition for feed-forward constants tuning.
*/
typedef struct
{
int32_t wConst_1D;
int32_t wConst_1Q;
int32_t wConst_2;
} FF_TuningStruct_t;
/**
* @brief structure type definition for phase offsets setting/getting. In case of single shunt
* only phaseAOffset is relevant.
*/
typedef struct
{
int32_t phaseAOffset;
int32_t phaseBOffset;
int32_t phaseCOffset;
} PolarizationOffsets_t;
/**
* @brief Current references source type, internal or external to FOCDriveClass.
*/
typedef enum
{
INTERNAL, EXTERNAL
} CurrRefSource_t ;
/**
* @brief FOC variables structure.
*/
typedef struct
{ //cstat !MISRAC2012-Dir-4.8
ab_t Iab; /**< @brief Stator current on stator reference frame abc.
*
* @note This field does not exists if HSO is used.
*/
alphabeta_t Ialphabeta; /**< @brief Stator current on stator reference frame alfa-beta.
*
* @note This field does not exists if HSO is used.
*/
qd_t IqdHF; /**< @brief Stator current on stator reference frame alfa-beta.
*
* @note This field does not exists if HSO is used.
*/
qd_t Iqd; /**< @brief Stator current on rotor reference frame qd.
*
* @note This field does not exists if HSO is used.
*/
qd_t Iqdref; /**< @brief Stator current on rotor reference frame qd.
*
* @note This field does not exists if HSO is used.
*/
int16_t UserIdref; /**< @brief User value for the Idref stator current.
*
* @note This field does not exists if HSO is used.
*/
qd_t Vqd; /**< @brief Phase voltage on rotor reference frame qd.
*
* @note This field does not exists if HSO is used.
*/
alphabeta_t Valphabeta; /**< @brief Phase voltage on stator reference frame alpha-beta.
*
* @note This field does not exists if HSO is used.
*/
int16_t hTeref; /**< @brief Reference torque.
*
* @note This field does not exists if HSO is used.
*/
int16_t hElAngle; /**< @brief Electrical angle used for reference frame transformation.
*
* @note This field does not exists if HSO is used.
*/
uint16_t hCodeError; /**< @brief Error Code.
*
* @note This field does not exists if HSO is used.
*/
CurrRefSource_t bDriveInput; /**< @brief Specifies whether the current reference source must be
* #INTERNAL or #EXTERNAL.
*
* @note This field does not exists if HSO is used.
*/
} FOCVars_t, *pFOCVars_t;
/**
* @brief 6step variables structure.
*/
typedef struct
{
uint16_t DutyCycleRef; /**< @brief Reference speed. */
uint16_t hCodeError; /**< @brief error message. */
CurrRefSource_t bDriveInput; /**< @brief It specifies whether the current reference source must be
* #INTERNAL or #EXTERNAL. */
int16_t qElAngle;
} SixStepVars_t, *pSixStepVars_t;
/**
* @brief Low side or enabling signal definition.
*/
typedef enum
{
LS_DISABLED = 0x0U, /**< @brief Low side signals and enabling signals always off.
It is equivalent to DISABLED. */
LS_PWM_TIMER = 0x1U, /**< @brief Low side PWM signals are generated by timer.
It is equivalent to ENABLED. */
ES_GPIO = 0x2U /**< @brief Enabling signals are managed by GPIOs (L6230 mode). */
} LowSideOutputsFunction_t;
/** @name UserInterface related exported definitions. */
/** @{ */
#define OPT_NONE 0x00 /**< @brief No UI option selected. */
#define OPT_COM 0x02 /**< @brief Bit field indicating that the UI uses serial communication. */
#define OPT_DAC 0x04 /**< @brief Bit field indicating that the UI uses real DAC. */
#define OPT_DACT 0x08 /**< @brief Bit field indicating that the UI uses RC Timer DAC. */
#define OPT_DACS 0x10 /**< @brief Bit field indicating that the UI uses SPI communication. */
#define OPT_DACF3 0x40 /**< @brief Bit field indicating that the UI uses DAC for STM32F3. */
#define OPT_DACF072 0x80 /**< @brief Bit field indicating that the UI uses DAC for STM32F072. */
/** @} */
#define MAIN_SCFG_POS (28)
#define AUX_SCFG_POS (24)
#define MAIN_SCFG_VALUE(x) (((x)>>MAIN_SCFG_POS)& ( uint8_t )0x0F)
#define AUX_SCFG_VALUE(x) (((x)>>AUX_SCFG_POS)& ( uint8_t )0x0F)
/** @name PFC related exported definitions */
/** @{ */
#define PFC_SWE 0x0001U /**< @brief PFC Software error. */
#define PFC_HW_PROT 0x0002U /**< @brief PFC hardware protection. */
#define PFC_SW_OVER_VOLT 0x0004U /**< @brief PFC software over voltage. */
#define PFC_SW_OVER_CURRENT 0x0008U /**< @brief PFC software over current. */
#define PFC_SW_MAINS_FREQ 0x0010U /**< @brief PFC mains frequency error. */
#define PFC_SW_MAIN_VOLT 0x0020U /**< @brief PFC mains voltage error. */
/** @} */
/** @name Definitions exported for the DAC channel used as reference for protection. */
/** @{ */
#define AO_DISABLED 0x00U /**< @brief Analog output disabled. */
#define AO_DEBUG 0x01U /**< @brief Analog output debug. */
#define VREF_OCPM1 0x02U /**< @brief Voltage reference for over current protection of motor 1. */
#define VREF_OCPM2 0x03U /**< @brief Voltage reference for over current protection of motor 2. */
#define VREF_OCPM12 0x04U /**< @brief Voltage reference for over current protection of both motors. */
#define VREF_OVPM12 0x05U /**< @brief Voltage reference for over voltage protection of both motors. */
/** @} */
/** @name ADC channel number definitions */
/** @{ */
#define MC_ADC_CHANNEL_0 0
#define MC_ADC_CHANNEL_1 1
#define MC_ADC_CHANNEL_2 2
#define MC_ADC_CHANNEL_3 3
#define MC_ADC_CHANNEL_4 4
#define MC_ADC_CHANNEL_5 5
#define MC_ADC_CHANNEL_6 6
#define MC_ADC_CHANNEL_7 7
#define MC_ADC_CHANNEL_8 8
#define MC_ADC_CHANNEL_9 9
#define MC_ADC_CHANNEL_10 10
#define MC_ADC_CHANNEL_11 11
#define MC_ADC_CHANNEL_12 12
#define MC_ADC_CHANNEL_13 13
#define MC_ADC_CHANNEL_14 14
#define MC_ADC_CHANNEL_15 15
#define MC_ADC_CHANNEL_16 16
#define MC_ADC_CHANNEL_17 17
#define MC_ADC_CHANNEL_18 18
#define MC_ADC_CHANNEL_19 19
#define MC_ADC_CHANNEL_20 20
#define MC_ADC_CHANNEL_21 21
#define MC_ADC_CHANNEL_22 22
/** @} */
/** @name Utility macros definitions */
/** @{ */
#define RPM2MEC01HZ(rpm) (int16_t)((int32_t)(rpm)/6)
#define MAX(a,b) (((a)>(b))?(a):(b))
/** @} */
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* MC_TYPE_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 15,166 |
C
| 33.707094 | 130 | 0.551826 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/aspep.h
|
/**
******************************************************************************
* @file aspep.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides aspep API that implement the aspep protocol
*
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef ASPEP_H
#define ASPEP_H
#include "parameters_conversion.h"
#include "mcptl.h"
#define ASPEP_CTRL ((uint8_t)0) /* Beacon, Nack, or Ping*/
#define ASPEP_OK ((uint8_t)0)
#define ASPEP_SYNC_NOT_EXPECTED 1
#define ASPEP_NOT_CONNECTED 2
#define ASPEP_BUFFER_ERROR 3
#define ASPEP_BAD_PACKET_TYPE 1
#define ASPEP_BAD_PACKET_SIZE 2
#define ASPEP_BAD_CRC_HEADER 4
#define ASPEP_BAD_CRC_DATA 5
#define ASPEP_PING_RESET 0
#define ASPEP_PING_CFG 1
#define ASPEP_HEADER_SIZE 4
#define ASPEP_CTRL_SIZE 4
#define ASPEP_DATACRC_SIZE 2U
#define ID_MASK ((uint32_t)0xF)
#define DATA_PACKET ((uint32_t)0x9)
#define PING ((uint32_t)0x6)
#define BEACON ((uint32_t)0x5)
#define NACK ((uint32_t)0xF)
#define ACK ((uint32_t)0xA)
typedef uint32_t ASPEP_packetType;
typedef bool (*ASPEP_send_cb_t) (void *pHW_Handle, void *txbuffer, uint16_t length);
typedef void (*ASPEP_receive_cb_t) (void *pHW_Handle, void *rxbuffer, uint16_t length);
typedef void (*ASPEP_hwinit_cb_t) (void *pHW_Handle);
typedef void (*ASPEP_hwsync_cb_t) (void *pHW_Handle);
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MCP
* @{
*/
/**
* @brief ASPEP State Machine Type.
*/
typedef enum
{
ASPEP_IDLE,
ASPEP_CONFIGURED,
ASPEP_CONNECTED,
} ASPEP_sm_type;
/**
* @brief ASPEP Transport Layer State Machine Type.
*/
typedef enum
{
WAITING_PACKET,
WAITING_PAYLOAD,
} ASPEP_TL_sm_type;
/**
* @brief ASPEP Control Buffer structure.
*/
typedef struct
{
uint8_t buffer[ASPEP_HEADER_SIZE];
buff_access_t state;
} ASPEP_ctrlBuff_t;
/**
* @brief ASPEP communication capabilities.
*
* Minimum between Controller and Performer capabilities.
*/
typedef struct
{
uint8_t DATA_CRC;
uint8_t RX_maxSize;
uint8_t TXS_maxSize;
uint8_t TXA_maxSize;
uint8_t version;
} ASPEP_Capabilities_def;
/**
* @brief Handle structure for ASPEP related components.
*/
typedef struct
{
MCTL_Handle_t _Super; /** Transport Layer component handle */
void *HWIp; /** Hardware components chosen for communication */
uint8_t *rxBuffer; /** Contains the ASPEP Data payload */
uint8_t rxHeader[4]; /** Contains the ASPEP 32 bits header */
ASPEP_ctrlBuff_t ctrlBuffer; /** ASPEP protocol control buffer */
MCTL_Buff_t syncBuffer; /** Buffer used for synchronous communication */
MCTL_Buff_t asyncBufferA; /** First buffer used for asynchronous communication */
MCTL_Buff_t asyncBufferB; /** Second buffer used for asynchronous communication */
MCTL_Buff_t *lastRequestedAsyncBuff; /** Last buffer requested for asynchronous communication */
MCTL_Buff_t *asyncNextBuffer; /** Next buffer that will be transmitted by asynchronous communication */
void *lockBuffer; /** Buffer locked to avoid erasing data not yet transmitted */
ASPEP_hwinit_cb_t fASPEP_HWInit; /** Pointer to the initialization function */
ASPEP_hwsync_cb_t fASPEP_HWSync; /** Pointer to the starting function */
ASPEP_receive_cb_t fASPEP_receive; /** Pointer to the receiving packet function */
ASPEP_send_cb_t fASPEP_send; /** Pointer to the sending packet function */
uint16_t rxLength; /** Length of the received data packet : payload and header */
uint16_t maxRXPayload; /** Maximum payload size the performer can process */
uint8_t syncPacketCount; /** Reset at startup only, this counter is incremented at each valid data packet received from controller */
bool NewPacketAvailable; /** Boolean stating if performer is ready to receive a new packet or not */
uint8_t badPacketFlag; /** Contains the error code in case of ASPEP decoding issue */
uint8_t liid;
ASPEP_sm_type ASPEP_State; /** ASPEP State of the communication between performer and controller */
ASPEP_TL_sm_type ASPEP_TL_State; /** Transport Layer state of the communication between performer and controller */
ASPEP_packetType rxPacketType; /** Type of the received packet */
ASPEP_Capabilities_def Capabilities; /** Minimum between Controller and Performer capabilities */
} ASPEP_Handle_t;
void ASPEP_start(ASPEP_Handle_t *pHandle);
/* MCTL (Motor Control Transport Layer) API */
bool ASPEP_getBuffer(MCTL_Handle_t *pHandle, void **buffer, uint8_t syncAsync);
uint8_t ASPEP_sendPacket(MCTL_Handle_t *pHandle, void *txBuffer, uint16_t txDataLength, uint8_t syncAsync);
uint8_t *ASPEP_RXframeProcess(MCTL_Handle_t *pHandle, uint16_t *packetLength);
/* */
void ASPEP_HWDataReceivedIT(ASPEP_Handle_t *pHandle);
void ASPEP_HWDataTransmittedIT(ASPEP_Handle_t *pHandle);
/* Debugger stuff */
void ASPEP_HWDMAReset(ASPEP_Handle_t *pHandle);
#endif /* ASPEP_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 6,017 |
C
| 35.695122 | 151 | 0.614924 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_configuration_registers.h
|
/**
******************************************************************************
* @file mc_configuration_registers.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides the definitions needed to build the project
* configuration information registers.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MC_CONFIGURATION_REGISTERS_H
#define MC_CONFIGURATION_REGISTERS_H
#include "mc_type.h"
typedef struct
{
uint32_t SDKVersion;
uint8_t MotorNumber;
uint8_t MCP_Flag;
uint8_t MCPA_UARTA_LOG;
uint8_t MCPA_UARTB_LOG;
uint8_t MCPA_STLNK_LOG;
uint8_t Padding;
} __attribute__ ((packed)) GlobalConfig_reg_t;
typedef struct
{
float_t polePairs;
float_t ratedFlux;
float_t rs;
float_t rsSkinFactor;
float_t ls;
float_t ld;
float_t maxCurrent;
float_t mass_copper_kg;
float_t cooling_tau_s;
char_t name[24];
} __attribute__ ((packed)) MotorConfig_reg_t;
typedef struct
{
uint32_t maxMechanicalSpeed;
float_t maxReadableCurrent;
float_t nominalCurrent;
uint16_t nominalVoltage;
uint8_t driveType;
uint8_t padding;
} __attribute__ ((packed)) ApplicationConfig_reg_t;
typedef struct
{
uint8_t primarySensor;
uint8_t auxiliarySensor;
uint8_t topology;
uint8_t FOCRate;
uint32_t PWMFrequency;
uint16_t MediumFrequency;
uint16_t configurationFlag1;
uint16_t configurationFlag2;
} __attribute__ ((packed)) FOCFwConfig_reg_t;
#define ENO_SENSOR 0
#define EPLL 1
#define ECORDIC 2
#define EENCODER 3
#define EHALL 4
#define EHSO 5
#define EZEST 6
#define SDK_VERSION_MAIN (0x6) /*!< [31:24] main version */
#define SDK_VERSION_SUB1 (0x2) /*!< [23:16] sub1 version */
#define SDK_VERSION_SUB2 (0x0) /*!< [15:8] sub2 version */
#define SDK_VERSION_RC (0x0) /*!< [7:0] release candidate */
#define SDK_VERSION ((SDK_VERSION_MAIN << 24U)\
|(SDK_VERSION_SUB1 << 16U)\
|(SDK_VERSION_SUB2 << 8U )\
|(SDK_VERSION_RC))
/* configurationFlag1 definition */
#define FLUX_WEAKENING_FLAG (1U)
#define FEED_FORWARD_FLAG (1U << 1U)
#define MTPA_FLAG (1U << 2U)
#define PFC_FLAG (1U << 3U)
#define ICL_FLAG (1U << 4U)
#define RESISTIVE_BREAK_FLAG (1U << 5U)
#define OCP_DISABLE_FLAG (1U << 6U)
#define STGAP_FLAG (1U << 7U)
#define POSITION_CTRL_FLAG (1U << 8U)
#define VBUS_SENSING_FLAG (1U << 9U)
#define TEMP_SENSING_FLAG (1U << 10U)
#define VOLTAGE_SENSING_FLAG (1U << 11U)
#define FLASH_CONFIG_FLAG (1U << 12U)
#define DAC_CH1_FLAG (1U << 13U)
#define DAC_CH2_FLAG (1U << 14U)
#define OTF_STARTUP_FLAG (1U << 15U)
/* configurationFlag2 definition */
#define OVERMODULATION_FLAG (1U)
#define DISCONTINUOUS_PWM_FLAG (1U << 1U)
#define PROFILER_FLAG (1U << 13U)
#define DBG_MCU_LOAD_MEASURE_FLAG (1U << 14U)
#define DBG_OPEN_LOOP_FLAG (1U << 15U)
/* MCP_Flag definition */
#define FLAG_MCP_OVER_STLINK 0U
#define FLAG_MCP_OVER_UARTA (1U << 1U)
#define FLAG_MCP_OVER_UARTB 0U
#define configurationFlag1_M1 (VBUS_SENSING_FLAG)
#define configurationFlag2_M1 (0U)
#define DRIVE_TYPE_M1 0
#define PRIM_SENSOR_M1 EENCODER
#define AUX_SENSOR_M1 EPLL
#define TOPOLOGY_M1 0
#define FOC_RATE_M1 1
#define PWM_FREQ_M1 16000
extern const char_t FIRMWARE_NAME[]; //cstat !MISRAC2012-Rule-18.8 !MISRAC2012-Rule-8.11
extern const char_t CTL_BOARD[]; //cstat !MISRAC2012-Rule-18.8 !MISRAC2012-Rule-8.11
extern const char_t *PWR_BOARD_NAME[NBR_OF_MOTORS];
extern const char_t *MOTOR_NAME[NBR_OF_MOTORS];
extern const GlobalConfig_reg_t globalConfig_reg;
extern const FOCFwConfig_reg_t *FOCConfig_reg[NBR_OF_MOTORS];
extern const MotorConfig_reg_t *MotorConfig_reg[NBR_OF_MOTORS];
extern const ApplicationConfig_reg_t *ApplicationConfig_reg[NBR_OF_MOTORS];
#endif /* MC_CONFIGURATION_REGISTERS_H */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 4,871 |
C
| 33.309859 | 88 | 0.583658 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/regular_conversion_manager.h
|
/**
******************************************************************************
* @file regular_conversion_manager.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains all definitions and functions prototypes for the
* regular_conversion_manager component of the Motor Control SDK.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef REGULAR_CONVERSION_MANAGER_H
#define REGULAR_CONVERSION_MANAGER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup RCM
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief RegConv_t contains all the parameters required to execute a regular conversion
*
* it is used by all regular_conversion_manager's client
*
*/
typedef struct
{
ADC_TypeDef *regADC;
uint8_t channel;
uint32_t samplingTime;
uint8_t convHandle; /*!< handler to the regular conversion */
} RegConv_t;
/**
* @brief Conversion states
*/
typedef enum
{
RCM_USERCONV_IDLE, /**< @brief No conversion currently scheduled. */
RCM_USERCONV_REQUESTED, /**< @brief A conversion is scheduled for execution. */
RCM_USERCONV_EOC /**< @brief A conversion has completed and the value is ready. */
}RCM_UserConvState_t;
typedef void (*RCM_exec_cb_t)(RegConv_t *regConv, uint16_t data, void *UserData);
/* Exported functions ------------------------------------------------------- */
/* Function used to register a regular conversion */
void RCM_RegisterRegConv(RegConv_t *regConv);
/* Function used to register a regular conversion with a callback attached*/
void RCM_RegisterRegConv_WithCB(RegConv_t *regConv, RCM_exec_cb_t fctCB, void *data);
/* Function used to execute an already registered regular conversion */
uint16_t RCM_ExecRegularConv(RegConv_t *regConv);
/* select the handle conversion to be executed during the next call to RCM_ExecUserConv */
bool RCM_RequestUserConv(RegConv_t *regConv);
/* Return the latest user conversion value */
uint16_t RCM_GetUserConv(void);
/* Must be called by MC_TASK only to grantee proper scheduling */
void RCM_ExecUserConv(void);
/* return the state of the user conversion state machine*/
RCM_UserConvState_t RCM_GetUserConvState(void);
/* Function used to un-schedule a regular conversion exectuted after current sampling in HF task */
bool RCM_PauseRegularConv(RegConv_t *regConv);
/* Non blocking function to start conversion inside HF task */
void RCM_ExecNextConv(void);
/* Non blocking function used to read back already started regular conversion */
void RCM_ReadOngoingConv(void);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* REGULAR_CONVERSION_MANAGER_H */
/************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 3,579 |
C
| 29.862069 | 99 | 0.6038 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_stm_types.h
|
/**
******************************************************************************
* @file mc_stm_types.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief Includes HAL/LL headers relevant to the current configuration.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MC_STM_TYPES_H
#define MC_STM_TYPES_H
#ifdef FULL_MISRA_C_COMPLIANCY
#define FULL_MISRA_C_COMPLIANCY_ENC_SPD_POS
#define FULL_MISRA_C_COMPLIANCY_FWD_FDB
#define FULL_MISRA_C_COMPLIANCY_FLUX_WEAK
#define FULL_MISRA_C_COMPLIANCY_MAX_TOR
#define FULL_MISRA_C_COMPLIANCY_MC_MATH
#define FULL_MISRA_C_COMPLIANCY_NTC_TEMP
#define FULL_MISRA_C_COMPLIANCY_PID_REGULATOR
#define FULL_MISRA_C_COMPLIANCY_PFC
#define FULL_MISRA_C_COMPLIANCY_PWM_CURR
#define FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM
#define FULL_MISRA_C_COMPLIANCY_SPD_TORQ_CTRL
#define FULL_MISRA_C_COMPLIANCY_STO_CORDIC
#define FULL_MISRA_C_COMPLIANCY_STO_PLL
#define FULL_MISRA_C_COMPLIANCY_VIRT_SPD_SENS
#endif
#ifdef NULL_PTR_CHECK
#define NULL_PTR_CHECK_ASP
#define NULL_PTR_CHECK_BUS_VOLT
#define NULL_PTR_CHECK_CRC_LIM
#define NULL_PTR_CHECK_DAC_UI
#define NULL_PTR_CHECK_DIG_OUT
#define NULL_PTR_CHECK_ENC_ALI_CTRL
#define NULL_PTR_CHECK_ENC_SPD_POS_FDB
#define NULL_PTR_CHECK_FEED_FWD_CTRL
#define NULL_PTR_CHECK_FLUX_WEAK
#define NULL_PTR_CHECK_HALL_SPD_POS_FDB
#define NULL_PTR_CHECK_MAX_TRQ_PER_AMP
#define NULL_PTR_CHECK_MCP
#define NULL_PTR_CHECK_MCPA
#define NULL_PTR_CHECK_MC_INT
#define NULL_PTR_CHECK_MC_PERF
#define NULL_PTR_CHECK_MOT_POW_MES
#define NULL_PTR_CHECK_NTC_TEMP_SENS
#define NULL_PTR_CHECK_OPEN_LOOP
#define NULL_PTR_CHECK_PID_REG
#define NULL_PTR_CHECK_POT
#define NULL_PTR_CHECK_POW_COM
#define NULL_PTR_CHECK_PQD_MOT_POW_MEAS
#define NULL_PTR_CHECK_PWR_CUR_FDB
#define NULL_PTR_CHECK_PWM_CUR_FDB_OVM
#define NULL_PTR_CHECK_RDIV_BUS_VLT_SNS
#define NULL_PTR_CHECK_REG_CON_MNG
#define NULL_PTR_CHECK_REG_INT
#define NULL_PTR_CHECK_REV_UP_CTL
#define NULL_PTR_CHECK_RMP_EXT_MNG
#define NULL_PTR_CHECK_R1_PS_PWR_CUR_FDB
#define NULL_PTR_CHECK_R3_2_PWM_CURR_FDB
#define NULL_PTR_CHECK_SPD_POS_FBK
#define NULL_PTR_CHECK_SPD_POT
#define NULL_PTR_CHECK_SPD_REG_POT
#define NULL_PTR_CHECK_SPD_TRQ_CTL
#define NULL_PTR_CHECK_STL_MNG
#define NULL_PTR_CHECK_STO_COR_SPD_POS_FDB
#define NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB
#define NULL_PTR_CHECK_USA_ASP_DRV
#define NULL_PTR_CHECK_VIR_SPD_SEN
#endif
#ifndef USE_FULL_LL_DRIVER
#define USE_FULL_LL_DRIVER
#endif
#include "stm32g4xx_ll_bus.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_system.h"
#include "stm32g4xx_ll_adc.h"
#include "stm32g4xx_ll_tim.h"
#include "stm32g4xx_ll_gpio.h"
#include "stm32g4xx_ll_usart.h"
#include "stm32g4xx_ll_dac.h"
#include "stm32g4xx_ll_dma.h"
#include "stm32g4xx_ll_comp.h"
#include "stm32g4xx_ll_opamp.h"
#include "stm32g4xx_ll_cordic.h"
/* Make this define visible for all projects */
#define NBR_OF_MOTORS 1
__STATIC_INLINE void LL_DMA_ClearFlag_TC(DMA_TypeDef *DMAx, uint32_t Channel)
{
if (NULL == DMAx)
{
/* Nothing to do */
}
else
{
/* Clear TC bits with bits position depending on parameter "Channel" */
WRITE_REG (DMAx->IFCR, DMA_IFCR_CTCIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2));
}
}
//cstat !MISRAC2012-Rule-8.13
__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC(DMA_TypeDef *DMAx, uint32_t Channel)
{
return ((NULL == DMAx) ? 0U : ((READ_BIT(DMAx->ISR,
(DMA_ISR_TCIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2))) == (DMA_ISR_TCIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2))) ?
1UL : 0UL));
}
//cstat !MISRAC2012-Rule-8.13
__STATIC_INLINE void LL_DMA_ClearFlag_HT(DMA_TypeDef *DMAx, uint32_t Channel)
{
if (NULL == DMAx)
{
/* Nothing to do */
}
else
{
/* Clear HT bits with bits position depending on parameter "Channel" */
WRITE_REG (DMAx->IFCR, DMA_IFCR_CHTIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2));
}
}
//cstat !MISRAC2012-Rule-8.13
__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT(DMA_TypeDef *DMAx, uint32_t Channel)
{
return ((NULL == DMAx) ? 0U : ((READ_BIT(DMAx->ISR,
(DMA_ISR_HTIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2))) == (DMA_ISR_HTIF1 << ((Channel-LL_DMA_CHANNEL_1)<<2))) ?
1UL : 0UL));
}
#define PIN_CONNECT (uint32_t)(0)
#define DIRECT_CONNECT (uint32_t)(OPAMP_CSR_OPAMPINTEN)
#define OPAMP_UNCHANGED (uint32_t)(0xFFFFFFFFUL)
/* #define ADC_INJ_TRIG_TIMER LL_ADC_INJ_TRIG_EXT_TIM1_TRGO */
/**
* @name Predefined Speed Units
*
* Each of the following symbols defines a rotation speed unit that can be used by the
* functions of the API for their speed parameter. Each Unit is defined by expressing
* the value of 1 Hz in this unit.
*
* These symbols can be used to set the #SPEED_UNIT macro which defines the rotation speed
* unit used by the functions of the API.
*
* @anchor SpeedUnit
*/
/** @{ */
/** Revolutions Per Minute: 1 Hz is 60 RPM */
#define U_RPM 60
/** Tenth of Hertz: 1 Hz is 10 01Hz */
#define U_01HZ 10
/* Hundreth of Hertz: 1 Hz is 100 001Hz */
/* #define _001HZ 100 */
/** @} */
/* USER CODE BEGIN DEFINITIONS */
/* Definitions placed here will not be erased by code generation */
/**
* @brief Rotation speed unit used at the interface with the application
*
* This symbols defines the value of 1 Hertz in the unit used by the functions of the API for
* their speed parameters.
*
* For instance, if the chosen unit is the RPM, SPEED_UNIT is defined to 60, since 1 Hz is 60 RPM.
* The default unit is #U_01HZ, set on the initial generation of the project by the Workbench.
* As this symbol is defined in a User Section, custom values set by users persist across project
* regeneration.
*
* PID parameters computed by the Motor Control Workbench for speed regulation are
* suited for a speed in 01Hz. The motor control subsystem internally scales them to adapt to the
* actual speed unit.
*
* This symbol should not be set to a literal numeric value. Rather, it should be set to one
* of the symbols predefined for that purpose such as #U_RPM, #U_01HZ,... See @ref SpeedUnit for
* more details.
*
* Refer to the documentation of the @ref MCIAPI for the functions that use this unit.
*
* @{
*/
#define SPEED_UNIT U_01HZ
/* USER CODE END DEFINITIONS */
/*!< Convenient macro to convert user friendly RPM into SpeedUnit used by MC API */
#define RPM_2_SPEED_UNIT(rpm) ((int16_t)(((rpm)*SPEED_UNIT)/U_RPM))
/*!< Convenient macro to convert SpeedUnit used by MC API into user friendly RPM */
#define SPEED_UNIT_2_RPM(speed) ((int16_t)(((speed)*U_RPM)/SPEED_UNIT))
/**
* @}
*/
#endif /* MC_STM_TYPES_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 7,159 |
C
| 33.423077 | 118 | 0.680821 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_config.h
|
/**
******************************************************************************
* @file mc_config.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief Motor Control Subsystem components configuration and handler
* structures declarations.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MC_CONFIG_H
#define MC_CONFIG_H
#include "pid_regulator.h"
#include "speed_torq_ctrl.h"
#include "virtual_speed_sensor.h"
#include "ntc_temperature_sensor.h"
#include "revup_ctrl.h"
#include "pwm_curr_fdbk.h"
#include "mc_interface.h"
#include "mc_configuration_registers.h"
#include "regular_conversion_manager.h"
#include "r_divider_bus_voltage_sensor.h"
#include "virtual_bus_voltage_sensor.h"
#include "pqd_motor_power_measurement.h"
#include "r3_1_g4xx_pwm_curr_fdbk.h"
#include "encoder_speed_pos_fdbk.h"
#include "enc_align_ctrl.h"
#include "ramp_ext_mngr.h"
#include "circle_limitation.h"
#include "sto_speed_pos_fdbk.h"
#include "sto_pll_speed_pos_fdbk.h"
/* USER CODE BEGIN Additional include */
/* USER CODE END Additional include */
extern PID_Handle_t PIDSpeedHandle_M1;
extern PID_Handle_t PIDIqHandle_M1;
extern PID_Handle_t PIDIdHandle_M1;
extern NTC_Handle_t TempSensor_M1;
extern PWMC_R3_1_Handle_t PWM_Handle_M1;
extern SpeednTorqCtrl_Handle_t SpeednTorqCtrlM1;
extern PQD_MotorPowMeas_Handle_t PQD_MotorPowMeasM1;
extern PQD_MotorPowMeas_Handle_t *pPQD_MotorPowMeasM1;
extern VirtualSpeedSensor_Handle_t VirtualSpeedSensorM1;
extern STO_PLL_Handle_t STO_PLL_M1;
extern ENCODER_Handle_t ENCODER_M1;
extern EncAlign_Handle_t EncAlignCtrlM1;
extern RegConv_t VbusRegConv_M1;
extern RDivider_Handle_t BusVoltageSensor_M1;
extern CircleLimitation_Handle_t CircleLimitationM1;
extern RampExtMngr_Handle_t RampExtMngrHFParamsM1;
extern MCI_Handle_t Mci[NBR_OF_MOTORS];
extern SpeednTorqCtrl_Handle_t *pSTC[NBR_OF_MOTORS];
extern PID_Handle_t *pPIDIq[NBR_OF_MOTORS];
extern PID_Handle_t *pPIDId[NBR_OF_MOTORS];
extern NTC_Handle_t *pTemperatureSensor[NBR_OF_MOTORS];
extern PQD_MotorPowMeas_Handle_t *pMPM[NBR_OF_MOTORS];
extern MCI_Handle_t* pMCI[NBR_OF_MOTORS];
/* USER CODE BEGIN Additional extern */
/* USER CODE END Additional extern */
#endif /* MC_CONFIG_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 2,822 |
C
| 32.607142 | 80 | 0.675053 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/parameters_conversion.h
|
/**
******************************************************************************
* @file parameters_conversion.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file includes the proper Parameter conversion on the base
* of stdlib for the first drive
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PARAMETERS_CONVERSION_H
#define PARAMETERS_CONVERSION_H
#include "mc_math.h"
#include "parameters_conversion_g4xx.h"
#include "pmsm_motor_parameters.h"
#include "drive_parameters.h"
#include "power_stage_parameters.h"
/* Current conversion from Ampere unit to 16Bit Digit */
#define CURRENT_CONV_FACTOR (uint16_t)((65536.0 * RSHUNT * AMPLIFICATION_GAIN)/ADC_REFERENCE_VOLTAGE)
#define CURRENT_CONV_FACTOR_INV (1.0 / ((65536.0 * RSHUNT * AMPLIFICATION_GAIN) / ADC_REFERENCE_VOLTAGE))
/* Current conversion from Ampere unit to 16Bit Digit */
#define NOMINAL_CURRENT (NOMINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define ADC_REFERENCE_VOLTAGE 3.3
#define M1_MAX_READABLE_CURRENT (ADC_REFERENCE_VOLTAGE / (2 * RSHUNT * AMPLIFICATION_GAIN))
/************************* CONTROL FREQUENCIES & DELAIES **********************/
#define TF_REGULATION_RATE (uint32_t)((uint32_t)(PWM_FREQUENCY) / (REGULATION_EXECUTION_RATE))
/* TF_REGULATION_RATE_SCALED is TF_REGULATION_RATE divided by PWM_FREQ_SCALING to allow more dynamic */
#define TF_REGULATION_RATE_SCALED (uint16_t)((uint32_t)(PWM_FREQUENCY) / (REGULATION_EXECUTION_RATE\
* PWM_FREQ_SCALING))
/* DPP_CONV_FACTOR is introduce to compute the right DPP with TF_REGULATOR_SCALED */
#define DPP_CONV_FACTOR (65536 / PWM_FREQ_SCALING)
/* Current conversion from Ampere unit to 16Bit Digit */
#define ID_DEMAG (ID_DEMAG_A * CURRENT_CONV_FACTOR)
#define IQMAX (IQMAX_A * CURRENT_CONV_FACTOR)
#define DEFAULT_TORQUE_COMPONENT (DEFAULT_TORQUE_COMPONENT_A * CURRENT_CONV_FACTOR)
#define DEFAULT_FLUX_COMPONENT (DEFAULT_FLUX_COMPONENT_A * CURRENT_CONV_FACTOR)
#define REP_COUNTER (uint16_t)((REGULATION_EXECUTION_RATE * 2u) - 1u)
#define SYS_TICK_FREQUENCY (uint16_t)2000
#define UI_TASK_FREQUENCY_HZ 10U
#define PHASE1_FINAL_CURRENT (PHASE1_FINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define PHASE2_FINAL_CURRENT (PHASE2_FINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define PHASE3_FINAL_CURRENT (PHASE3_FINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define PHASE4_FINAL_CURRENT (PHASE4_FINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define PHASE5_FINAL_CURRENT (PHASE5_FINAL_CURRENT_A * CURRENT_CONV_FACTOR)
#define MEDIUM_FREQUENCY_TASK_RATE (uint16_t)SPEED_LOOP_FREQUENCY_HZ
#define MF_TASK_OCCURENCE_TICKS (SYS_TICK_FREQUENCY / SPEED_LOOP_FREQUENCY_HZ) - 1u
#define UI_TASK_OCCURENCE_TICKS (SYS_TICK_FREQUENCY / UI_TASK_FREQUENCY_HZ) - 1u
#define SERIALCOM_TIMEOUT_OCCURENCE_TICKS (SYS_TICK_FREQUENCY / SERIAL_COM_TIMEOUT_INVERSE) - 1u
#define SERIALCOM_ATR_TIME_TICKS (uint16_t)(((SYS_TICK_FREQUENCY * SERIAL_COM_ATR_TIME_MS) / 1000u) - 1u)
/************************* COMMON OBSERVER PARAMETERS **************************/
#define MAX_BEMF_VOLTAGE (uint16_t)((MAX_APPLICATION_SPEED_RPM * 1.2 *\
MOTOR_VOLTAGE_CONSTANT * SQRT_2) / (1000u * SQRT_3))
/*max phase voltage, 0-peak Volts*/
#define MAX_VOLTAGE (int16_t)((ADC_REFERENCE_VOLTAGE / SQRT_3) / VBUS_PARTITIONING_FACTOR)
#define MAX_CURRENT (ADC_REFERENCE_VOLTAGE / (2 * RSHUNT * AMPLIFICATION_GAIN))
#define OBS_MINIMUM_SPEED_UNIT (uint16_t)((OBS_MINIMUM_SPEED_RPM * SPEED_UNIT) / U_RPM)
#define MAX_APPLICATION_SPEED_UNIT ((MAX_APPLICATION_SPEED_RPM * SPEED_UNIT) / U_RPM)
#define MIN_APPLICATION_SPEED_UNIT ((MIN_APPLICATION_SPEED_RPM * SPEED_UNIT) / U_RPM)
/************************* PLL PARAMETERS **************************/
#define C1 (int32_t)((((int16_t)F1) * RS) / (LS * TF_REGULATION_RATE))
#define C2 (int32_t)GAIN1
#define C3 (int32_t)((((int16_t)F1) * MAX_BEMF_VOLTAGE) / (LS * MAX_CURRENT * TF_REGULATION_RATE))
#define C4 (int32_t)GAIN2
#define C5 (int32_t)((((int16_t)F1) * MAX_VOLTAGE) / (LS * MAX_CURRENT * TF_REGULATION_RATE))
#define PERCENTAGE_FACTOR (uint16_t)(VARIANCE_THRESHOLD*128u)
#define HFI_MINIMUM_SPEED (uint16_t) (HFI_MINIMUM_SPEED_RPM/6u)
#define MAX_APPLICATION_SPEED_UNIT2 ((MAX_APPLICATION_SPEED_RPM2 * SPEED_UNIT) / U_RPM)
#define MIN_APPLICATION_SPEED_UNIT2 ((MIN_APPLICATION_SPEED_RPM2 * SPEED_UNIT) / U_RPM)
/************************** VOLTAGE CONVERSIONS Motor 1 *************************/
#define OVERVOLTAGE_THRESHOLD_d (uint16_t)(OV_VOLTAGE_THRESHOLD_V * 65535 /\
(ADC_REFERENCE_VOLTAGE / VBUS_PARTITIONING_FACTOR))
#define OVERVOLTAGE_THRESHOLD_LOW_d (uint16_t)(OV_VOLTAGE_THRESHOLD_V * 65535 /\
(ADC_REFERENCE_VOLTAGE / VBUS_PARTITIONING_FACTOR))
#define UNDERVOLTAGE_THRESHOLD_d (uint16_t)((UD_VOLTAGE_THRESHOLD_V * 65535) /\
((uint16_t)(ADC_REFERENCE_VOLTAGE / VBUS_PARTITIONING_FACTOR)))
#define INT_SUPPLY_VOLTAGE (uint16_t)(65536 / ADC_REFERENCE_VOLTAGE)
#define DELTA_TEMP_THRESHOLD (OV_TEMPERATURE_THRESHOLD_C - T0_C)
#define DELTA_V_THRESHOLD (dV_dT * DELTA_TEMP_THRESHOLD)
#define OV_TEMPERATURE_THRESHOLD_d ((V0_V + DELTA_V_THRESHOLD) * INT_SUPPLY_VOLTAGE)
#define DELTA_TEMP_HYSTERESIS (OV_TEMPERATURE_HYSTERESIS_C)
#define DELTA_V_HYSTERESIS (dV_dT * DELTA_TEMP_HYSTERESIS)
#define OV_TEMPERATURE_HYSTERESIS_d (DELTA_V_HYSTERESIS * INT_SUPPLY_VOLTAGE)
#define ALIGNMENT_ANGLE_S16 (int16_t)(M1_ALIGNMENT_ANGLE_DEG * 65536u / 360u)
#define FINAL_I_ALIGNMENT (uint16_t)(FINAL_I_ALIGNMENT_A * CURRENT_CONV_FACTOR)
/*************** Timer for PWM generation & currenst sensing parameters ******/
#define PWM_PERIOD_CYCLES (uint16_t)(((uint32_t)ADV_TIM_CLK_MHz * (uint32_t)1000000u\
/ ((uint32_t)(PWM_FREQUENCY))) & (uint16_t)0xFFFE)
#define DEADTIME_NS SW_DEADTIME_NS
#define DEAD_TIME_ADV_TIM_CLK_MHz (ADV_TIM_CLK_MHz * TIM_CLOCK_DIVIDER)
#define DEAD_TIME_COUNTS_1 (DEAD_TIME_ADV_TIM_CLK_MHz * DEADTIME_NS / 1000uL)
#if (DEAD_TIME_COUNTS_1 <= 255)
#define DEAD_TIME_COUNTS (uint16_t)DEAD_TIME_COUNTS_1
#elif (DEAD_TIME_COUNTS_1 <= 508)
#define DEAD_TIME_COUNTS (uint16_t)(((DEAD_TIME_ADV_TIM_CLK_MHz * DEADTIME_NS/2) /1000uL) + 128)
#elif (DEAD_TIME_COUNTS_1 <= 1008)
#define DEAD_TIME_COUNTS (uint16_t)(((DEAD_TIME_ADV_TIM_CLK_MHz * DEADTIME_NS/8) /1000uL) + 320)
#elif (DEAD_TIME_COUNTS_1 <= 2015)
#define DEAD_TIME_COUNTS (uint16_t)(((DEAD_TIME_ADV_TIM_CLK_MHz * DEADTIME_NS/16) /1000uL) + 384)
#else
#define DEAD_TIME_COUNTS 510
#endif
#define DTCOMPCNT (uint16_t)((DEADTIME_NS * ADV_TIM_CLK_MHz) / 2000)
#define TON_NS 500
#define TOFF_NS 500
#define TON (uint16_t)((TON_NS * ADV_TIM_CLK_MHz) / 2000)
#define TOFF (uint16_t)((TOFF_NS * ADV_TIM_CLK_MHz) / 2000)
/**********************/
/* MOTOR 1 ADC Timing */
/**********************/
/* In ADV_TIMER CLK cycles*/
#define SAMPLING_TIME ((ADC_SAMPLING_CYCLES * ADV_TIM_CLK_MHz) / ADC_CLK_MHz)
#define TRISE ((TRISE_NS * ADV_TIM_CLK_MHz)/1000uL)
#define TDEAD ((uint16_t)((DEADTIME_NS * ADV_TIM_CLK_MHz)/1000))
#define TNOISE ((uint16_t)((TNOISE_NS*ADV_TIM_CLK_MHz)/1000))
#define HTMIN 1 /* Required for main.c compilation only, CCR4 is overwritten at runtime */
#define TW_AFTER ((uint16_t)(((DEADTIME_NS+MAX_TNTR_NS)*ADV_TIM_CLK_MHz)/1000UL))
#define MAX_TWAIT ((uint16_t)((TW_AFTER - SAMPLING_TIME)/2))
#define TW_BEFORE ((uint16_t)((ADC_TRIG_CONV_LATENCY_CYCLES + ADC_SAMPLING_CYCLES) * ADV_TIM_CLK_MHz) / ADC_CLK_MHz + 1u)
#define TW_BEFORE_R3_1 ((uint16_t)((ADC_TRIG_CONV_LATENCY_CYCLES + ADC_SAMPLING_CYCLES*2 + ADC_SAR_CYCLES) * ADV_TIM_CLK_MHz) / ADC_CLK_MHz + 1u)
/* USER CODE BEGIN temperature */
#define M1_VIRTUAL_HEAT_SINK_TEMPERATURE_VALUE 25u
#define M1_TEMP_SW_FILTER_BW_FACTOR 250u
/* USER CODE END temperature */
#define PQD_CONVERSION_FACTOR (float_t)(((1.732 * ADC_REFERENCE_VOLTAGE) /\
(RSHUNT * AMPLIFICATION_GAIN)) / 65536.0f)
/****** Prepares the UI configurations according the MCconfxx settings ********/
#define DAC_ENABLE
#define DAC_OP_ENABLE
/* Motor 1 settings */
#define FW_ENABLE
#define DIFFTERM_ENABLE
/* Sensors setting */
#define AUX_SCFG UI_SCODE_STO_PLL
#define MAIN_SCFG UI_SCODE_ENC
#define PLLTUNING_ENABLE
#define UI_CFGOPT_PFC_ENABLE
/*******************************************************************************
* UI configurations settings. It can be manually overwritten if special
* configuartion is required.
*******************************************************************************/
/* Specific options of UI */
#define UI_CONFIG_M1 (UI_CFGOPT_NONE DAC_OP_ENABLE FW_ENABLE DIFFTERM_ENABLE\
| (MAIN_SCFG << MAIN_SCFG_POS)\
| (AUX_SCFG << AUX_SCFG_POS)\
| UI_CFGOPT_SETIDINSPDMODE PLLTUNING_ENABLE UI_CFGOPT_PFC_ENABLE\
| UI_CFGOPT_PLLTUNING)
#define UI_CONFIG_M2
#define DIN_ACTIVE_LOW Bit_RESET
#define DIN_ACTIVE_HIGH Bit_SET
#define DOUT_ACTIVE_HIGH DOutputActiveHigh
#define DOUT_ACTIVE_LOW DOutputActiveLow
/********** AUXILIARY ENCODER TIMER MOTOR 1 *************/
#define M1_PULSE_NBR ((4 * (M1_ENCODER_PPR)) - 1)
#define M1_ENC_IC_FILTER_LL LL_TIM_IC_FILTER_FDIV16_N8
#define M1_ENC_IC_FILTER 12
#define SPD_TIM_M1_IRQHandler TIM2_IRQHandler
#define LPF_FILT_CONST ((int16_t)(32767 * 0.5))
/* MMI Table Motor 1 MAX_MODULATION_100_PER_CENT */
#define MAX_MODULE (uint16_t)((100* 32767)/100)
#define SAMPLING_CYCLE_CORRECTION 0.5 /* Add half cycle required by STM32G474RETx ADC */
#define LL_ADC_SAMPLINGTIME_1CYCLES_5 LL_ADC_SAMPLINGTIME_1CYCLE_5
//cstat !MISRAC2012-Rule-20.10 !DEFINE-hash-multiple
#define LL_ADC_SAMPLING_CYCLE(CYCLE) LL_ADC_SAMPLINGTIME_ ## CYCLE ## CYCLES_5
#endif /*PARAMETERS_CONVERSION_H*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 12,247 |
C
| 52.021645 | 146 | 0.558912 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/parameters_conversion_g4xx.h
|
/**
******************************************************************************
* @file parameters_conversion_g4xx.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains the definitions needed to convert MC SDK parameters
* so as to target the STM32G4 Family.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PARAMETERS_CONVERSION_G4XX_H
#define PARAMETERS_CONVERSION_G4XX_H
#include "drive_parameters.h"
#include "power_stage_parameters.h"
#include "mc_math.h"
/************************* CPU & ADC PERIPHERAL CLOCK CONFIG ******************/
#define SYSCLK_FREQ 170000000uL
#define TIM_CLOCK_DIVIDER 1
#define ADV_TIM_CLK_MHz 170 /* Actual TIM clk including Timer clock divider*/
#define ADC_CLK_MHz 42
#define HALL_TIM_CLK 170000000uL
#define APB1TIM_FREQ 170000000uL
/************************* IRQ Handler Mapping *********************/
#define TIMx_UP_M1_IRQHandler TIM1_UP_TIM16_IRQHandler
#define TIMx_BRK_M1_IRQHandler TIM1_BRK_TIM15_IRQHandler
#define ADC_TRIG_CONV_LATENCY_CYCLES 3.5
#define ADC_SAR_CYCLES 12.5
#define M1_VBUS_SW_FILTER_BW_FACTOR 6u
#define OPAMP1_InvertingInput_PC5 LL_OPAMP_INPUT_INVERT_IO0
#define OPAMP1_InvertingInput_PA3 LL_OPAMP_INPUT_INVERT_IO1
#define OPAMP1_InvertingInput_PGA LL_OPAMP_INPUT_INVERT_CONNECT_NO
#define OPAMP1_InvertingInput_FOLLOWER LL_OPAMP_MODE_FOLLOWER
#define OPAMP2_InvertingInput_PC5 LL_OPAMP_INPUT_INVERT_IO0
#define OPAMP2_InvertingInput_PA5 LL_OPAMP_INPUT_INVERT_IO1
#define OPAMP2_InvertingInput_PGA LL_OPAMP_INPUT_INVERT_CONNECT_NO
#define OPAMP2_InvertingInput_FOLLOWER LL_OPAMP_MODE_FOLLOWER
#define OPAMP3_InvertingInput_PB10 LL_OPAMP_INPUT_INVERT_IO0
#define OPAMP3_InvertingInput_PB2 LL_OPAMP_INPUT_INVERT_IO1
#define OPAMP3_InvertingInput_PGA LL_OPAMP_INPUT_INVERT_CONNECT_NO
#define OPAMP3_InvertingInput_FOLLOWER LL_OPAMP_MODE_FOLLOWER
#define OPAMP4_InvertingInput_PB10 LL_OPAMP_INPUT_INVERT_IO0
#define OPAMP4_InvertingInput_PD8 LL_OPAMP_INPUT_INVERT_IO1
#define OPAMP4_InvertingInput_PGA LL_OPAMP_INPUT_INVERT_CONNECT_NO
#define OPAMP4_InvertingInput_FOLLOWER LL_OPAMP_MODE_FOLLOWER
#define OPAMP1_NonInvertingInput_PA1 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP1_NonInvertingInput_PA3 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP1_NonInvertingInput_PA7 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP2_NonInvertingInput_PA7 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP2_NonInvertingInput_PB14 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP2_NonInvertingInput_PB0 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP2_NonInvertingInput_PD14 LL_OPAMP_INPUT_NONINVERT_IO3
#define OPAMP3_NonInvertingInput_PB0 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP3_NonInvertingInput_PB13 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP3_NonInvertingInput_PA1 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP4_NonInvertingInput_PB13 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP4_NonInvertingInput_PD11 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP4_NonInvertingInput_PB11 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP5_NonInvertingInput_PB14 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP5_NonInvertingInput_PD12 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP5_NonInvertingInput_PC3 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP6_NonInvertingInput_PB12 LL_OPAMP_INPUT_NONINVERT_IO0
#define OPAMP6_NonInvertingInput_PD9 LL_OPAMP_INPUT_NONINVERT_IO1
#define OPAMP6_NonInvertingInput_PB13 LL_OPAMP_INPUT_NONINVERT_IO2
#define OPAMP1_PGAConnect_PC5 OPAMP_CSR_PGGAIN_3
#define OPAMP1_PGAConnect_PA3 (OPAMP_CSR_PGGAIN_3|OPAMP_CSR_PGGAIN_2)
#define OPAMP2_PGAConnect_PC5 OPAMP_CSR_PGGAIN_3
#define OPAMP2_PGAConnect_PA5 (OPAMP_CSR_PGGAIN_3|OPAMP_CSR_PGGAIN_2)
#define OPAMP3_PGAConnect_PB10 OPAMP_CSR_PGGAIN_3
#define OPAMP3_PGAConnect_PB2 (OPAMP_CSR_PGGAIN_3|OPAMP_CSR_PGGAIN_2)
#define OPAMP4_PGAConnect_PB10 OPAMP_CSR_PGGAIN_3
#define OPAMP4_PGAConnect_PD8 (OPAMP_CSR_PGGAIN_3|OPAMP_CSR_PGGAIN_2)
#define COMP1_InvertingInput_PA0 LL_COMP_INPUT_MINUS_IO1
#define COMP2_InvertingInput_PA2 LL_COMP_INPUT_MINUS_IO1
#define COMP3_InvertingInput_PD15 LL_COMP_INPUT_MINUS_IO1
#define COMP3_InvertingInput_PB12 LL_COMP_INPUT_MINUS_IO2
#define COMP4_InvertingInput_PE8 LL_COMP_INPUT_MINUS_IO1
#define COMP4_InvertingInput_PB2 LL_COMP_INPUT_MINUS_IO2
#define COMP5_InvertingInput_PD13 LL_COMP_INPUT_MINUS_IO1
#define COMP5_InvertingInput_PB10 LL_COMP_INPUT_MINUS_IO2
#define COMP6_InvertingInput_PD10 LL_COMP_INPUT_MINUS_IO1
#define COMP6_InvertingInput_PB15 LL_COMP_INPUT_MINUS_IO2
#define COMP7_InvertingInput_PC0 LL_COMP_INPUT_MINUS_IO1
#define COMPX_InvertingInput_DAC1 LL_COMP_INPUT_MINUS_DAC1_CH1
#define COMPX_InvertingInput_DAC2 LL_COMP_INPUT_MINUS_DAC1_CH2
#define COMPX_InvertingInput_VREF LL_COMP_INPUT_MINUS_VREFINT
#define COMPX_InvertingInput_VREF_1_4 LL_COMP_INPUT_MINUS_1_4VREFINT
#define COMPX_InvertingInput_VREF_1_2 LL_COMP_INPUT_MINUS_1_2VREFINT
#define COMPX_InvertingInput_VREF_3_4 LL_COMP_INPUT_MINUS_3_4VREFINT
#define COMP1_NonInvertingInput_PA1 LL_COMP_INPUT_PLUS_IO1
#define COMP2_NonInvertingInput_PA3 LL_COMP_INPUT_PLUS_IO2
#define COMP2_NonInvertingInput_PA7 LL_COMP_INPUT_PLUS_IO1
#define COMP3_NonInvertingInput_PB14 LL_COMP_INPUT_PLUS_IO1
#define COMP3_NonInvertingInput_PD14 LL_COMP_INPUT_PLUS_IO2
#define COMP4_NonInvertingInput_PB0 LL_COMP_INPUT_PLUS_IO1
#define COMP4_NonInvertingInput_PE7 LL_COMP_INPUT_PLUS_IO2
#define COMP5_NonInvertingInput_PB13 LL_COMP_INPUT_PLUS_IO2
#define COMP5_NonInvertingInput_PD12 LL_COMP_INPUT_PLUS_IO1
#define COMP6_NonInvertingInput_PB11 LL_COMP_INPUT_PLUS_IO2
#define COMP6_NonInvertingInput_PD11 LL_COMP_INPUT_PLUS_IO1
#define COMP7_NonInvertingInput_PC1 LL_COMP_INPUT_PLUS_IO2
#define COMP7_NonInvertingInput_PA0 LL_COMP_INPUT_PLUS_IO1
/* USER CODE BEGIN Additional parameters */
/* USER CODE END Additional parameters */
#endif /*PARAMETERS_CONVERSION_G4XX_H*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 6,947 |
C
| 51.240601 | 83 | 0.705053 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/power_stage_parameters.h
|
/**
******************************************************************************
* @file power_stage_parameters.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains the parameters needed for the Motor Control SDK
* in order to configure a power stage.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef POWER_STAGE_PARAMETERS_H
#define POWER_STAGE_PARAMETERS_H
/************************
*** Motor Parameters ***
************************/
/************* PWM Driving signals section **************/
#define HW_DEAD_TIME_NS 1000 /*!< Dead-time inserted
by HW if low side signals
are not used */
/*********** Bus voltage sensing section ****************/
#define VBUS_PARTITIONING_FACTOR 0.052164840897235255 /*!< It expresses how
much the Vbus is attenuated
before being converted into
digital value */
#define NOMINAL_BUS_VOLTAGE_V 30
/******** Current reading parameters section ******/
/*** Topology ***/
#define THREE_SHUNT
#define RSHUNT 0.007
/* ICSs gains in case of isolated current sensors,
amplification gain for shunts based sensing */
#define AMPLIFICATION_GAIN 20
/*** Noise parameters ***/
#define TNOISE_NS 1000
#define TRISE_NS 1000
#define MAX_TNTR_NS TRISE_NS
/************ Temperature sensing section ***************/
/* V[V]=V0+dV/dT[V/Celsius]*(T-T0)[Celsius]*/
#define V0_V 0.290 /*!< in Volts */
#define T0_C 25 /*!< in Celsius degrees */
#define dV_dT 0.025 /*!< V/Celsius degrees */
#define T_MAX 70 /*!< Sensor measured
temperature at maximum
power stage working
temperature, Celsius degrees */
#endif /*POWER_STAGE_PARAMETERS_H*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 2,960 |
C
| 42.544117 | 86 | 0.440541 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/motorcontrol.h
|
/**
******************************************************************************
* @file motorcontrol.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief Motor Control Subsystem initialization functions.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCInterface
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MOTORCONTROL_H
#define MOTORCONTROL_H
#include "mc_config.h"
#include "parameters_conversion.h"
#include "mc_api.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MCInterface
* @{
*/
/* Initializes the Motor Control Subsystem */
void MX_MotorControl_Init(void);
/* Do not remove the definition of this symbol. */
#define MC_HAL_IS_USED
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* MOTORCONTROL_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 1,506 |
C
| 23.704918 | 80 | 0.518592 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_api.h
|
/**
******************************************************************************
* @file mc_api.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file defines the high level interface of the Motor Control SDK.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCIAPI
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MC_API_H
#define MC_API_H
#include "mc_type.h"
#include "mc_interface.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup CAI
* @{
*/
/** @addtogroup MCIAPI
* @{
*/
/* Starts Motor 1 */
bool MC_StartMotor1(void);
/* Stops Motor 1 */
bool MC_StopMotor1(void);
/* Programs a Speed ramp for Motor 1 */
void MC_ProgramSpeedRampMotor1(int16_t hFinalSpeed, uint16_t hDurationms);
/* Programs a Speed ramp for Motor 1 */
void MC_ProgramSpeedRampMotor1_F(float_t FinalSpeed, uint16_t hDurationms);
/* Programs a Torque ramp for Motor 1 */
void MC_ProgramTorqueRampMotor1(int16_t hFinalTorque, uint16_t hDurationms);
/* Programs a Torque ramp for Motor 1 */
void MC_ProgramTorqueRampMotor1_F(float_t FinalTorque, uint16_t hDurationms);
/* Programs a current reference for Motor 1 */
void MC_SetCurrentReferenceMotor1(qd_t Iqdref);
/* Programs a current reference for Motor 1 */
void MC_SetCurrentReferenceMotor1_F(qd_f_t IqdRef);
/* Returns the state of the last submited command for Motor 1 */
MCI_CommandState_t MC_GetCommandStateMotor1(void);
/* Stops the execution of the current speed ramp for Motor 1 if any */
bool MC_StopSpeedRampMotor1(void);
/* Stops the execution of the on going ramp for Motor 1 if any.
Note: this function is deprecated and should not be used anymore. It will be removed in a future version. */
void MC_StopRampMotor1(void);
/* Returns true if the last submited ramp for Motor 1 has completed, false otherwise */
bool MC_HasRampCompletedMotor1(void);
/* Returns the current mechanical rotor speed reference set for Motor 1, expressed in the unit defined by #SPEED_UNIT */
int16_t MC_GetMecSpeedReferenceMotor1(void);
/* Returns the current mechanical rotor speed reference set for Motor 1, expressed in rpm */
float_t MC_GetMecSpeedReferenceMotor1_F(void);
/* Returns the last computed average mechanical rotor speed for Motor 1, expressed in the unit defined by #SPEED_UNIT */
int16_t MC_GetMecSpeedAverageMotor1(void);
/* Returns the last computed average mechanical rotor speed for Motor 1, expressed in rpm */
float_t MC_GetAverageMecSpeedMotor1_F(void);
/* Returns the last computed average mechanical rotor speed from auxiliary sensor for Motor 1, expressed in the unit defined by #SPEED_UNIT */
int16_t MC_GetMecAuxiliarySpeedAverageM1(void);
/* Returns the last computed average mechanical rotor speed from auxiliary sensor for Motor 1, expressed in RPM */
float_t MC_GetMecAuxiliarySpeedAvgM1_F(void);
/* Returns the electrical angle of the rotor from auxiliary sensor of Motor 1, in DDP format */
int16_t MC_GetAuxiliaryElAngledppMotor1(void);
/* Returns the electrical angle of the rotor from auxiliary sensor of Motor 1, expressed in radians */
float_t MC_GetAuxiliaryElAngleMotor1_F(void);
/* Returns the final speed of the last ramp programmed for Motor 1, if this ramp was a speed ramp */
int16_t MC_GetLastRampFinalSpeedMotor1(void);
/* Returns the final speed of the last ramp programmed for Motor 1, if this ramp was a speed ramp */
float_t MC_GetLastRampFinalSpeedM1_F(void);
/* Returns the current Control Mode for Motor 1 (either Speed or Torque) */
MC_ControlMode_t MC_GetControlModeMotor1(void);
/* Returns the direction imposed by the last command on Motor 1 */
int16_t MC_GetImposedDirectionMotor1(void);
/* Returns the current reliability of the speed sensor used for Motor 1 */
bool MC_GetSpeedSensorReliabilityMotor1(void);
/* returns the amplitude of the phase current injected in Motor 1 */
int16_t MC_GetPhaseCurrentAmplitudeMotor1(void);
/* returns the amplitude of the phase voltage applied to Motor 1 */
int16_t MC_GetPhaseVoltageAmplitudeMotor1(void);
/* returns current Ia and Ib values for Motor 1 */
ab_t MC_GetIabMotor1(void);
/* returns current Ia and Ib values in Ampere for Motor 1 */
ab_f_t MC_GetIabMotor1_F(void);
/* returns current Ialpha and Ibeta values for Motor 1 */
alphabeta_t MC_GetIalphabetaMotor1(void);
/* returns current Iq and Id values for Motor 1 */
qd_t MC_GetIqdMotor1(void);
/* returns current Iq and Id values in Ampere for Motor 1 */
qd_f_t MC_GetIqdMotor1_F(void);
/* returns Iq and Id reference values for Motor 1 */
qd_t MC_GetIqdrefMotor1(void);
/* returns Iq and Id reference values for Motor 1 */
qd_f_t MC_GetIqdrefMotor1_F(void);
/* returns current Vq and Vd values for Motor 1 */
qd_t MC_GetVqdMotor1(void);
/* returns current Valpha and Vbeta values for Motor 1 */
alphabeta_t MC_GetValphabetaMotor1(void);
/* returns the electrical angle of the rotor of Motor 1, in DDP format */
int16_t MC_GetElAngledppMotor1(void);
/* returns the current electrical torque reference for Motor 1 */
int16_t MC_GetTerefMotor1(void);
/* returns the current electrical torque reference in Ampere for Motor 1 */
float_t MC_GetTerefMotor1_F(void);
/* re-initializes Iq and Id references to their default values */
void MC_Clear_IqdrefMotor1(void);
/* Sets the polarization offset values to use for Motor 1*/
bool MC_SetPolarizationOffsetsMotor1(PolarizationOffsets_t * PolarizationOffsets);
/* @brief Returns the polarization offset values measured or set for Motor 1 */
bool MC_GetPolarizationOffsetsMotor1(PolarizationOffsets_t * PolarizationOffsets);
/* Starts the polarization offsets measurement procedure for Motor 1. */
bool MC_StartPolarizationOffsetsMeasurementMotor1(void);
/* Acknowledge a Motor Control fault on Motor 1 */
bool MC_AcknowledgeFaultMotor1(void);
/* Returns a bitfiled showing faults that occured since the State Machine of Motor 1 was moved to FAULT_NOW state */
uint16_t MC_GetOccurredFaultsMotor1(void);
/* Returns a bitfield showing all current faults on Motor 1 */
uint16_t MC_GetCurrentFaultsMotor1(void);
/* returns the current state of Motor 1 state machine */
MCI_State_t MC_GetSTMStateMotor1(void);
/* returns the current power of Motor 1 in float_t format */
float_t MC_GetAveragePowerMotor1_F(void);
/* Call the Profiler command */
uint8_t MC_ProfilerCommand (uint16_t rxLength, uint8_t *rxBuffer, int16_t txSyncFreeSpace, uint16_t *txLength, uint8_t *txBuffer);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* MC_API_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 7,222 |
C
| 33.232227 | 142 | 0.713237 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/drive_parameters.h
|
/**
******************************************************************************
* @file drive_parameters.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains the parameters needed for the Motor Control SDK
* in order to configure a motor drive.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DRIVE_PARAMETERS_H
#define DRIVE_PARAMETERS_H
/************************
*** Motor Parameters ***
************************/
/******** MAIN AND AUXILIARY SPEED/POSITION SENSOR(S) SETTINGS SECTION ********/
/*** Speed measurement settings ***/
#define MAX_APPLICATION_SPEED_RPM 2478 /*!< rpm, mechanical */
#define MIN_APPLICATION_SPEED_RPM 0 /*!< rpm, mechanical,
absolute value */
#define M1_SS_MEAS_ERRORS_BEFORE_FAULTS 3 /*!< Number of speed
measurement errors before
main sensor goes in fault */
/*** Encoder **********************/
#define ENC_AVERAGING_FIFO_DEPTH 16 /*!< depth of the FIFO used to
average mechanical speed in
0.1Hz resolution */
/****** State Observer + PLL ****/
#define VARIANCE_THRESHOLD 0.25 /*!<Maximum accepted
variance on speed
estimates (percentage) */
/* State observer scaling factors F1 */
#define F1 8192
#define F2 16384
#define F1_LOG LOG2((8192))
#define F2_LOG LOG2((16384))
/* State observer constants */
#define GAIN1 -11321
#define GAIN2 8442
/*Only in case PLL is used, PLL gains */
#define PLL_KP_GAIN 1154
#define PLL_KI_GAIN 51
#define PLL_KPDIV 16384
#define PLL_KPDIV_LOG LOG2((PLL_KPDIV))
#define PLL_KIDIV 65535
#define PLL_KIDIV_LOG LOG2((PLL_KIDIV))
#define STO_FIFO_DEPTH_DPP 64 /*!< Depth of the FIFO used
to average mechanical speed
in dpp format */
#define STO_FIFO_DEPTH_DPP_LOG LOG2((64))
#define STO_FIFO_DEPTH_UNIT 64 /*!< Depth of the FIFO used
to average mechanical speed
in the unit defined by #SPEED_UNIT */
#define M1_BEMF_CONSISTENCY_TOL 64 /* Parameter for B-emf
amplitude-speed consistency */
#define M1_BEMF_CONSISTENCY_GAIN 64 /* Parameter for B-emf
amplitude-speed consistency */
/* USER CODE BEGIN angle reconstruction M1 */
#define PARK_ANGLE_COMPENSATION_FACTOR 0
#define REV_PARK_ANGLE_COMPENSATION_FACTOR 0
/* USER CODE END angle reconstruction M1 */
/************************** DRIVE SETTINGS SECTION **********************/
/* PWM generation and current reading */
#define PWM_FREQUENCY 16000
#define PWM_FREQ_SCALING 1
#define LOW_SIDE_SIGNALS_ENABLING LS_PWM_TIMER
#define SW_DEADTIME_NS 850 /*!< Dead-time to be inserted
by FW, only if low side
signals are enabled */
/* Torque and flux regulation loops */
#define REGULATION_EXECUTION_RATE 1 /*!< FOC execution rate in
number of PWM cycles */
#define ISR_FREQUENCY_HZ (PWM_FREQUENCY/REGULATION_EXECUTION_RATE) /*!< @brief FOC execution rate in
Hz */
/* Gains values for torque and flux control loops */
#define PID_TORQUE_KP_DEFAULT 2317
#define PID_TORQUE_KI_DEFAULT 730
#define PID_TORQUE_KD_DEFAULT 100
#define PID_FLUX_KP_DEFAULT 2317
#define PID_FLUX_KI_DEFAULT 730
#define PID_FLUX_KD_DEFAULT 100
/* Torque/Flux control loop gains dividers*/
#define TF_KPDIV 8192
#define TF_KIDIV 16384
#define TF_KDDIV 8192
#define TF_KPDIV_LOG LOG2((8192))
#define TF_KIDIV_LOG LOG2((16384))
#define TF_KDDIV_LOG LOG2((8192))
#define TFDIFFERENTIAL_TERM_ENABLING DISABLE
/* Speed control loop */
#define SPEED_LOOP_FREQUENCY_HZ ( uint16_t )1000 /*!<Execution rate of speed
regulation loop (Hz) */
#define PID_SPEED_KP_DEFAULT 1000/(SPEED_UNIT/10) /* Workbench compute the gain for 01Hz unit*/
#define PID_SPEED_KI_DEFAULT 100/(SPEED_UNIT/10) /* Workbench compute the gain for 01Hz unit*/
#define PID_SPEED_KD_DEFAULT 0/(SPEED_UNIT/10) /* Workbench compute the gain for 01Hz unit*/
/* Speed PID parameter dividers */
#define SP_KPDIV 256
#define SP_KIDIV 32768
#define SP_KDDIV 16
#define SP_KPDIV_LOG LOG2((256))
#define SP_KIDIV_LOG LOG2((32768))
#define SP_KDDIV_LOG LOG2((16))
/* USER CODE BEGIN PID_SPEED_INTEGRAL_INIT_DIV */
#define PID_SPEED_INTEGRAL_INIT_DIV 1 /* */
/* USER CODE END PID_SPEED_INTEGRAL_INIT_DIV */
#define SPD_DIFFERENTIAL_TERM_ENABLING DISABLE
#define IQMAX_A 10
/* Default settings */
#define DEFAULT_CONTROL_MODE MCM_SPEED_MODE
#define DEFAULT_TARGET_SPEED_RPM 892
#define DEFAULT_TARGET_SPEED_UNIT (DEFAULT_TARGET_SPEED_RPM*SPEED_UNIT/U_RPM)
#define DEFAULT_TORQUE_COMPONENT_A 0
#define DEFAULT_FLUX_COMPONENT_A 0
/************************** FIRMWARE PROTECTIONS SECTION *****************/
#define OV_VOLTAGE_THRESHOLD_V 36 /*!< Over-voltage
threshold */
#define UD_VOLTAGE_THRESHOLD_V 6 /*!< Under-voltage
threshold */
#ifdef NOT_IMPLEMENTED
#define ON_OVER_VOLTAGE TURN_OFF_PWM /*!< TURN_OFF_PWM,
TURN_ON_R_BRAKE or
TURN_ON_LOW_SIDES */
#endif /* NOT_IMPLEMENTED */
#define OV_TEMPERATURE_THRESHOLD_C 70 /*!< Celsius degrees */
#define OV_TEMPERATURE_HYSTERESIS_C 10 /*!< Celsius degrees */
#define HW_OV_CURRENT_PROT_BYPASS DISABLE /*!< In case ON_OVER_VOLTAGE
is set to TURN_ON_LOW_SIDES
this feature may be used to
bypass HW over-current
protection (if supported by
power stage) */
#define OVP_INVERTINGINPUT_MODE INT_MODE
#define OVP_INVERTINGINPUT_MODE2 INT_MODE
#define OVP_SELECTION COMP_Selection_COMP1
#define OVP_SELECTION2 COMP_Selection_COMP1
/****************************** START-UP PARAMETERS **********************/
/* Encoder alignment */
#define M1_ALIGNMENT_DURATION 700 /*!< milliseconds */
#define M1_ALIGNMENT_ANGLE_DEG 90 /*!< degrees [0...359] */
#define FINAL_I_ALIGNMENT_A 10 /*!< s16A */
// With ALIGNMENT_ANGLE_DEG equal to 90 degrees final alignment
// phase current = (FINAL_I_ALIGNMENT * 1.65/ Av)/(32767 * Rshunt)
// being Av the voltage gain between Rshunt and A/D input
/* Observer start-up output conditions */
#define OBS_MINIMUM_SPEED_RPM 1000
#define NB_CONSECUTIVE_TESTS 2 /* corresponding to
former NB_CONSECUTIVE_TESTS/
(TF_REGULATION_RATE/
MEDIUM_FREQUENCY_TASK_RATE) */
#define SPEED_BAND_UPPER_LIMIT 17 /*!< It expresses how much
estimated speed can exceed
forced stator electrical
without being considered wrong.
In 1/16 of forced speed */
#define SPEED_BAND_LOWER_LIMIT 15 /*!< It expresses how much
estimated speed can be below
forced stator electrical
without being considered wrong.
In 1/16 of forced speed */
#define TRANSITION_DURATION 25 /* Switch over duration, ms */
/****************************** BUS VOLTAGE Motor 1 **********************/
#define M1_VBUS_SAMPLING_TIME LL_ADC_SAMPLING_CYCLE(47)
/****************************** Current sensing Motor 1 **********************/
#define ADC_SAMPLING_CYCLES (6 + SAMPLING_CYCLE_CORRECTION)
/****************************** ADDITIONAL FEATURES **********************/
/*** On the fly start-up ***/
/**************************
*** Control Parameters ***
**************************/
/* ##@@_USER_CODE_START_##@@ */
/* ##@@_USER_CODE_END_##@@ */
#endif /*DRIVE_PARAMETERS_H*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 10,689 |
C
| 47.590909 | 104 | 0.461222 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/main.h
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* Copyright (c) 2023 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.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#include "motorcontrol.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
#define Start_Stop_Pin GPIO_PIN_13
#define Start_Stop_GPIO_Port GPIOC
#define Start_Stop_EXTI_IRQn EXTI15_10_IRQn
#define M1_CURR_AMPL_W_Pin GPIO_PIN_0
#define M1_CURR_AMPL_W_GPIO_Port GPIOC
#define M1_CURR_AMPL_V_Pin GPIO_PIN_1
#define M1_CURR_AMPL_V_GPIO_Port GPIOC
#define M1_CURR_AMPL_U_Pin GPIO_PIN_0
#define M1_CURR_AMPL_U_GPIO_Port GPIOA
#define M1_BUS_VOLTAGE_Pin GPIO_PIN_1
#define M1_BUS_VOLTAGE_GPIO_Port GPIOA
#define UART_TX_Pin GPIO_PIN_2
#define UART_TX_GPIO_Port GPIOA
#define UART_RX_Pin GPIO_PIN_3
#define UART_RX_GPIO_Port GPIOA
#define M1_PWM_UL_Pin GPIO_PIN_7
#define M1_PWM_UL_GPIO_Port GPIOA
#define M1_PWM_VL_Pin GPIO_PIN_0
#define M1_PWM_VL_GPIO_Port GPIOB
#define M1_PWM_WL_Pin GPIO_PIN_1
#define M1_PWM_WL_GPIO_Port GPIOB
#define M1_PWM_UH_Pin GPIO_PIN_8
#define M1_PWM_UH_GPIO_Port GPIOA
#define M1_PWM_VH_Pin GPIO_PIN_9
#define M1_PWM_VH_GPIO_Port GPIOA
#define M1_PWM_WH_Pin GPIO_PIN_10
#define M1_PWM_WH_GPIO_Port GPIOA
#define TMS_Pin GPIO_PIN_13
#define TMS_GPIO_Port GPIOA
#define TCK_Pin GPIO_PIN_14
#define TCK_GPIO_Port GPIOA
#define M1_ENCODER_A_Pin GPIO_PIN_15
#define M1_ENCODER_A_GPIO_Port GPIOA
#define M1_ENCODER_B_Pin GPIO_PIN_3
#define M1_ENCODER_B_GPIO_Port GPIOB
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
| 3,171 |
C
| 28.64486 | 80 | 0.5462 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_math.h
|
/**
******************************************************************************
* @file mc_math.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides mathematics functions useful for and specific to
* Motor Control.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MC_Math
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MC_MATH_H
#define MC_MATH_H
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup MC_Math
* @{
*/
#define SQRT_2 1.4142
#define SQRT_3 1.732
/* CORDIC coprocessor configuration register settings */
/* CORDIC FUNCTION: PHASE q1.31 (Electrical Angle computation) */
#define CORDIC_CONFIG_PHASE (LL_CORDIC_FUNCTION_PHASE | LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_0 |\
LL_CORDIC_NBWRITE_2 | LL_CORDIC_NBREAD_1 |\
LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS)
/* CORDIC FUNCTION: SQUAREROOT q1.31 */
#define CORDIC_CONFIG_SQRT (LL_CORDIC_FUNCTION_SQUAREROOT | LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_1 |\
LL_CORDIC_NBWRITE_1 | LL_CORDIC_NBREAD_1 |\
LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS)
/* CORDIC FUNCTION: COSINE q1.15 */
#define CORDIC_CONFIG_COSINE (LL_CORDIC_FUNCTION_COSINE | LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_0 |\
LL_CORDIC_NBWRITE_1 | LL_CORDIC_NBREAD_1 |\
LL_CORDIC_INSIZE_16BITS | LL_CORDIC_OUTSIZE_16BITS)
/* CORDIC FUNCTION: MODULUS q1.15 */
#define CORDIC_CONFIG_MODULUS (LL_CORDIC_FUNCTION_MODULUS | LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_0 |\
LL_CORDIC_NBWRITE_1 | LL_CORDIC_NBREAD_1 |\
LL_CORDIC_INSIZE_16BITS | LL_CORDIC_OUTSIZE_16BITS)
/**
* @brief Macro to compute logarithm of two
*/
#define LOG2(x) \
(((x) == 65535 ) ? 16 : \
(((x) == (2*2*2*2*2*2*2*2*2*2*2*2*2*2*2)) ? 15 : \
(((x) == (2*2*2*2*2*2*2*2*2*2*2*2*2*2)) ? 14 : \
(((x) == (2*2*2*2*2*2*2*2*2*2*2*2*2)) ? 13 : \
(((x) == (2*2*2*2*2*2*2*2*2*2*2*2)) ? 12 : \
(((x) == (2*2*2*2*2*2*2*2*2*2*2)) ? 11 : \
(((x) == (2*2*2*2*2*2*2*2*2*2)) ? 10 : \
(((x) == (2*2*2*2*2*2*2*2*2)) ? 9 : \
(((x) == (2*2*2*2*2*2*2*2)) ? 8 : \
(((x) == (2*2*2*2*2*2*2)) ? 7 : \
(((x) == (2*2*2*2*2*2)) ? 6 : \
(((x) == (2*2*2*2*2)) ? 5 : \
(((x) == (2*2*2*2)) ? 4 : \
(((x) == (2*2*2)) ? 3 : \
(((x) == (2*2)) ? 2 : \
(((x) == 2) ? 1 : \
(((x) == 1) ? 0 : -1)))))))))))))))))
/**
* @brief Trigonometrical functions type definition
*/
typedef struct
{
int16_t hCos;
int16_t hSin;
} Trig_Components;
/**
* @brief This function transforms stator currents Ia and qIb (which are
* directed along axes each displaced by 120 degrees) into currents
* Ialpha and Ibeta in a stationary qd reference frame.
* Ialpha = Ia
* Ibeta = -(2*Ib+Ia)/sqrt(3)
* @param Curr_Input: stator current Ia and Ib in ab_t format.
* @retval Stator current Ialpha and Ibeta in alphabeta_t format.
*/
alphabeta_t MCM_Clarke(ab_t Input);
/**
* @brief This function transforms stator values alpha and beta, which
* belong to a stationary qd reference frame, to a rotor flux
* synchronous reference frame (properly oriented), so as Iq and Id.
* Id= Ialpha *sin(theta)+qIbeta *cos(Theta)
* Iq=qIalpha *cos(Theta)-qIbeta *sin(Theta)
* @param Curr_Input: stator values alpha and beta in alphabeta_t format.
* @param Theta: rotating frame angular position in q1.15 format.
* @retval Stator current q and d in qd_t format.
*/
qd_t MCM_Park(alphabeta_t Input, int16_t Theta);
/**
* @brief This function transforms stator voltage qVq and qVd, that belong to
* a rotor flux synchronous rotating frame, to a stationary reference
* frame, so as to obtain qValpha and qVbeta:
* Valfa= Vq*Cos(theta)+ Vd*Sin(theta)
* Vbeta=-Vq*Sin(theta)+ Vd*Cos(theta)
* @param Curr_Input: stator voltage Vq and Vd in qd_t format.
* @param Theta: rotating frame angular position in q1.15 format.
* @retval Stator values alpha and beta in alphabeta_t format.
*/
alphabeta_t MCM_Rev_Park(qd_t Input, int16_t Theta);
/**
* @brief This function returns cosine and sine functions of the angle fed in input.
* @param hAngle: angle in q1.15 format.
* @retval Trig_Components Cos(angle) and Sin(angle) in Trig_Components format.
*/
Trig_Components MCM_Trig_Functions(int16_t hAngle);
/**
* @brief It calculates the square root of a non-negative s32. It returns 0 for negative s32.
* @param Input int32_t number.
* @retval int32_t Square root of Input (0 if Input<0).
*/
int32_t MCM_Sqrt(int32_t wInput);
/**
* @brief Sqrt table used by Circle Limitation function
* used for STM32F0/STM32G0 series only
*/
#define SQRT_CIRCLE_LIMITATION {\
0 , 1023 , 1448 , 1773 , 2047 , 2289 , 2508 , 2709,\
2896 , 3071 , 3238 , 3396 , 3547 , 3691 , 3831 , 3965,\
4095 , 4221 , 4344 , 4463 , 4579 , 4692 , 4802 , 4910,\
5016 , 5119 , 5221 , 5320 , 5418 , 5514 , 5608 , 5701,\
5792 , 5882 , 5970 , 6057 , 6143 , 6228 , 6312 , 6394,\
6476 , 6556 , 6636 , 6714 , 6792 , 6868 , 6944 , 7019,\
7094 , 7167 , 7240 , 7312 , 7383 , 7454 , 7524 , 7593,\
7662 , 7730 , 7798 , 7865 , 7931 , 7997 , 8062 , 8127,\
8191 , 8255 , 8318 , 8381 , 8443 , 8505 , 8567 , 8628,\
8688 , 8748 , 8808 , 8867 , 8926 , 8985 , 9043 , 9101,\
9158 , 9215 , 9272 , 9328 , 9384 , 9440 , 9495 , 9550,\
9605 , 9660 , 9714 , 9768 , 9821 , 9874 , 9927 , 9980,\
10032 , 10084 , 10136 , 10188 , 10239 , 10290 , 10341 , 10392,\
10442 , 10492 , 10542 , 10592 , 10641 , 10690 , 10739 , 10788,\
10836 , 10884 , 10932 , 10980 , 11028 , 11075 , 11123 , 11170,\
11217 , 11263 , 11310 , 11356 , 11402 , 11448 , 11494 , 11539,\
11584 , 11630 , 11675 , 11719 , 11764 , 11808 , 11853 , 11897,\
11941 , 11985 , 12028 , 12072 , 12115 , 12158 , 12201 , 12244,\
12287 , 12330 , 12372 , 12414 , 12457 , 12499 , 12541 , 12582,\
12624 , 12665 , 12707 , 12748 , 12789 , 12830 , 12871 , 12911,\
12952 , 12992 , 13032 , 13073 , 13113 , 13153 , 13192 , 13232,\
13272 , 13311 , 13350 , 13390 , 13429 , 13468 , 13507 , 13545,\
13584 , 13623 , 13661 , 13699 , 13737 , 13776 , 13814 , 13851,\
13889 , 13927 , 13965 , 14002 , 14039 , 14077 , 14114 , 14151,\
14188 , 14225 , 14262 , 14298 , 14335 , 14372 , 14408 , 14444,\
14481 , 14517 , 14553 , 14589 , 14625 , 14661 , 14696 , 14732,\
14767 , 14803 , 14838 , 14874 , 14909 , 14944 , 14979 , 15014,\
15049 , 15084 , 15118 , 15153 , 15187 , 15222 , 15256 , 15291,\
15325 , 15359 , 15393 , 15427 , 15461 , 15495 , 15529 , 15562,\
15596 , 15630 , 15663 , 15697 , 15730 , 15763 , 15797 , 15830,\
15863 , 15896 , 15929 , 15962 , 15994 , 16027 , 16060 , 16092,\
16125 , 16157 , 16190 , 16222 , 16254 , 16287 , 16319 , 16351,\
16383 , 16415 , 16447 , 16479 , 16510 , 16542 , 16574 , 16605,\
16637 , 16669 , 16700 , 16731 , 16763 , 16794 , 16825 , 16856,\
16887 , 16918 , 16949 , 16980 , 17011 , 17042 , 17072 , 17103,\
17134 , 17164 , 17195 , 17225 , 17256 , 17286 , 17316 , 17347,\
17377 , 17407 , 17437 , 17467 , 17497 , 17527 , 17557 , 17587,\
17617 , 17646 , 17676 , 17706 , 17735 , 17765 , 17794 , 17824,\
17853 , 17882 , 17912 , 17941 , 17970 , 17999 , 18028 , 18057,\
18086 , 18115 , 18144 , 18173 , 18202 , 18231 , 18259 , 18288,\
18317 , 18345 , 18374 , 18402 , 18431 , 18459 , 18488 , 18516,\
18544 , 18573 , 18601 , 18629 , 18657 , 18685 , 18713 , 18741,\
18769 , 18797 , 18825 , 18853 , 18881 , 18908 , 18936 , 18964,\
18991 , 19019 , 19046 , 19074 , 19101 , 19129 , 19156 , 19184,\
19211 , 19238 , 19265 , 19293 , 19320 , 19347 , 19374 , 19401,\
19428 , 19455 , 19482 , 19509 , 19536 , 19562 , 19589 , 19616,\
19643 , 19669 , 19696 , 19723 , 19749 , 19776 , 19802 , 19829,\
19855 , 19881 , 19908 , 19934 , 19960 , 19987 , 20013 , 20039,\
20065 , 20091 , 20117 , 20143 , 20169 , 20235 , 20231 , 20247,\
20273 , 20299 , 20325 , 20350 , 20376 , 20402 , 20428 , 20453,\
20479 , 20504 , 20530 , 20556 , 20581 , 20606 , 20632 , 20657,\
20683 , 20708 , 20733 , 20759 , 20784 , 20809 , 20834 , 20859,\
20884 , 20910 , 20935 , 20960 , 20985 , 21010 , 21035 , 21059,\
21084 , 21109 , 21134 , 21159 , 21184 , 21208 , 21233 , 21258,\
21282 , 21307 , 21331 , 21356 , 21381 , 21405 , 21430 , 21454,\
21478 , 21503 , 21527 , 21552 , 21576 , 21600 , 21624 , 21649,\
21673 , 21697 , 21721 , 21745 , 21769 , 21793 , 21817 , 21841,\
21865 , 21889 , 21913 , 21937 , 21961 , 21985 , 22009 , 22033,\
22056 , 22080 , 22104 , 22128 , 22151 , 22175 , 22199 , 22222,\
22246 , 22269 , 22293 , 22316 , 22340 , 22363 , 22387 , 22410,\
22434 , 22457 , 22480 , 22504 , 22527 , 22550 , 22573 , 22597,\
22620 , 22643 , 22666 , 22689 , 22712 , 22735 , 22758 , 22781,\
22804 , 22827 , 22850 , 22873 , 22896 , 22919 , 22942 , 22965,\
22988 , 23010 , 23033 , 23056 , 23079 , 23101 , 23124 , 23147,\
23169 , 23192 , 23214 , 23237 , 23260 , 23282 , 23305 , 23327,\
23350 , 23372 , 23394 , 23417 , 23439 , 23462 , 23484 , 23506,\
23529 , 23551 , 23573 , 23595 , 23617 , 23640 , 23662 , 23684,\
23706 , 23728 , 23750 , 23772 , 23794 , 23816 , 23838 , 23860,\
23882 , 23904 , 23926 , 23948 , 23970 , 23992 , 24014 , 24036,\
24057 , 24079 , 24101 , 24123 , 24144 , 24166 , 24188 , 24209,\
24231 , 24253 , 24274 , 24296 , 24317 , 24339 , 24360 , 24382,\
24403 , 24425 , 24446 , 24468 , 24489 , 24511 , 24532 , 24553,\
24575 , 24596 , 24617 , 24639 , 24660 , 24681 , 24702 , 24724,\
24745 , 24766 , 24787 , 24808 , 24829 , 24851 , 24872 , 24893,\
24914 , 24935 , 24956 , 24977 , 24998 , 25019 , 25040 , 25061,\
25082 , 25102 , 25123 , 25144 , 25165 , 25186 , 25207 , 25227,\
25248 , 25269 , 25290 , 25310 , 25331 , 25352 , 25372 , 25393,\
25414 , 25434 , 25455 , 25476 , 25496 , 25517 , 25537 , 25558,\
25578 , 25599 , 25619 , 25640 , 25660 , 25681 , 25701 , 25721,\
25742 , 25762 , 25782 , 25803 , 25823 , 25843 , 25864 , 25884,\
25904 , 25924 , 25945 , 25965 , 25985 , 26005 , 26025 , 26045,\
26065 , 26086 , 26106 , 26126 , 26146 , 26166 , 26186 , 26206,\
26226 , 26246 , 26266 , 26286 , 26306 , 26326 , 26346 , 26365,\
26385 , 26405 , 26425 , 26445 , 26465 , 26484 , 26504 , 26524,\
26544 , 26564 , 26583 , 26603 , 26623 , 26642 , 26662 , 26682,\
26701 , 26721 , 26741 , 26760 , 26780 , 26799 , 26819 , 26838,\
26858 , 26877 , 26897 , 26916 , 26936 , 26955 , 26975 , 26994,\
27014 , 27033 , 27052 , 27072 , 27091 , 27111 , 27130 , 27149,\
27168 , 27188 , 27207 , 27226 , 27246 , 27265 , 27284 , 27303,\
27322 , 27342 , 27361 , 27380 , 27399 , 27418 , 27437 , 27456,\
27475 , 27495 , 27514 , 27533 , 27552 , 27571 , 27590 , 27609,\
27628 , 27647 , 27666 , 27685 , 27703 , 27722 , 27741 , 27760,\
27779 , 27798 , 27817 , 27836 , 27854 , 27873 , 27892 , 27911,\
27930 , 27948 , 27967 , 27986 , 28005 , 28023 , 28042 , 28061,\
28079 , 28098 , 28117 , 28135 , 28154 , 28173 , 28191 , 28210,\
28228 , 28247 , 28265 , 28284 , 28303 , 28321 , 28340 , 28358,\
28377 , 28395 , 28413 , 28432 , 28450 , 28469 , 28487 , 28506,\
28524 , 28542 , 28561 , 28579 , 28597 , 28616 , 28634 , 28652,\
28671 , 28689 , 28707 , 28725 , 28744 , 28762 , 28780 , 28798,\
28817 , 28835 , 28853 , 28871 , 28889 , 28907 , 28925 , 28944,\
28962 , 28980 , 28998 , 29016 , 29034 , 29052 , 29070 , 29088,\
29106 , 29124 , 29142 , 29160 , 29178 , 29196 , 29214 , 29232,\
29250 , 29268 , 29286 , 29304 , 29322 , 29339 , 29357 , 29375,\
29393 , 29411 , 29429 , 29446 , 29464 , 29482 , 29500 , 29518,\
29535 , 29553 , 29571 , 29588 , 29606 , 29624 , 29642 , 29659,\
29677 , 29695 , 29712 , 29730 , 29748 , 29765 , 29783 , 29800,\
29818 , 29835 , 29853 , 29871 , 29888 , 29906 , 29923 , 29941,\
29958 , 29976 , 29993 , 30011 , 30028 , 30046 , 30063 , 30080,\
30098 , 30115 , 30133 , 30150 , 30168 , 30185 , 30202 , 30220,\
30237 , 30254 , 30272 , 30289 , 30306 , 30324 , 30341 , 30358,\
30375 , 30393 , 30410 , 30427 , 30444 , 30461 , 30479 , 30496,\
30513 , 30530 , 30547 , 30565 , 30582 , 30599 , 30616 , 30633,\
30650 , 30667 , 30684 , 30701 , 30719 , 30736 , 30753 , 30770,\
30787 , 30804 , 30821 , 30838 , 30855 , 30872 , 30889 , 30906,\
30923 , 30940 , 30957 , 30973 , 30990 , 31007 , 31024 , 31041,\
31058 , 31075 , 31092 , 31109 , 31125 , 31142 , 31159 , 31176,\
31193 , 31210 , 31226 , 31243 , 31260 , 31277 , 31293 , 31310,\
31327 , 31344 , 31360 , 31377 , 31394 , 31410 , 31427 , 31444,\
31461 , 31477 , 31494 , 31510 , 31527 , 31544 , 31560 , 31577,\
31594 , 31610 , 31627 , 31643 , 31660 , 31676 , 31693 , 31709,\
31726 , 31743 , 31759 , 31776 , 31792 , 31809 , 31825 , 31841,\
31858 , 31874 , 31891 , 31907 , 31924 , 31940 , 31957 , 31973,\
31989 , 32006 , 32023 , 32038 , 32055 , 32071 , 32087 , 32104,\
32120 , 32136 , 32153 , 32169 , 32185 , 32202 , 32218 , 32234,\
32250 , 32267 , 32283 , 32299 , 32315 , 32332 , 32348 , 32364,\
32380 , 32396 , 32413 , 32429 , 32445 , 32461 , 32477 , 32493,\
32509 , 32526 , 32542 , 32558 , 32574 , 32590 , 32606 , 32622,\
32638 , 32654 , 32670 , 32686 , 32702 , 32718 , 32734 , 32750,\
32767 }
#define ATAN1DIV1 (int16_t)8192
#define ATAN1DIV2 (int16_t)4836
#define ATAN1DIV4 (int16_t)2555
#define ATAN1DIV8 (int16_t)1297
#define ATAN1DIV16 (int16_t)651
#define ATAN1DIV32 (int16_t)326
#define ATAN1DIV64 (int16_t)163
#define ATAN1DIV128 (int16_t)81
#define ATAN1DIV256 (int16_t)41
#define ATAN1DIV512 (int16_t)20
#define ATAN1DIV1024 (int16_t)10
#define ATAN1DIV2048 (int16_t)5
#define ATAN1DIV4096 (int16_t)3
#define ATAN1DIV8192 (int16_t)1
/**
* @brief It executes Modulus algorithm.
* @param alpha component,
* beta component.
* @retval int16_t Modulus.
*/
static inline int16_t MCM_Modulus(int16_t alpha, int16_t beta)
{
uint32_t temp_val;
__disable_irq();
/* Configure and call to CORDIC- */
WRITE_REG(CORDIC->CSR,CORDIC_CONFIG_MODULUS);
LL_CORDIC_WriteData(CORDIC, (((uint32_t)beta << 16U) | (uint32_t)alpha));
/* Wait for result */
while(LL_CORDIC_IsActiveFlag_RRDY(CORDIC) == 0U)
{
/* Nothing to do */
}
/* Read computed modulus */
temp_val = ((LL_CORDIC_ReadData(CORDIC) << 16U) >> 16U); /* Avoid Over/underflow when cast to int16_t */
__enable_irq();
return ((int16_t)temp_val);
}
/**
* @brief It executes CORDIC algorithm for rotor position extraction from B-emf alpha and beta.
* @param wBemf_alfa_est estimated Bemf alpha on the stator reference frame.
* wBemf_beta_est estimated Bemf beta on the stator reference frame.
* @retval int16_t rotor electrical angle (s16degrees).
*/
static inline int16_t MCM_PhaseComputation(int32_t wBemf_alfa_est, int32_t wBemf_beta_est)
{
/* Configure and call to CORDIC */
WRITE_REG(CORDIC->CSR,CORDIC_CONFIG_PHASE);
LL_CORDIC_WriteData(CORDIC, (uint32_t)wBemf_alfa_est);
LL_CORDIC_WriteData(CORDIC, (uint32_t)wBemf_beta_est);
/* Read computed angle */
uint32_t result;
result = LL_CORDIC_ReadData(CORDIC) >> 16U;
return ((int16_t)result);
}
/**
* @brief This function codify a floting point number into the relative 32bit integer.
* @param float_t Floting point number to be coded.
* @retval uint32_t Coded 32bit integer.
*/
uint32_t MCM_floatToIntBit(float_t x);
/**
* @}
*/
/**
* @}
*/
#endif /* MC_MATH_H*/
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 16,713 |
C
| 46.214689 | 115 | 0.582361 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_interface.h
|
/**
******************************************************************************
* @file mc_interface.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains all definitions and functions prototypes for the
* MC Interface component of the Motor Control SDK.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
* @ingroup MCInterface
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef MC_INTERFACE_H
#define MC_INTERFACE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Includes ------------------------------------------------------------------*/
#include "mc_type.h"
#include "pwm_curr_fdbk.h"
#include "speed_torq_ctrl.h"
/** @addtogroup MCSDK
* @{
*/
/** @addtogroup CAI
* @{
*/
/** @addtogroup MCInterface
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief Status of a user (buffered) command
*/
typedef enum
{
MCI_BUFFER_EMPTY, /*!< If no buffered command has been called.*/
MCI_COMMAND_NOT_ALREADY_EXECUTED, /*!< If the buffered command condition hasn't already occurred.*/
MCI_COMMAND_EXECUTED_SUCCESSFULLY, /*!< If the buffered command has been executed successfully.*/
MCI_COMMAND_EXECUTED_UNSUCCESSFULLY /*!< If the buffered command has been executed unsuccessfully.*/
} MCI_CommandState_t ;
/**
* @brief list of user (buffered) commands
*/
typedef enum
{
MCI_NOCOMMANDSYET, /*!< No command has been set by the user.*/
MCI_CMD_EXECSPEEDRAMP, /*!< ExecSpeedRamp command coming from the user.*/
MCI_CMD_EXECTORQUERAMP, /*!< ExecTorqueRamp command coming from the user.*/
MCI_CMD_SETCURRENTREFERENCES, /*!< SetCurrentReferences command coming from the user.*/
MCI_CMD_SETOPENLOOPCURRENT, /*!< set open loop current .*/
MCI_CMD_SETOPENLOOPVOLTAGE, /*!< set open loop voltage .*/
} MCI_UserCommands_t;
typedef struct
{
float voltage;
float current;
float frequency;
float padding [1];
} __attribute__ ((packed)) ScaleParams_t;
/**
* @brief State_t enum type definition, it lists all the possible state machine states
*/
typedef enum
{
ICLWAIT = 12, /**< The system is waiting for ICL deactivation. Is not possible
* to run the motor if ICL is active. While the ICL is active
* the state is forced to #ICLWAIT; when ICL become inactive the
* state is moved to #IDLE. */
IDLE = 0, /**< The state machine remains in this state as long as the
* application is not controlling the motor. This state is exited
* when the application sends a motor command or when a fault occurs. */
ALIGNMENT = 2, /**< The encoder alignment procedure that will properly align the
* the encoder to a set mechanical angle is being executed. */
CHARGE_BOOT_CAP = 16, /**< The gate driver boot capacitors are being charged. */
OFFSET_CALIB = 17, /**< The offset of motor currents and voltages measurement cirtcuitry
* are being calibrated. */
START = 4, /**< The motor start-up is procedure is being executed. */
SWITCH_OVER = 19, /**< Transition between the open loop startup procedure and
* closed loop operation */
RUN = 6, /**< The state machien remains in this state as long as the
* application is running (controlling) the motor. This state
* is exited when the application isues a stop command or when
* a fault occurs. */
STOP = 8, /**< The stop motor procedure is being executed. */
FAULT_NOW = 10, /**< The state machine is moved from any state directly to this
* state when a fault occurs. The next state can only be
* #FAULT_OVER. */
FAULT_OVER = 11, /*!< The state machine transitions from #FAULT_NOW to this state
* when there is no active fault condition anymore. It remains
* in this state until either a new fault condition occurs (in which
* case it goes back to the #FAULT_NOW state) or the application
* acknowledges the faults (in which case it goes to the #IDLE state).
*/
WAIT_STOP_MOTOR = 20 /**< Temporisation to make sure the motor is stopped. */
} MCI_State_t;
/**
* @brief list of direct (unbffered) commands
*/
typedef enum
{
MCI_NO_COMMAND = 0, /**< No Command --- Set when going to IDLE */
MCI_START, /**< Start controling the Motor */
MCI_ACK_FAULTS, /**< Acknowledge Motor Control subsystem faults */
MCI_MEASURE_OFFSETS, /**< Start the ADCs Offset measurements procedure */
/* Shouldn't we remove this command ? */
MCI_ALIGN_ENCODER, /**< Start the Encoder alignment procedure */
MCI_STOP /**< Stop the Motor and the control */
} MCI_DirectCommands_t;
typedef struct
{
SpeednTorqCtrl_Handle_t *pSTC; /*!< Speed and torque controller object used by MCI.*/
pFOCVars_t pFOCVars; /*!< Pointer to FOC vars used by MCI.*/
PWMC_Handle_t *pPWM; /*!< Pointer to PWM handle structure.*/
MCI_UserCommands_t lastCommand; /*!< Last command coming from the user.*/
int16_t hFinalSpeed; /*!< Final speed of last ExecSpeedRamp command.*/
int16_t hFinalTorque; /*!< Final torque of last ExecTorqueRamp command.*/
qd_t Iqdref; /*!< Current component of last SetCurrentReferences command.*/
ScaleParams_t *pScale;
uint16_t hDurationms; /*!< Duration in ms of last ExecSpeedRamp or ExecTorqueRamp command.*/
MCI_DirectCommands_t DirectCommand;
MCI_State_t State;
uint16_t CurrentFaults;
uint16_t PastFaults;
MCI_CommandState_t CommandState; /*!< The status of the buffered command.*/
MC_ControlMode_t LastModalitySetByUser; /*!< The last MC_ControlMode_t set by the user. */
} MCI_Handle_t;
/* Exported functions ------------------------------------------------------- */
void MCI_Init(MCI_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, pFOCVars_t pFOCVars, PWMC_Handle_t *pPWMHandle);
void MCI_ExecBufferedCommands(MCI_Handle_t *pHandle );
void MCI_ExecSpeedRamp(MCI_Handle_t *pHandle, int16_t hFinalSpeed, uint16_t hDurationms);
void MCI_ExecSpeedRamp_F(MCI_Handle_t *pHandle, const float_t FinalSpeed, uint16_t hDurationms);
void MCI_ExecTorqueRamp(MCI_Handle_t *pHandle, int16_t hFinalTorque, uint16_t hDurationms);
void MCI_ExecTorqueRamp_F(MCI_Handle_t *pHandle, const float_t FinalTorque, uint16_t hDurationms);
void MCI_SetCurrentReferences(MCI_Handle_t *pHandle, qd_t Iqdref);
void MCI_SetCurrentReferences_F(MCI_Handle_t *pHandle, qd_f_t IqdRef);
void MCI_SetIdref(MCI_Handle_t *pHandle, int16_t hNewIdRef);
void MCI_SetIdref_F(MCI_Handle_t *pHandle, float_t NewIdRef);
bool MCI_StartMotor(MCI_Handle_t *pHandle);
bool MCI_StartWithPolarizationMotor(MCI_Handle_t *pHandle);
bool MCI_StartOffsetMeasurments(MCI_Handle_t *pHandle);
bool MCI_GetCalibratedOffsetsMotor(MCI_Handle_t* pHandle, PolarizationOffsets_t * PolarizationOffsets);
bool MCI_SetCalibratedOffsetsMotor(MCI_Handle_t* pHandle, PolarizationOffsets_t * PolarizationOffsets);
bool MCI_StopMotor(MCI_Handle_t *pHandle);
bool MCI_FaultAcknowledged(MCI_Handle_t *pHandle);
void MCI_FaultProcessing(MCI_Handle_t *pHandle, uint16_t hSetErrors, uint16_t hResetErrors);
uint32_t MCI_GetFaultState(MCI_Handle_t *pHandle );
MCI_CommandState_t MCI_IsCommandAcknowledged(MCI_Handle_t *pHandle);
MCI_State_t MCI_GetSTMState(MCI_Handle_t *pHandle);
uint16_t MCI_GetOccurredFaults(MCI_Handle_t *pHandle);
uint16_t MCI_GetCurrentFaults(MCI_Handle_t *pHandle);
float_t MCI_GetMecSpeedRef_F(MCI_Handle_t *pHandle);
float_t MCI_GetAvrgMecSpeed_F(MCI_Handle_t *pHandle);
MC_ControlMode_t MCI_GetControlMode(MCI_Handle_t *pHandle);
int16_t MCI_GetImposedMotorDirection(MCI_Handle_t *pHandle);
int16_t MCI_GetLastRampFinalSpeed(MCI_Handle_t *pHandle);
int16_t MCI_GetLastRampFinalTorque(MCI_Handle_t *pHandle);
uint16_t MCI_GetLastRampFinalDuration(MCI_Handle_t *pHandle);
bool MCI_RampCompleted(MCI_Handle_t *pHandle);
float_t MCI_GetLastRampFinalSpeed_F(MCI_Handle_t *pHandle);
bool MCI_StopSpeedRamp(MCI_Handle_t *pHandle);
void MCI_StopRamp(MCI_Handle_t *pHandle);
bool MCI_GetSpdSensorReliability(MCI_Handle_t *pHandle);
int16_t MCI_GetAvrgMecSpeedUnit(MCI_Handle_t *pHandle);
int16_t MCI_GetMecSpeedRefUnit(MCI_Handle_t *pHandle);
ab_t MCI_GetIab(MCI_Handle_t *pHandle);
ab_f_t MCI_GetIab_F(MCI_Handle_t *pHandle);
alphabeta_t MCI_GetIalphabeta(MCI_Handle_t *pHandle);
qd_t MCI_GetIqd(MCI_Handle_t *pHandle);
qd_f_t MCI_GetIqd_F(MCI_Handle_t *pHandle);
qd_t MCI_GetIqdHF(MCI_Handle_t *pHandle);
qd_t MCI_GetIqdref(MCI_Handle_t *pHandle);
qd_f_t MCI_GetIqdref_F(MCI_Handle_t *pHandle);
qd_t MCI_GetVqd(MCI_Handle_t *pHandle);
alphabeta_t MCI_GetValphabeta(MCI_Handle_t *pHandle);
int16_t MCI_GetElAngledpp(MCI_Handle_t *pHandle);
int16_t MCI_GetTeref(MCI_Handle_t *pHandle);
float_t MCI_GetTeref_F(MCI_Handle_t *pHandle );
int16_t MCI_GetPhaseCurrentAmplitude(MCI_Handle_t *pHandle);
int16_t MCI_GetPhaseVoltageAmplitude(MCI_Handle_t *pHandle);
void MCI_Clear_Iqdref(MCI_Handle_t *pHandle);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* __cpluplus */
#endif /* MC_INTERFACE_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 10,234 |
C
| 43.694323 | 116 | 0.637874 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/mc_parameters.h
|
/**
******************************************************************************
* @file mc_parameters.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file provides declarations of HW parameters specific to the
* configuration of the subsystem.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef MC_PARAMETERS_H
#define MC_PARAMETERS_H
#include "mc_interface.h"
#include "r3_1_g4xx_pwm_curr_fdbk.h"
/* USER CODE BEGIN Additional include */
/* USER CODE END Additional include */
extern const R3_1_Params_t R3_1_ParamsM1;
extern ScaleParams_t scaleParams_M1;
/* USER CODE BEGIN Additional extern */
/* USER CODE END Additional extern */
#endif /* MC_PARAMETERS_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 1,327 |
C
| 29.88372 | 80 | 0.543331 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Inc/pmsm_motor_parameters.h
|
/**
******************************************************************************
* @file pmsm_motor_parameters.h
* @author Motor Control SDK Team, ST Microelectronics
* @brief This file contains the parameters needed for the Motor Control SDK
* in order to configure the motor to drive.
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2023 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PMSM_MOTOR_PARAMETERS_H
#define PMSM_MOTOR_PARAMETERS_H
/************************
*** Motor Parameters ***
************************/
/***************** MOTOR ELECTRICAL PARAMETERS ******************************/
#define POLE_PAIR_NUM 14 /* Number of motor pole pairs */
#define RS 0.15 /* Stator resistance , ohm*/
#define LS 0.00006 /* Stator inductance, H
For I-PMSM it is equal to Lq */
/* When using Id = 0, NOMINAL_CURRENT is utilized to saturate the output of the
PID for speed regulation (i.e. reference torque).
Transformation of real currents (A) into int16_t format must be done accordingly with
formula:
Phase current (int16_t 0-to-peak) = (Phase current (A 0-to-peak)* 32767 * Rshunt *
*Amplifying network gain)/(MCU supply voltage/2)
*/
#define MOTOR_MAX_SPEED_RPM 2478 /*!< Maximum rated speed */
#define MOTOR_VOLTAGE_CONSTANT 5.2 /*!< Volts RMS ph-ph /kRPM */
#define NOMINAL_CURRENT_A 10
#define ID_DEMAG_A (int16_t)-10 /*!< Demagnetization current */
/***************** MOTOR SENSORS PARAMETERS ******************************/
/* Motor sensors parameters are always generated but really meaningful only
if the corresponding sensor is actually present in the motor */
/*** Hall sensors ***/
#define HALL_SENSORS_PLACEMENT DEGREES_120 /*!<Define here the
mechanical position of the sensors
withreference to an electrical cycle.
It can be either DEGREES_120 or
DEGREES_60 */
#define HALL_PHASE_SHIFT 300 /*!< Define here in degrees
the electrical phase shift between
the low to high transition of
signal H1 and the maximum of
the Bemf induced on phase A */
/*** Quadrature encoder ***/
#define M1_ENCODER_PPR 1024 /*!< Number of pulses per
revolution */
#endif /* PMSM_MOTOR_PARAMETERS_H */
/******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
| 3,407 |
C
| 46.333333 | 88 | 0.484884 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_i2s.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_i2s.c
* @author MCD Application Team
* @brief I2S HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Integrated Interchip Sound (I2S) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
===============================================================================
##### How to use this driver #####
===============================================================================
[..]
The I2S HAL driver can be used as follow:
(#) Declare a I2S_HandleTypeDef handle structure.
(#) Initialize the I2S low level resources by implement the HAL_I2S_MspInit() API:
(##) Enable the SPIx interface clock.
(##) I2S pins configuration:
(+++) Enable the clock for the I2S GPIOs.
(+++) Configure these I2S pins as alternate function pull-up.
(##) NVIC configuration if you need to use interrupt process (HAL_I2S_Transmit_IT()
and HAL_I2S_Receive_IT() APIs).
(+++) Configure the I2Sx interrupt priority.
(+++) Enable the NVIC I2S IRQ handle.
(##) DMA Configuration if you need to use DMA process (HAL_I2S_Transmit_DMA()
and HAL_I2S_Receive_DMA() APIs:
(+++) Declare a DMA handle structure for the Tx/Rx Stream/Channel.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
(+++) Configure the DMA Tx/Rx Stream/Channel.
(+++) Associate the initialized DMA handle to the I2S DMA Tx/Rx handle.
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the
DMA Tx/Rx Stream/Channel.
(#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity
using HAL_I2S_Init() function.
-@- The specific I2S interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_I2S_ENABLE_IT() and __HAL_I2S_DISABLE_IT() inside the transmit and receive process.
-@- Make sure that either:
(+@) SYSCLK is configured or
(+@) PLLADCCLK output is configured or
(+@) HSI is enabled or
(+@) External clock source is configured after setting correctly
the define constant EXTERNAL_CLOCK_VALUE in the stm32g4xx_hal_conf.h file.
(#) Three mode of operations are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Send an amount of data in blocking mode using HAL_I2S_Transmit()
(+) Receive an amount of data in blocking mode using HAL_I2S_Receive()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT()
(+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
(+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_TxCpltCallback
(+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT()
(+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
(+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_RxCpltCallback
(+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_I2S_ErrorCallback
*** DMA mode IO operation ***
==============================
[..]
(+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA()
(+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback
(+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_TxCpltCallback
(+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA()
(+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback
(+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_I2S_RxCpltCallback
(+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_I2S_ErrorCallback
(+) Pause the DMA Transfer using HAL_I2S_DMAPause()
(+) Resume the DMA Transfer using HAL_I2S_DMAResume()
(+) Stop the DMA Transfer using HAL_I2S_DMAStop()
In Slave mode, if HAL_I2S_DMAStop is used to stop the communication, an error
HAL_I2S_ERROR_BUSY_LINE_RX is raised as the master continue to transmit data.
In this case __HAL_I2S_FLUSH_RX_DR macro must be used to flush the remaining data
inside DR register and avoid using DeInit/Init process for the next transfer.
*** I2S HAL driver macros list ***
===================================
[..]
Below the list of most used macros in I2S HAL driver.
(+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode)
(+) __HAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode)
(+) __HAL_I2S_ENABLE_IT : Enable the specified I2S interrupts
(+) __HAL_I2S_DISABLE_IT : Disable the specified I2S interrupts
(+) __HAL_I2S_GET_FLAG: Check whether the specified I2S flag is set or not
(+) __HAL_I2S_FLUSH_RX_DR: Read DR Register to Flush RX Data
[..]
(@) You can refer to the I2S HAL driver header file for more useful macros
*** I2S HAL driver macros list ***
===================================
[..]
Callback registration:
(#) The compilation flag USE_HAL_I2S_REGISTER_CALLBACKS when set to 1U
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_I2S_RegisterCallback() to register an interrupt callback.
Function HAL_I2S_RegisterCallback() allows to register following callbacks:
(++) TxCpltCallback : I2S Tx Completed callback
(++) RxCpltCallback : I2S Rx Completed callback
(++) TxHalfCpltCallback : I2S Tx Half Completed callback
(++) RxHalfCpltCallback : I2S Rx Half Completed callback
(++) ErrorCallback : I2S Error callback
(++) MspInitCallback : I2S Msp Init callback
(++) MspDeInitCallback : I2S Msp DeInit callback
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
(#) Use function HAL_I2S_UnRegisterCallback to reset a callback to the default
weak function.
HAL_I2S_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(++) TxCpltCallback : I2S Tx Completed callback
(++) RxCpltCallback : I2S Rx Completed callback
(++) TxHalfCpltCallback : I2S Tx Half Completed callback
(++) RxHalfCpltCallback : I2S Rx Half Completed callback
(++) ErrorCallback : I2S Error callback
(++) MspInitCallback : I2S Msp Init callback
(++) MspDeInitCallback : I2S Msp DeInit callback
[..]
By default, after the HAL_I2S_Init() and when the state is HAL_I2S_STATE_RESET
all callbacks are set to the corresponding weak functions:
examples HAL_I2S_MasterTxCpltCallback(), HAL_I2S_MasterRxCpltCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the HAL_I2S_Init()/ HAL_I2S_DeInit() only when
these callbacks are null (not registered beforehand).
If MspInit or MspDeInit are not null, the HAL_I2S_Init()/ HAL_I2S_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in HAL_I2S_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in HAL_I2S_STATE_READY or HAL_I2S_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
Then, the user first registers the MspInit/MspDeInit user callbacks
using HAL_I2S_RegisterCallback() before calling HAL_I2S_DeInit()
or HAL_I2S_Init() function.
[..]
When the compilation define USE_HAL_I2S_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registering feature is not available
and weak (surcharged) callbacks are used.
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#ifdef HAL_I2S_MODULE_ENABLED
#if defined(SPI_I2S_SUPPORT)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup I2S I2S
* @brief I2S HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define I2S_TIMEOUT_FLAG 100U /*!< Timeout 100 ms */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup I2S_Private_Functions I2S Private Functions
* @{
*/
static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma);
static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma);
static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
static void I2S_DMAError(DMA_HandleTypeDef *hdma);
static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s);
static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s);
static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State,
uint32_t Timeout);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup I2S_Exported_Functions I2S Exported Functions
* @{
*/
/** @defgroup I2S_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
de-initialize the I2Sx peripheral in simplex mode:
(+) User must Implement HAL_I2S_MspInit() function in which he configures
all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
(+) Call the function HAL_I2S_Init() to configure the selected device with
the selected configuration:
(++) Mode
(++) Standard
(++) Data Format
(++) MCLK Output
(++) Audio frequency
(++) Polarity
(+) Call the function HAL_I2S_DeInit() to restore the default configuration
of the selected I2Sx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initializes the I2S according to the specified parameters
* in the I2S_InitTypeDef and create the associated handle.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s)
{
uint32_t i2sdiv;
uint32_t i2sodd;
uint32_t packetlength;
uint32_t tmp;
uint32_t i2sclk;
/* Check the I2S handle allocation */
if (hi2s == NULL)
{
return HAL_ERROR;
}
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance));
assert_param(IS_I2S_MODE(hi2s->Init.Mode));
assert_param(IS_I2S_STANDARD(hi2s->Init.Standard));
assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat));
assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput));
assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq));
assert_param(IS_I2S_CPOL(hi2s->Init.CPOL));
if (hi2s->State == HAL_I2S_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hi2s->Lock = HAL_UNLOCKED;
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
/* Init the I2S Callback settings */
hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */
hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */
hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */
hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */
hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */
if (hi2s->MspInitCallback == NULL)
{
hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware : GPIO, CLOCK, NVIC... */
hi2s->MspInitCallback(hi2s);
#else
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
HAL_I2S_MspInit(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
hi2s->State = HAL_I2S_STATE_BUSY;
/*----------------------- SPIx I2SCFGR & I2SPR Configuration ----------------*/
/* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */
CLEAR_BIT(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \
SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \
SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD));
hi2s->Instance->I2SPR = 0x0002U;
/*----------------------- I2SPR: I2SDIV and ODD Calculation -----------------*/
/* If the requested audio frequency is not the default, compute the prescaler */
if (hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT)
{
/* Check the frame length (For the Prescaler computing) ********************/
if (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B)
{
/* Packet length is 16 bits */
packetlength = 16U;
}
else
{
/* Packet length is 32 bits */
packetlength = 32U;
}
/* I2S standard */
if (hi2s->Init.Standard <= I2S_STANDARD_LSB)
{
/* In I2S standard packet length is multiplied by 2 */
packetlength = packetlength * 2U;
}
/* Get the source clock value: based on System Clock value */
i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_I2S);
/* Compute the Real divider depending on the MCLK output state, with a floating point */
if (hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE)
{
/* MCLK output is enabled */
if (hi2s->Init.DataFormat != I2S_DATAFORMAT_16B)
{
tmp = (uint32_t)(((((i2sclk / (packetlength * 4U)) * 10U) / hi2s->Init.AudioFreq)) + 5U);
}
else
{
tmp = (uint32_t)(((((i2sclk / (packetlength * 8U)) * 10U) / hi2s->Init.AudioFreq)) + 5U);
}
}
else
{
/* MCLK output is disabled */
tmp = (uint32_t)(((((i2sclk / packetlength) * 10U) / hi2s->Init.AudioFreq)) + 5U);
}
/* Remove the flatting point */
tmp = tmp / 10U;
/* Check the parity of the divider */
i2sodd = (uint32_t)(tmp & (uint32_t)1U);
/* Compute the i2sdiv prescaler */
i2sdiv = (uint32_t)((tmp - i2sodd) / 2U);
/* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */
i2sodd = (uint32_t)(i2sodd << 8U);
}
else
{
/* Set the default values */
i2sdiv = 2U;
i2sodd = 0U;
}
/* Test if the divider is 1 or 0 or greater than 0xFF */
if ((i2sdiv < 2U) || (i2sdiv > 0xFFU))
{
/* Set the error code and execute error callback*/
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_PRESCALER);
return HAL_ERROR;
}
/*----------------------- SPIx I2SCFGR & I2SPR Configuration ----------------*/
/* Write to SPIx I2SPR register the computed value */
hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput));
/* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */
/* And configure the I2S with the I2S_InitStruct values */
MODIFY_REG(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \
SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD | \
SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \
SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD), \
(SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | \
hi2s->Init.Standard | hi2s->Init.DataFormat | \
hi2s->Init.CPOL));
#if defined(SPI_I2SCFGR_ASTRTEN)
if ((hi2s->Init.Standard == I2S_STANDARD_PCM_SHORT) || ((hi2s->Init.Standard == I2S_STANDARD_PCM_LONG)))
{
/* Write to SPIx I2SCFGR */
SET_BIT(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_ASTRTEN);
}
#endif /* SPI_I2SCFGR_ASTRTEN */
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->State = HAL_I2S_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the I2S peripheral
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s)
{
/* Check the I2S handle allocation */
if (hi2s == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance));
hi2s->State = HAL_I2S_STATE_BUSY;
/* Disable the I2S Peripheral Clock */
__HAL_I2S_DISABLE(hi2s);
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
if (hi2s->MspDeInitCallback == NULL)
{
hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
hi2s->MspDeInitCallback(hi2s);
#else
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
HAL_I2S_MspDeInit(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->State = HAL_I2S_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief I2S MSP Init
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_MspInit could be implemented in the user file
*/
}
/**
* @brief I2S MSP DeInit
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_MspDeInit could be implemented in the user file
*/
}
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
/**
* @brief Register a User I2S Callback
* To be used instead of the weak predefined callback
* @param hi2s Pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for the specified I2S.
* @param CallbackID ID of the callback to be registered
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_RegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID,
pI2S_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hi2s->ErrorCode |= HAL_I2S_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hi2s);
if (HAL_I2S_STATE_READY == hi2s->State)
{
switch (CallbackID)
{
case HAL_I2S_TX_COMPLETE_CB_ID :
hi2s->TxCpltCallback = pCallback;
break;
case HAL_I2S_RX_COMPLETE_CB_ID :
hi2s->RxCpltCallback = pCallback;
break;
case HAL_I2S_TX_HALF_COMPLETE_CB_ID :
hi2s->TxHalfCpltCallback = pCallback;
break;
case HAL_I2S_RX_HALF_COMPLETE_CB_ID :
hi2s->RxHalfCpltCallback = pCallback;
break;
case HAL_I2S_ERROR_CB_ID :
hi2s->ErrorCallback = pCallback;
break;
case HAL_I2S_MSPINIT_CB_ID :
hi2s->MspInitCallback = pCallback;
break;
case HAL_I2S_MSPDEINIT_CB_ID :
hi2s->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_I2S_STATE_RESET == hi2s->State)
{
switch (CallbackID)
{
case HAL_I2S_MSPINIT_CB_ID :
hi2s->MspInitCallback = pCallback;
break;
case HAL_I2S_MSPDEINIT_CB_ID :
hi2s->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2s);
return status;
}
/**
* @brief Unregister an I2S Callback
* I2S callback is redirected to the weak predefined callback
* @param hi2s Pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for the specified I2S.
* @param CallbackID ID of the callback to be unregistered
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_UnRegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hi2s);
if (HAL_I2S_STATE_READY == hi2s->State)
{
switch (CallbackID)
{
case HAL_I2S_TX_COMPLETE_CB_ID :
hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */
break;
case HAL_I2S_RX_COMPLETE_CB_ID :
hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */
break;
case HAL_I2S_TX_HALF_COMPLETE_CB_ID :
hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */
break;
case HAL_I2S_RX_HALF_COMPLETE_CB_ID :
hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */
break;
case HAL_I2S_ERROR_CB_ID :
hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_I2S_MSPINIT_CB_ID :
hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */
break;
case HAL_I2S_MSPDEINIT_CB_ID :
hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_I2S_STATE_RESET == hi2s->State)
{
switch (CallbackID)
{
case HAL_I2S_MSPINIT_CB_ID :
hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */
break;
case HAL_I2S_MSPDEINIT_CB_ID :
hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK);
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2s);
return status;
}
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup I2S_Exported_Functions_Group2 IO operation functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the I2S data
transfers.
(#) There are two modes of transfer:
(++) Blocking mode : The communication is performed in the polling mode.
The status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode : The communication is performed using Interrupts
or DMA. These functions return the status of the transfer startup.
The end of the data processing will be indicated through the
dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
(#) Blocking mode functions are :
(++) HAL_I2S_Transmit()
(++) HAL_I2S_Receive()
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_I2S_Transmit_IT()
(++) HAL_I2S_Receive_IT()
(#) No-Blocking mode functions with DMA are :
(++) HAL_I2S_Transmit_DMA()
(++) HAL_I2S_Receive_DMA()
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_I2S_TxCpltCallback()
(++) HAL_I2S_RxCpltCallback()
(++) HAL_I2S_ErrorCallback()
@endverbatim
* @{
*/
/**
* @brief Transmit an amount of data in blocking mode
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @param Timeout Timeout duration
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_TX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pTxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->TxXferSize = (Size << 1U);
hi2s->TxXferCount = (Size << 1U);
}
else
{
hi2s->TxXferSize = Size;
hi2s->TxXferCount = Size;
}
tmpreg_cfgr = hi2s->Instance->I2SCFGR;
/* Check if the I2S is already enabled */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
/* Wait until TXE flag is set */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
while (hi2s->TxXferCount > 0U)
{
hi2s->Instance->DR = (*hi2s->pTxBuffPtr);
hi2s->pTxBuffPtr++;
hi2s->TxXferCount--;
/* Wait until TXE flag is set */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
/* Check if an underrun occurs */
if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET)
{
/* Clear underrun flag */
__HAL_I2S_CLEAR_UDRFLAG(hi2s);
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR);
}
}
/* Check if Slave mode is selected */
if (((tmpreg_cfgr & SPI_I2SCFGR_I2SCFG) == I2S_MODE_SLAVE_TX)
|| ((tmpreg_cfgr & SPI_I2SCFGR_I2SCFG) == I2S_MODE_SLAVE_RX))
{
/* Wait until Busy flag is reset */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, RESET, Timeout) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
}
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Receive an amount of data in blocking mode
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @param Timeout Timeout duration
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate
* in continuous way and as the I2S is not disabled at the end of the I2S transaction.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_RX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pRxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->RxXferSize = (Size << 1U);
hi2s->RxXferCount = (Size << 1U);
}
else
{
hi2s->RxXferSize = Size;
hi2s->RxXferCount = Size;
}
/* Check if the I2S is already enabled */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
/* Check if Master Receiver mode is selected */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
{
/* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read
access to the SPI_SR register. */
__HAL_I2S_CLEAR_OVRFLAG(hi2s);
}
/* Receive data */
while (hi2s->RxXferCount > 0U)
{
/* Wait until RXNE flag is set */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, SET, Timeout) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
(*hi2s->pRxBuffPtr) = (uint16_t)hi2s->Instance->DR;
hi2s->pRxBuffPtr++;
hi2s->RxXferCount--;
/* Check if an overrun occurs */
if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET)
{
/* Clear overrun flag */
__HAL_I2S_CLEAR_OVRFLAG(hi2s);
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR);
}
}
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Transmit an amount of data in non-blocking mode with Interrupt
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_TX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pTxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->TxXferSize = (Size << 1U);
hi2s->TxXferCount = (Size << 1U);
}
else
{
hi2s->TxXferSize = Size;
hi2s->TxXferCount = Size;
}
/* Enable TXE and ERR interrupt */
__HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
/* Check if the I2S is already enabled */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Receive an amount of data in non-blocking mode with Interrupt
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to the Receive data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @note It is recommended to use DMA for the I2S receiver to avoid de-synchronization
* between Master and Slave otherwise the I2S interrupt should be optimized.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_RX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pRxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->RxXferSize = (Size << 1U);
hi2s->RxXferCount = (Size << 1U);
}
else
{
hi2s->RxXferSize = Size;
hi2s->RxXferCount = Size;
}
/* Enable RXNE and ERR interrupt */
__HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR));
/* Check if the I2S is already enabled */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE)
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Transmit an amount of data in non-blocking mode with DMA
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to the Transmit data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_TX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pTxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->TxXferSize = (Size << 1U);
hi2s->TxXferCount = (Size << 1U);
}
else
{
hi2s->TxXferSize = Size;
hi2s->TxXferCount = Size;
}
/* Set the I2S Tx DMA Half transfer complete callback */
hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt;
/* Set the I2S Tx DMA transfer complete callback */
hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt;
/* Set the DMA error callback */
hi2s->hdmatx->XferErrorCallback = I2S_DMAError;
/* Enable the Tx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hi2s->hdmatx,
(uint32_t)hi2s->pTxBuffPtr,
(uint32_t)&hi2s->Instance->DR,
hi2s->TxXferSize))
{
/* Update SPI error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
/* Check if the I2S is already enabled */
if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE))
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
/* Check if the I2S Tx request is already enabled */
if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN))
{
/* Enable Tx DMA Request */
SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN);
}
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Receive an amount of data in non-blocking mode with DMA
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param pData a 16-bit pointer to the Receive data buffer.
* @param Size number of data sample to be sent:
* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S
* configuration phase, the Size parameter means the number of 16-bit data length
* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected
* the Size parameter means the number of 24-bit or 32-bit data length.
* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization
* between Master and Slave(example: audio streaming).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size)
{
uint32_t tmpreg_cfgr;
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State != HAL_I2S_STATE_READY)
{
__HAL_UNLOCK(hi2s);
return HAL_BUSY;
}
/* Set state and reset error code */
hi2s->State = HAL_I2S_STATE_BUSY_RX;
hi2s->ErrorCode = HAL_I2S_ERROR_NONE;
hi2s->pRxBuffPtr = pData;
tmpreg_cfgr = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN);
if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B))
{
hi2s->RxXferSize = (Size << 1U);
hi2s->RxXferCount = (Size << 1U);
}
else
{
hi2s->RxXferSize = Size;
hi2s->RxXferCount = Size;
}
/* Set the I2S Rx DMA Half transfer complete callback */
hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt;
/* Set the I2S Rx DMA transfer complete callback */
hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt;
/* Set the DMA error callback */
hi2s->hdmarx->XferErrorCallback = I2S_DMAError;
/* Check if Master Receiver mode is selected */
if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX)
{
/* Clear the Overrun Flag by a read operation to the SPI_DR register followed by a read
access to the SPI_SR register. */
__HAL_I2S_CLEAR_OVRFLAG(hi2s);
}
/* Enable the Rx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, (uint32_t)hi2s->pRxBuffPtr,
hi2s->RxXferSize))
{
/* Update SPI error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA);
hi2s->State = HAL_I2S_STATE_READY;
__HAL_UNLOCK(hi2s);
return HAL_ERROR;
}
/* Check if the I2S is already enabled */
if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE))
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
/* Check if the I2S Rx request is already enabled */
if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN))
{
/* Enable Rx DMA Request */
SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN);
}
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Pauses the audio DMA Stream/Channel playing from the Media.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s)
{
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State == HAL_I2S_STATE_BUSY_TX)
{
/* Disable the I2S DMA Tx request */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN);
}
else if (hi2s->State == HAL_I2S_STATE_BUSY_RX)
{
/* Disable the I2S DMA Rx request */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN);
}
else
{
/* nothing to do */
}
/* Process Unlocked */
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Resumes the audio DMA Stream/Channel playing from the Media.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s)
{
/* Process Locked */
__HAL_LOCK(hi2s);
if (hi2s->State == HAL_I2S_STATE_BUSY_TX)
{
/* Enable the I2S DMA Tx request */
SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN);
}
else if (hi2s->State == HAL_I2S_STATE_BUSY_RX)
{
/* Enable the I2S DMA Rx request */
SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN);
}
else
{
/* nothing to do */
}
/* If the I2S peripheral is still not enabled, enable it */
if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE))
{
/* Enable I2S peripheral */
__HAL_I2S_ENABLE(hi2s);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2s);
return HAL_OK;
}
/**
* @brief Stops the audio DMA Stream/Channel playing from the Media.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s)
{
HAL_StatusTypeDef errorcode = HAL_OK;
/* The Lock is not implemented on this API to allow the user application
to call the HAL SPI API under callbacks HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback()
when calling HAL_DMA_Abort() API the DMA TX or RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback()
*/
if ((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX))
{
/* Abort the I2S DMA tx Stream/Channel */
if (hi2s->hdmatx != NULL)
{
/* Disable the I2S DMA tx Stream/Channel */
if (HAL_OK != HAL_DMA_Abort(hi2s->hdmatx))
{
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA);
errorcode = HAL_ERROR;
}
}
/* Wait until TXE flag is set */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, I2S_TIMEOUT_FLAG) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
errorcode = HAL_ERROR;
}
/* Wait until BSY flag is Reset */
if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, RESET, I2S_TIMEOUT_FLAG) != HAL_OK)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT);
hi2s->State = HAL_I2S_STATE_READY;
errorcode = HAL_ERROR;
}
/* Disable I2S peripheral */
__HAL_I2S_DISABLE(hi2s);
/* Clear UDR flag */
__HAL_I2S_CLEAR_UDRFLAG(hi2s);
/* Disable the I2S Tx DMA requests */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN);
}
else if ((hi2s->Init.Mode == I2S_MODE_MASTER_RX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_RX))
{
/* Abort the I2S DMA rx Stream/Channel */
if (hi2s->hdmarx != NULL)
{
/* Disable the I2S DMA rx Stream/Channel */
if (HAL_OK != HAL_DMA_Abort(hi2s->hdmarx))
{
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA);
errorcode = HAL_ERROR;
}
}
/* Disable I2S peripheral */
__HAL_I2S_DISABLE(hi2s);
/* Clear OVR flag */
__HAL_I2S_CLEAR_OVRFLAG(hi2s);
/* Disable the I2S Rx DMA request */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN);
if (hi2s->Init.Mode == I2S_MODE_SLAVE_RX)
{
/* Set the error code */
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_BUSY_LINE_RX);
/* Set the I2S State ready */
hi2s->State = HAL_I2S_STATE_READY;
errorcode = HAL_ERROR;
}
else
{
/* Read DR to Flush RX Data */
READ_REG((hi2s->Instance)->DR);
}
}
hi2s->State = HAL_I2S_STATE_READY;
return errorcode;
}
/**
* @brief This function handles I2S interrupt request.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s)
{
uint32_t itsource = hi2s->Instance->CR2;
uint32_t itflag = hi2s->Instance->SR;
/* I2S in mode Receiver ------------------------------------------------*/
if ((I2S_CHECK_FLAG(itflag, I2S_FLAG_OVR) == RESET) &&
(I2S_CHECK_FLAG(itflag, I2S_FLAG_RXNE) != RESET) && (I2S_CHECK_IT_SOURCE(itsource, I2S_IT_RXNE) != RESET))
{
I2S_Receive_IT(hi2s);
return;
}
/* I2S in mode Tramitter -----------------------------------------------*/
if ((I2S_CHECK_FLAG(itflag, I2S_FLAG_TXE) != RESET) && (I2S_CHECK_IT_SOURCE(itsource, I2S_IT_TXE) != RESET))
{
I2S_Transmit_IT(hi2s);
return;
}
/* I2S interrupt error -------------------------------------------------*/
if (I2S_CHECK_IT_SOURCE(itsource, I2S_IT_ERR) != RESET)
{
/* I2S Overrun error interrupt occurred ---------------------------------*/
if (I2S_CHECK_FLAG(itflag, I2S_FLAG_OVR) != RESET)
{
/* Disable RXNE and ERR interrupt */
__HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR));
/* Set the error code and execute error callback*/
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR);
}
/* I2S Underrun error interrupt occurred --------------------------------*/
if (I2S_CHECK_FLAG(itflag, I2S_FLAG_UDR) != RESET)
{
/* Disable TXE and ERR interrupt */
__HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
/* Set the error code and execute error callback*/
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR);
}
/* Set the I2S State ready */
hi2s->State = HAL_I2S_STATE_READY;
/* Call user error callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->ErrorCallback(hi2s);
#else
HAL_I2S_ErrorCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
}
/**
* @brief Tx Transfer Half completed callbacks
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_TxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief Tx Transfer completed callbacks
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_TxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer half completed callbacks
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_RxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief I2S error callbacks
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
__weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2s);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_I2S_ErrorCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup I2S_Exported_Functions_Group3 Peripheral State and Errors functions
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State and Errors functions #####
===============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the I2S state
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval HAL state
*/
HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s)
{
return hi2s->State;
}
/**
* @brief Return the I2S error code
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval I2S Error Code
*/
uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s)
{
return hi2s->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup I2S_Private_Functions I2S Private Functions
* @{
*/
/**
* @brief DMA I2S transmit process complete callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma)
{
I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */
/* if DMA is configured in DMA_NORMAL Mode */
if (hdma->Init.Mode == DMA_NORMAL)
{
/* Disable Tx DMA Request */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN);
hi2s->TxXferCount = 0U;
hi2s->State = HAL_I2S_STATE_READY;
}
/* Call user Tx complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->TxCpltCallback(hi2s);
#else
HAL_I2S_TxCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
/**
* @brief DMA I2S transmit process half complete callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
{
I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */
/* Call user Tx half complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->TxHalfCpltCallback(hi2s);
#else
HAL_I2S_TxHalfCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
/**
* @brief DMA I2S receive process complete callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma)
{
I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */
/* if DMA is configured in DMA_NORMAL Mode */
if (hdma->Init.Mode == DMA_NORMAL)
{
/* Disable Rx DMA Request */
CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN);
hi2s->RxXferCount = 0U;
hi2s->State = HAL_I2S_STATE_READY;
}
/* Call user Rx complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->RxCpltCallback(hi2s);
#else
HAL_I2S_RxCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
/**
* @brief DMA I2S receive process half complete callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */
/* Call user Rx half complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->RxHalfCpltCallback(hi2s);
#else
HAL_I2S_RxHalfCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
/**
* @brief DMA I2S communication error callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void I2S_DMAError(DMA_HandleTypeDef *hdma)
{
I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */
/* Disable Rx and Tx DMA Request */
CLEAR_BIT(hi2s->Instance->CR2, (SPI_CR2_RXDMAEN | SPI_CR2_TXDMAEN));
hi2s->TxXferCount = 0U;
hi2s->RxXferCount = 0U;
hi2s->State = HAL_I2S_STATE_READY;
/* Set the error code and execute error callback*/
SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA);
/* Call user error callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->ErrorCallback(hi2s);
#else
HAL_I2S_ErrorCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
/**
* @brief Transmit an amount of data in non-blocking mode with Interrupt
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s)
{
/* Transmit data */
hi2s->Instance->DR = (*hi2s->pTxBuffPtr);
hi2s->pTxBuffPtr++;
hi2s->TxXferCount--;
if (hi2s->TxXferCount == 0U)
{
/* Disable TXE and ERR interrupt */
__HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR));
hi2s->State = HAL_I2S_STATE_READY;
/* Call user Tx complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->TxCpltCallback(hi2s);
#else
HAL_I2S_TxCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
}
/**
* @brief Receive an amount of data in non-blocking mode with Interrupt
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @retval None
*/
static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s)
{
/* Receive data */
(*hi2s->pRxBuffPtr) = (uint16_t)hi2s->Instance->DR;
hi2s->pRxBuffPtr++;
hi2s->RxXferCount--;
if (hi2s->RxXferCount == 0U)
{
/* Disable RXNE and ERR interrupt */
__HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR));
hi2s->State = HAL_I2S_STATE_READY;
/* Call user Rx complete callback */
#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U)
hi2s->RxCpltCallback(hi2s);
#else
HAL_I2S_RxCpltCallback(hi2s);
#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */
}
}
/**
* @brief This function handles I2S Communication Timeout.
* @param hi2s pointer to a I2S_HandleTypeDef structure that contains
* the configuration information for I2S module
* @param Flag Flag checked
* @param State Value of the flag expected
* @param Timeout Duration of the timeout
* @retval HAL status
*/
static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State,
uint32_t Timeout)
{
uint32_t tickstart;
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until flag is set to status*/
while (((__HAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U))
{
/* Set the I2S State ready */
hi2s->State = HAL_I2S_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2s);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* SPI_I2S_SUPPORT */
#endif /* HAL_I2S_MODULE_ENABLED */
| 61,668 |
C
| 32.155376 | 123 | 0.622608 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_lptim.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_lptim.c
* @author MCD Application Team
* @brief LPTIM HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Low Power Timer (LPTIM) peripheral:
* + Initialization and de-initialization functions.
* + Start/Stop operation functions in polling mode.
* + Start/Stop operation functions in interrupt mode.
* + Reading operation functions.
* + Peripheral State functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The LPTIM HAL driver can be used as follows:
(#)Initialize the LPTIM low level resources by implementing the
HAL_LPTIM_MspInit():
(++) Enable the LPTIM interface clock using __HAL_RCC_LPTIMx_CLK_ENABLE().
(++) In case of using interrupts (e.g. HAL_LPTIM_PWM_Start_IT()):
(+++) Configure the LPTIM interrupt priority using HAL_NVIC_SetPriority().
(+++) Enable the LPTIM IRQ handler using HAL_NVIC_EnableIRQ().
(+++) In LPTIM IRQ handler, call HAL_LPTIM_IRQHandler().
(#)Initialize the LPTIM HAL using HAL_LPTIM_Init(). This function
configures mainly:
(++) The instance: LPTIM1.
(++) Clock: the counter clock.
(+++) Source : it can be either the ULPTIM input (IN1) or one of
the internal clock; (APB, LSE or LSI).
(+++) Prescaler: select the clock divider.
(++) UltraLowPowerClock : To be used only if the ULPTIM is selected
as counter clock source.
(+++) Polarity: polarity of the active edge for the counter unit
if the ULPTIM input is selected.
(+++) SampleTime: clock sampling time to configure the clock glitch
filter.
(++) Trigger: How the counter start.
(+++) Source: trigger can be software or one of the hardware triggers.
(+++) ActiveEdge : only for hardware trigger.
(+++) SampleTime : trigger sampling time to configure the trigger
glitch filter.
(++) OutputPolarity : 2 opposite polarities are possible.
(++) UpdateMode: specifies whether the update of the autoreload and
the compare values is done immediately or after the end of current
period.
(++) Input1Source: Source selected for input1 (GPIO or comparator output).
(++) Input2Source: Source selected for input2 (GPIO or comparator output).
Input2 is used only for encoder feature so is used only for LPTIM1 instance.
(#)Six modes are available:
(++) PWM Mode: To generate a PWM signal with specified period and pulse,
call HAL_LPTIM_PWM_Start() or HAL_LPTIM_PWM_Start_IT() for interruption
mode.
(++) One Pulse Mode: To generate pulse with specified width in response
to a stimulus, call HAL_LPTIM_OnePulse_Start() or
HAL_LPTIM_OnePulse_Start_IT() for interruption mode.
(++) Set once Mode: In this mode, the output changes the level (from
low level to high level if the output polarity is configured high, else
the opposite) when a compare match occurs. To start this mode, call
HAL_LPTIM_SetOnce_Start() or HAL_LPTIM_SetOnce_Start_IT() for
interruption mode.
(++) Encoder Mode: To use the encoder interface call
HAL_LPTIM_Encoder_Start() or HAL_LPTIM_Encoder_Start_IT() for
interruption mode. Only available for LPTIM1 instance.
(++) Time out Mode: an active edge on one selected trigger input rests
the counter. The first trigger event will start the timer, any
successive trigger event will reset the counter and the timer will
restart. To start this mode call HAL_LPTIM_TimeOut_Start_IT() or
HAL_LPTIM_TimeOut_Start_IT() for interruption mode.
(++) Counter Mode: counter can be used to count external events on
the LPTIM Input1 or it can be used to count internal clock cycles.
To start this mode, call HAL_LPTIM_Counter_Start() or
HAL_LPTIM_Counter_Start_IT() for interruption mode.
(#) User can stop any process by calling the corresponding API:
HAL_LPTIM_Xxx_Stop() or HAL_LPTIM_Xxx_Stop_IT() if the process is
already started in interruption mode.
(#) De-initialize the LPTIM peripheral using HAL_LPTIM_DeInit().
*** Callback registration ***
=============================================
[..]
The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
[..]
Use Function HAL_LPTIM_RegisterCallback() to register a callback.
HAL_LPTIM_RegisterCallback() takes as parameters the HAL peripheral handle,
the Callback ID and a pointer to the user callback function.
[..]
Use function HAL_LPTIM_UnRegisterCallback() to reset a callback to the
default weak function.
HAL_LPTIM_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
[..]
These functions allow to register/unregister following callbacks:
(+) MspInitCallback : LPTIM Base Msp Init Callback.
(+) MspDeInitCallback : LPTIM Base Msp DeInit Callback.
(+) CompareMatchCallback : Compare match Callback.
(+) AutoReloadMatchCallback : Auto-reload match Callback.
(+) TriggerCallback : External trigger event detection Callback.
(+) CompareWriteCallback : Compare register write complete Callback.
(+) AutoReloadWriteCallback : Auto-reload register write complete Callback.
(+) DirectionUpCallback : Up-counting direction change Callback.
(+) DirectionDownCallback : Down-counting direction change Callback.
[..]
By default, after the Init and when the state is HAL_LPTIM_STATE_RESET
all interrupt callbacks are set to the corresponding weak functions:
examples HAL_LPTIM_TriggerCallback(), HAL_LPTIM_CompareMatchCallback().
[..]
Exception done for MspInit and MspDeInit functions that are reset to the legacy weak
functionalities in the Init/DeInit only when these callbacks are null
(not registered beforehand). If not, MspInit or MspDeInit are not null, the Init/DeInit
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
[..]
Callbacks can be registered/unregistered in HAL_LPTIM_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_LPTIM_STATE_READY or HAL_LPTIM_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_LPTIM_RegisterCallback() before calling DeInit or Init function.
[..]
When The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available and all callbacks
are set to the corresponding weak functions.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup LPTIM LPTIM
* @brief LPTIM HAL module driver.
* @{
*/
#ifdef HAL_LPTIM_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup LPTIM_Private_Constants
* @{
*/
#define TIMEOUT 1000UL /* Timeout is 1s */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
static HAL_StatusTypeDef LPTIM_WaitForFlag(LPTIM_HandleTypeDef *hlptim, uint32_t flag);
/* Exported functions --------------------------------------------------------*/
/** @defgroup LPTIM_Exported_Functions LPTIM Exported Functions
* @{
*/
/** @defgroup LPTIM_Exported_Functions_Group1 Initialization/de-initialization functions
* @brief Initialization and Configuration functions.
*
@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Initialize the LPTIM according to the specified parameters in the
LPTIM_InitTypeDef and initialize the associated handle.
(+) DeInitialize the LPTIM peripheral.
(+) Initialize the LPTIM MSP.
(+) DeInitialize the LPTIM MSP.
@endverbatim
* @{
*/
/**
* @brief Initialize the LPTIM according to the specified parameters in the
* LPTIM_InitTypeDef and initialize the associated handle.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim)
{
uint32_t tmpcfgr;
/* Check the LPTIM handle allocation */
if (hlptim == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_CLOCK_SOURCE(hlptim->Init.Clock.Source));
assert_param(IS_LPTIM_CLOCK_PRESCALER(hlptim->Init.Clock.Prescaler));
if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM)
|| (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL))
{
assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity));
assert_param(IS_LPTIM_CLOCK_SAMPLE_TIME(hlptim->Init.UltraLowPowerClock.SampleTime));
}
assert_param(IS_LPTIM_TRG_SOURCE(hlptim->Init.Trigger.Source));
if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE)
{
assert_param(IS_LPTIM_EXT_TRG_POLARITY(hlptim->Init.Trigger.ActiveEdge));
assert_param(IS_LPTIM_TRIG_SAMPLE_TIME(hlptim->Init.Trigger.SampleTime));
}
assert_param(IS_LPTIM_OUTPUT_POLARITY(hlptim->Init.OutputPolarity));
assert_param(IS_LPTIM_UPDATE_MODE(hlptim->Init.UpdateMode));
assert_param(IS_LPTIM_COUNTER_SOURCE(hlptim->Init.CounterSource));
if (hlptim->State == HAL_LPTIM_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hlptim->Lock = HAL_UNLOCKED;
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
/* Reset interrupt callbacks to legacy weak callbacks */
LPTIM_ResetCallback(hlptim);
if (hlptim->MspInitCallback == NULL)
{
hlptim->MspInitCallback = HAL_LPTIM_MspInit;
}
/* Init the low level hardware : GPIO, CLOCK, NVIC */
hlptim->MspInitCallback(hlptim);
#else
/* Init the low level hardware : GPIO, CLOCK, NVIC */
HAL_LPTIM_MspInit(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
/* Change the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Get the LPTIMx CFGR value */
tmpcfgr = hlptim->Instance->CFGR;
if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM)
|| (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL))
{
tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKPOL | LPTIM_CFGR_CKFLT));
}
if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE)
{
tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_TRGFLT | LPTIM_CFGR_TRIGSEL));
}
/* Clear CKSEL, PRESC, TRIGEN, TRGFLT, WAVPOL, PRELOAD & COUNTMODE bits */
tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKSEL | LPTIM_CFGR_TRIGEN | LPTIM_CFGR_PRELOAD |
LPTIM_CFGR_WAVPOL | LPTIM_CFGR_PRESC | LPTIM_CFGR_COUNTMODE));
/* Set initialization parameters */
tmpcfgr |= (hlptim->Init.Clock.Source |
hlptim->Init.Clock.Prescaler |
hlptim->Init.OutputPolarity |
hlptim->Init.UpdateMode |
hlptim->Init.CounterSource);
/* Glitch filters for internal triggers and external inputs are configured
* only if an internal clock source is provided to the LPTIM
*/
if (hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC)
{
tmpcfgr |= (hlptim->Init.Trigger.SampleTime |
hlptim->Init.UltraLowPowerClock.SampleTime);
}
/* Configure LPTIM external clock polarity and digital filter */
if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM)
|| (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL))
{
tmpcfgr |= (hlptim->Init.UltraLowPowerClock.Polarity |
hlptim->Init.UltraLowPowerClock.SampleTime);
}
/* Configure LPTIM external trigger */
if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Enable External trigger and set the trigger source */
tmpcfgr |= (hlptim->Init.Trigger.Source |
hlptim->Init.Trigger.ActiveEdge |
hlptim->Init.Trigger.SampleTime);
}
/* Write to LPTIMx CFGR */
hlptim->Instance->CFGR = tmpcfgr;
/* Configure LPTIM input sources */
if (hlptim->Instance == LPTIM1)
{
/* Check LPTIM Input1 and Input2 sources */
assert_param(IS_LPTIM_INPUT1_SOURCE(hlptim->Instance, hlptim->Init.Input1Source));
assert_param(IS_LPTIM_INPUT2_SOURCE(hlptim->Instance, hlptim->Init.Input2Source));
/* Configure LPTIM Input1 and Input2 sources */
hlptim->Instance->OR = (hlptim->Init.Input1Source | hlptim->Init.Input2Source);
}
/* Change the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief DeInitialize the LPTIM peripheral.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim)
{
/* Check the LPTIM handle allocation */
if (hlptim == NULL)
{
return HAL_ERROR;
}
/* Change the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the LPTIM Peripheral Clock */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
if (hlptim->MspDeInitCallback == NULL)
{
hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit;
}
/* DeInit the low level hardware: CLOCK, NVIC.*/
hlptim->MspDeInitCallback(hlptim);
#else
/* DeInit the low level hardware: CLOCK, NVIC.*/
HAL_LPTIM_MspDeInit(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
/* Change the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hlptim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initialize the LPTIM MSP.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize LPTIM MSP.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup LPTIM_Exported_Functions_Group2 LPTIM Start-Stop operation functions
* @brief Start-Stop operation functions.
*
@verbatim
==============================================================================
##### LPTIM Start Stop operation functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Start the PWM mode.
(+) Stop the PWM mode.
(+) Start the One pulse mode.
(+) Stop the One pulse mode.
(+) Start the Set once mode.
(+) Stop the Set once mode.
(+) Start the Encoder mode.
(+) Stop the Encoder mode.
(+) Start the Timeout mode.
(+) Stop the Timeout mode.
(+) Start the Counter mode.
(+) Stop the Counter mode.
@endverbatim
* @{
*/
/**
* @brief Start the LPTIM PWM generation.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Reset WAVE bit to set PWM mode */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM PWM generation.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the LPTIM PWM generation in interrupt mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Reset WAVE bit to set PWM mode */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable Autoreload write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Enable Compare write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Enable Autoreload match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Enable Compare match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then enable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Enable external trigger interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM PWM generation in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable Autoreload write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Disable Compare write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Disable Autoreload match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Disable Compare match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then disable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Disable external trigger interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the LPTIM One pulse generation.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Reset WAVE bit to set one pulse mode */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in single (one shot) mode */
__HAL_LPTIM_START_SINGLE(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM One pulse generation.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the LPTIM One pulse generation in interrupt mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Reset WAVE bit to set one pulse mode */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable Autoreload write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Enable Compare write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Enable Autoreload match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Enable Compare match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then enable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Enable external trigger interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in single (one shot) mode */
__HAL_LPTIM_START_SINGLE(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM One pulse generation in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable Autoreload write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Disable Compare write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Disable Autoreload match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Disable Compare match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then disable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Disable external trigger interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the LPTIM in Set once mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Set WAVE bit to enable the set once mode */
hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in single (one shot) mode */
__HAL_LPTIM_START_SINGLE(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM Set once mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the LPTIM Set once mode in interrupt mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Pulse Specifies the compare value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Pulse));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Set WAVE bit to enable the set once mode */
hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the pulse value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Pulse);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable Autoreload write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Enable Compare write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Enable Autoreload match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Enable Compare match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then enable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Enable external trigger interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in single (one shot) mode */
__HAL_LPTIM_START_SINGLE(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the LPTIM Set once mode in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable Autoreload write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Disable Compare write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPOK);
/* Disable Autoreload match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Disable Compare match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPM);
/* If external trigger source is used, then disable external trigger interrupt */
if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE)
{
/* Disable external trigger interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG);
}
/* Change the LPTIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Encoder interface.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period)
{
uint32_t tmpcfgr;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC);
assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1);
assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Get the LPTIMx CFGR value */
tmpcfgr = hlptim->Instance->CFGR;
/* Clear CKPOL bits */
tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL);
/* Set Input polarity */
tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity;
/* Write to LPTIMx CFGR */
hlptim->Instance->CFGR = tmpcfgr;
/* Set ENC bit to enable the encoder interface */
hlptim->Instance->CFGR |= LPTIM_CFGR_ENC;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Encoder interface.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Reset ENC bit to disable the encoder interface */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC;
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Encoder interface in interrupt mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period)
{
uint32_t tmpcfgr;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC);
assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1);
assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Configure edge sensitivity for encoder mode */
/* Get the LPTIMx CFGR value */
tmpcfgr = hlptim->Instance->CFGR;
/* Clear CKPOL bits */
tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL);
/* Set Input polarity */
tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity;
/* Write to LPTIMx CFGR */
hlptim->Instance->CFGR = tmpcfgr;
/* Set ENC bit to enable the encoder interface */
hlptim->Instance->CFGR |= LPTIM_CFGR_ENC;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable "switch to down direction" interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_DOWN);
/* Enable "switch to up direction" interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_UP);
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Encoder interface in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Reset ENC bit to disable the encoder interface */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC;
/* Disable "switch to down direction" interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_DOWN);
/* Disable "switch to up direction" interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_UP);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Timeout function.
* @note The first trigger event will start the timer, any successive
* trigger event will reset the counter and the timer restarts.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Timeout Specifies the TimeOut value to reset the counter.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Timeout));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Set TIMOUT bit to enable the timeout function */
hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the Timeout value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Timeout);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Timeout function.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Reset TIMOUT bit to enable the timeout function */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT;
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Timeout function in interrupt mode.
* @note The first trigger event will start the timer, any successive
* trigger event will reset the counter and the timer restarts.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @param Timeout Specifies the TimeOut value to reset the counter.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
assert_param(IS_LPTIM_PULSE(Timeout));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */
__HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT();
/* Set TIMOUT bit to enable the timeout function */
hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT;
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Load the Timeout value in the compare register */
__HAL_LPTIM_COMPARE_SET(hlptim, Timeout);
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable Compare match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMPM);
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Timeout function in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */
__HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT();
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Reset TIMOUT bit to enable the timeout function */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT;
/* Disable Compare match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMPM);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Counter mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */
if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM)
&& (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL))
{
/* Check if clock is prescaled */
assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler));
/* Set clock prescaler to 0 */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC;
}
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Counter mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Start the Counter mode in interrupt mode.
* @param hlptim LPTIM handle
* @param Period Specifies the Autoreload value.
* This parameter must be a value between 0x0000 and 0xFFFF.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
assert_param(IS_LPTIM_PERIOD(Period));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */
__HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT();
/* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */
if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM)
&& (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL))
{
/* Check if clock is prescaled */
assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler));
/* Set clock prescaler to 0 */
hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC;
}
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Clear flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Enable Autoreload write complete interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Enable Autoreload match interrupt */
__HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Enable the Peripheral */
__HAL_LPTIM_ENABLE(hlptim);
/* Start timer in continuous mode */
__HAL_LPTIM_START_CONTINUOUS(hlptim);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the Counter mode in interrupt mode.
* @param hlptim LPTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
/* Set the LPTIM state */
hlptim->State = HAL_LPTIM_STATE_BUSY;
/* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */
__HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT();
/* Disable the Peripheral */
__HAL_LPTIM_DISABLE(hlptim);
if (HAL_LPTIM_GetState(hlptim) == HAL_LPTIM_STATE_TIMEOUT)
{
return HAL_TIMEOUT;
}
/* Disable Autoreload write complete interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK);
/* Disable Autoreload match interrupt */
__HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARRM);
/* Change the TIM state*/
hlptim->State = HAL_LPTIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup LPTIM_Exported_Functions_Group3 LPTIM Read operation functions
* @brief Read operation functions.
*
@verbatim
==============================================================================
##### LPTIM Read operation functions #####
==============================================================================
[..] This section provides LPTIM Reading functions.
(+) Read the counter value.
(+) Read the period (Auto-reload) value.
(+) Read the pulse (Compare)value.
@endverbatim
* @{
*/
/**
* @brief Return the current counter value.
* @param hlptim LPTIM handle
* @retval Counter value.
*/
uint32_t HAL_LPTIM_ReadCounter(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
return (hlptim->Instance->CNT);
}
/**
* @brief Return the current Autoreload (Period) value.
* @param hlptim LPTIM handle
* @retval Autoreload value.
*/
uint32_t HAL_LPTIM_ReadAutoReload(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
return (hlptim->Instance->ARR);
}
/**
* @brief Return the current Compare (Pulse) value.
* @param hlptim LPTIM handle
* @retval Compare value.
*/
uint32_t HAL_LPTIM_ReadCompare(LPTIM_HandleTypeDef *hlptim)
{
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(hlptim->Instance));
return (hlptim->Instance->CMP);
}
/**
* @}
*/
/** @defgroup LPTIM_Exported_Functions_Group4 LPTIM IRQ handler and callbacks
* @brief LPTIM IRQ handler.
*
@verbatim
==============================================================================
##### LPTIM IRQ handler and callbacks #####
==============================================================================
[..] This section provides LPTIM IRQ handler and callback functions called within
the IRQ handler:
(+) LPTIM interrupt request handler
(+) Compare match Callback
(+) Auto-reload match Callback
(+) External trigger event detection Callback
(+) Compare register write complete Callback
(+) Auto-reload register write complete Callback
(+) Up-counting direction change Callback
(+) Down-counting direction change Callback
@endverbatim
* @{
*/
/**
* @brief Handle LPTIM interrupt request.
* @param hlptim LPTIM handle
* @retval None
*/
void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim)
{
/* Compare match interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMPM) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMPM) != RESET)
{
/* Clear Compare match flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPM);
/* Compare match Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->CompareMatchCallback(hlptim);
#else
HAL_LPTIM_CompareMatchCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Autoreload match interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARRM) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARRM) != RESET)
{
/* Clear Autoreload match flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARRM);
/* Autoreload match Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->AutoReloadMatchCallback(hlptim);
#else
HAL_LPTIM_AutoReloadMatchCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Trigger detected interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_EXTTRIG) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_EXTTRIG) != RESET)
{
/* Clear Trigger detected flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_EXTTRIG);
/* Trigger detected callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->TriggerCallback(hlptim);
#else
HAL_LPTIM_TriggerCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Compare write interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMPOK) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMPOK) != RESET)
{
/* Clear Compare write flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
/* Compare write Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->CompareWriteCallback(hlptim);
#else
HAL_LPTIM_CompareWriteCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Autoreload write interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARROK) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARROK) != RESET)
{
/* Clear Autoreload write flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
/* Autoreload write Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->AutoReloadWriteCallback(hlptim);
#else
HAL_LPTIM_AutoReloadWriteCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Direction counter changed from Down to Up interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UP) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_UP) != RESET)
{
/* Clear Direction counter changed from Down to Up flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UP);
/* Direction counter changed from Down to Up Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->DirectionUpCallback(hlptim);
#else
HAL_LPTIM_DirectionUpCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
/* Direction counter changed from Up to Down interrupt */
if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_DOWN) != RESET)
{
if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_DOWN) != RESET)
{
/* Clear Direction counter changed from Up to Down flag */
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DOWN);
/* Direction counter changed from Up to Down Callback */
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
hlptim->DirectionDownCallback(hlptim);
#else
HAL_LPTIM_DirectionDownCallback(hlptim);
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
}
}
}
/**
* @brief Compare match callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_CompareMatchCallback could be implemented in the user file
*/
}
/**
* @brief Autoreload match callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_AutoReloadMatchCallback could be implemented in the user file
*/
}
/**
* @brief Trigger detected callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_TriggerCallback could be implemented in the user file
*/
}
/**
* @brief Compare write callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_CompareWriteCallback could be implemented in the user file
*/
}
/**
* @brief Autoreload write callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_AutoReloadWriteCallback could be implemented in the user file
*/
}
/**
* @brief Direction counter changed from Down to Up callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_DirectionUpCallback could be implemented in the user file
*/
}
/**
* @brief Direction counter changed from Up to Down callback in non-blocking mode.
* @param hlptim LPTIM handle
* @retval None
*/
__weak void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hlptim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_LPTIM_DirectionDownCallback could be implemented in the user file
*/
}
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User LPTIM callback to be used instead of the weak predefined callback
* @param hlptim LPTIM handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID
* @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID
* @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID
* @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID
* @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID
* @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID
* @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID
* @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID
* @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID
* @param pCallback pointer to the callback function
* @retval status
*/
HAL_StatusTypeDef HAL_LPTIM_RegisterCallback(LPTIM_HandleTypeDef *hlptim,
HAL_LPTIM_CallbackIDTypeDef CallbackID,
pLPTIM_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hlptim);
if (hlptim->State == HAL_LPTIM_STATE_READY)
{
switch (CallbackID)
{
case HAL_LPTIM_MSPINIT_CB_ID :
hlptim->MspInitCallback = pCallback;
break;
case HAL_LPTIM_MSPDEINIT_CB_ID :
hlptim->MspDeInitCallback = pCallback;
break;
case HAL_LPTIM_COMPARE_MATCH_CB_ID :
hlptim->CompareMatchCallback = pCallback;
break;
case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID :
hlptim->AutoReloadMatchCallback = pCallback;
break;
case HAL_LPTIM_TRIGGER_CB_ID :
hlptim->TriggerCallback = pCallback;
break;
case HAL_LPTIM_COMPARE_WRITE_CB_ID :
hlptim->CompareWriteCallback = pCallback;
break;
case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID :
hlptim->AutoReloadWriteCallback = pCallback;
break;
case HAL_LPTIM_DIRECTION_UP_CB_ID :
hlptim->DirectionUpCallback = pCallback;
break;
case HAL_LPTIM_DIRECTION_DOWN_CB_ID :
hlptim->DirectionDownCallback = pCallback;
break;
default :
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hlptim->State == HAL_LPTIM_STATE_RESET)
{
switch (CallbackID)
{
case HAL_LPTIM_MSPINIT_CB_ID :
hlptim->MspInitCallback = pCallback;
break;
case HAL_LPTIM_MSPDEINIT_CB_ID :
hlptim->MspDeInitCallback = pCallback;
break;
default :
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hlptim);
return status;
}
/**
* @brief Unregister a LPTIM callback
* LLPTIM callback is redirected to the weak predefined callback
* @param hlptim LPTIM handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID
* @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID
* @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID
* @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID
* @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID
* @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID
* @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID
* @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID
* @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID
* @retval status
*/
HAL_StatusTypeDef HAL_LPTIM_UnRegisterCallback(LPTIM_HandleTypeDef *hlptim,
HAL_LPTIM_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hlptim);
if (hlptim->State == HAL_LPTIM_STATE_READY)
{
switch (CallbackID)
{
case HAL_LPTIM_MSPINIT_CB_ID :
/* Legacy weak MspInit Callback */
hlptim->MspInitCallback = HAL_LPTIM_MspInit;
break;
case HAL_LPTIM_MSPDEINIT_CB_ID :
/* Legacy weak Msp DeInit Callback */
hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit;
break;
case HAL_LPTIM_COMPARE_MATCH_CB_ID :
/* Legacy weak Compare match Callback */
hlptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback;
break;
case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID :
/* Legacy weak Auto-reload match Callback */
hlptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback;
break;
case HAL_LPTIM_TRIGGER_CB_ID :
/* Legacy weak External trigger event detection Callback */
hlptim->TriggerCallback = HAL_LPTIM_TriggerCallback;
break;
case HAL_LPTIM_COMPARE_WRITE_CB_ID :
/* Legacy weak Compare register write complete Callback */
hlptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback;
break;
case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID :
/* Legacy weak Auto-reload register write complete Callback */
hlptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback;
break;
case HAL_LPTIM_DIRECTION_UP_CB_ID :
/* Legacy weak Up-counting direction change Callback */
hlptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback;
break;
case HAL_LPTIM_DIRECTION_DOWN_CB_ID :
/* Legacy weak Down-counting direction change Callback */
hlptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback;
break;
default :
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hlptim->State == HAL_LPTIM_STATE_RESET)
{
switch (CallbackID)
{
case HAL_LPTIM_MSPINIT_CB_ID :
/* Legacy weak MspInit Callback */
hlptim->MspInitCallback = HAL_LPTIM_MspInit;
break;
case HAL_LPTIM_MSPDEINIT_CB_ID :
/* Legacy weak Msp DeInit Callback */
hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit;
break;
default :
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hlptim);
return status;
}
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup LPTIM_Group5 Peripheral State functions
* @brief Peripheral State functions.
*
@verbatim
==============================================================================
##### Peripheral State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Return the LPTIM handle state.
* @param hlptim LPTIM handle
* @retval HAL state
*/
HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(LPTIM_HandleTypeDef *hlptim)
{
/* Return LPTIM handle state */
return hlptim->State;
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup LPTIM_Private_Functions LPTIM Private Functions
* @{
*/
#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1)
/**
* @brief Reset interrupt callbacks to the legacy weak callbacks.
* @param lptim pointer to a LPTIM_HandleTypeDef structure that contains
* the configuration information for LPTIM module.
* @retval None
*/
static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim)
{
/* Reset the LPTIM callback to the legacy weak callbacks */
lptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback;
lptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback;
lptim->TriggerCallback = HAL_LPTIM_TriggerCallback;
lptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback;
lptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback;
lptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback;
lptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback;
}
#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */
/**
* @brief LPTimer Wait for flag set
* @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains
* the configuration information for LPTIM module.
* @param flag The lptim flag
* @retval HAL status
*/
static HAL_StatusTypeDef LPTIM_WaitForFlag(LPTIM_HandleTypeDef *hlptim, uint32_t flag)
{
HAL_StatusTypeDef result = HAL_OK;
uint32_t count = TIMEOUT * (SystemCoreClock / 20UL / 1000UL);
do
{
count--;
if (count == 0UL)
{
result = HAL_TIMEOUT;
}
} while ((!(__HAL_LPTIM_GET_FLAG((hlptim), (flag)))) && (count != 0UL));
return result;
}
/**
* @brief Disable LPTIM HW instance.
* @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains
* the configuration information for LPTIM module.
* @note The following sequence is required to solve LPTIM disable HW limitation.
* Please check Errata Sheet ES0335 for more details under "MCU may remain
* stuck in LPTIM interrupt when entering Stop mode" section.
* @retval None
*/
void LPTIM_Disable(LPTIM_HandleTypeDef *hlptim)
{
uint32_t tmpclksource = 0;
uint32_t tmpIER;
uint32_t tmpCFGR;
uint32_t tmpCMP;
uint32_t tmpARR;
uint32_t primask_bit;
uint32_t tmpOR;
/* Enter critical section */
primask_bit = __get_PRIMASK();
__set_PRIMASK(1) ;
/*********** Save LPTIM Config ***********/
/* Save LPTIM source clock */
switch ((uint32_t)hlptim->Instance)
{
case LPTIM1_BASE:
tmpclksource = __HAL_RCC_GET_LPTIM1_SOURCE();
break;
default:
break;
}
/* Save LPTIM configuration registers */
tmpIER = hlptim->Instance->IER;
tmpCFGR = hlptim->Instance->CFGR;
tmpCMP = hlptim->Instance->CMP;
tmpARR = hlptim->Instance->ARR;
tmpOR = hlptim->Instance->OR;
/*********** Reset LPTIM ***********/
switch ((uint32_t)hlptim->Instance)
{
case LPTIM1_BASE:
__HAL_RCC_LPTIM1_FORCE_RESET();
__HAL_RCC_LPTIM1_RELEASE_RESET();
break;
default:
break;
}
/*********** Restore LPTIM Config ***********/
if ((tmpCMP != 0UL) || (tmpARR != 0UL))
{
/* Force LPTIM source kernel clock from APB */
switch ((uint32_t)hlptim->Instance)
{
case LPTIM1_BASE:
__HAL_RCC_LPTIM1_CONFIG(RCC_LPTIM1CLKSOURCE_PCLK1);
break;
default:
break;
}
if (tmpCMP != 0UL)
{
/* Restore CMP register (LPTIM should be enabled first) */
hlptim->Instance->CR |= LPTIM_CR_ENABLE;
hlptim->Instance->CMP = tmpCMP;
/* Wait for the completion of the write operation to the LPTIM_CMP register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMPOK) == HAL_TIMEOUT)
{
hlptim->State = HAL_LPTIM_STATE_TIMEOUT;
}
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK);
}
if (tmpARR != 0UL)
{
/* Restore ARR register (LPTIM should be enabled first) */
hlptim->Instance->CR |= LPTIM_CR_ENABLE;
hlptim->Instance->ARR = tmpARR;
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
hlptim->State = HAL_LPTIM_STATE_TIMEOUT;
}
__HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK);
}
/* Restore LPTIM source kernel clock */
switch ((uint32_t)hlptim->Instance)
{
case LPTIM1_BASE:
__HAL_RCC_LPTIM1_CONFIG(tmpclksource);
break;
default:
break;
}
}
/* Restore configuration registers (LPTIM should be disabled first) */
hlptim->Instance->CR &= ~(LPTIM_CR_ENABLE);
hlptim->Instance->IER = tmpIER;
hlptim->Instance->CFGR = tmpCFGR;
hlptim->Instance->OR = tmpOR;
/* Exit critical section: restore previous priority mask */
__set_PRIMASK(primask_bit);
}
/**
* @}
*/
#endif /* HAL_LPTIM_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 75,110 |
C
| 29.323375 | 108 | 0.65195 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_i2c.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_i2c.c
* @author MCD Application Team
* @brief I2C HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Inter Integrated Circuit (I2C) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The I2C HAL driver can be used as follows:
(#) Declare a I2C_HandleTypeDef handle structure, for example:
I2C_HandleTypeDef hi2c;
(#)Initialize the I2C low level resources by implementing the HAL_I2C_MspInit() API:
(##) Enable the I2Cx interface clock
(##) I2C pins configuration
(+++) Enable the clock for the I2C GPIOs
(+++) Configure I2C pins as alternate function open-drain
(##) NVIC configuration if you need to use interrupt process
(+++) Configure the I2Cx interrupt priority
(+++) Enable the NVIC I2C IRQ Channel
(##) DMA Configuration if you need to use DMA process
(+++) Declare a DMA_HandleTypeDef handle structure for
the transmit or receive channel
(+++) Enable the DMAx interface clock using
(+++) Configure the DMA handle parameters
(+++) Configure the DMA Tx or Rx channel
(+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on
the DMA Tx or Rx channel
(#) Configure the Communication Clock Timing, Own Address1, Master Addressing mode, Dual Addressing mode,
Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure.
(#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware
(GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I2C_MspInit(&hi2c) API.
(#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady()
(#) For I2C IO and IO MEM operations, three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit()
(+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive()
(+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit()
(+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive()
*** Polling mode IO MEM operation ***
=====================================
[..]
(+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write()
(+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Transmit in master mode an amount of data in non-blocking mode using HAL_I2C_Master_Transmit_IT()
(+) At transmission end of transfer, HAL_I2C_MasterTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
(+) Receive in master mode an amount of data in non-blocking mode using HAL_I2C_Master_Receive_IT()
(+) At reception end of transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
(+) Transmit in slave mode an amount of data in non-blocking mode using HAL_I2C_Slave_Transmit_IT()
(+) At transmission end of transfer, HAL_I2C_SlaveTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
(+) Receive in slave mode an amount of data in non-blocking mode using HAL_I2C_Slave_Receive_IT()
(+) At reception end of transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
(+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
add their own code by customization of function pointer HAL_I2C_ErrorCallback()
(+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
(+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
(+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** Interrupt mode or DMA mode IO sequential operation ***
==========================================================
[..]
(@) These interfaces allow to manage a sequential transfer with a repeated start condition
when a direction change during transfer
[..]
(+) A specific option field manage the different steps of a sequential transfer
(+) Option field values are defined through I2C_XFEROPTIONS and are listed below:
(++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functional is same as associated interfaces in
no sequential mode
(++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address
and data to transfer without a final stop condition
(++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with
start condition, address and data to transfer without a final stop condition,
an then permit a call the same master sequential interface several times
(like HAL_I2C_Master_Seq_Transmit_IT() then HAL_I2C_Master_Seq_Transmit_IT()
or HAL_I2C_Master_Seq_Transmit_DMA() then HAL_I2C_Master_Seq_Transmit_DMA())
(++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address
and with new data to transfer if the direction change or manage only the new data to
transfer
if no direction change and without a final stop condition in both cases
(++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address
and with new data to transfer if the direction change or manage only the new data to
transfer
if no direction change and with a final stop condition in both cases
(++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition
after several call of the same master sequential interface several times
(link with option I2C_FIRST_AND_NEXT_FRAME).
Usage can, transfer several bytes one by one using
HAL_I2C_Master_Seq_Transmit_IT
or HAL_I2C_Master_Seq_Receive_IT
or HAL_I2C_Master_Seq_Transmit_DMA
or HAL_I2C_Master_Seq_Receive_DMA
with option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME.
Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or
Receive sequence permit to call the opposite interface Receive or Transmit
without stopping the communication and so generate a restart condition.
(++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after
each call of the same master sequential
interface.
Usage can, transfer several bytes one by one with a restart with slave address between
each bytes using
HAL_I2C_Master_Seq_Transmit_IT
or HAL_I2C_Master_Seq_Receive_IT
or HAL_I2C_Master_Seq_Transmit_DMA
or HAL_I2C_Master_Seq_Receive_DMA
with option I2C_FIRST_FRAME then I2C_OTHER_FRAME.
Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic
generation of STOP condition.
(+) Different sequential I2C interfaces are listed below:
(++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using
HAL_I2C_Master_Seq_Transmit_IT() or using HAL_I2C_Master_Seq_Transmit_DMA()
(+++) At transmission end of current frame transfer, HAL_I2C_MasterTxCpltCallback() is executed and
users can add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
(++) Sequential receive in master I2C mode an amount of data in non-blocking mode using
HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA()
(+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
(++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
(+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
(++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT()
HAL_I2C_DisableListen_IT()
(+++) When address slave I2C match, HAL_I2C_AddrCallback() is executed and users can
add their own code to check the Address Match Code and the transmission direction request by master
(Write/Read).
(+++) At Listen mode end HAL_I2C_ListenCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_ListenCpltCallback()
(++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using
HAL_I2C_Slave_Seq_Transmit_IT() or using HAL_I2C_Slave_Seq_Transmit_DMA()
(+++) At transmission end of current frame transfer, HAL_I2C_SlaveTxCpltCallback() is executed and
users can add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
(++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using
HAL_I2C_Slave_Seq_Receive_IT() or using HAL_I2C_Slave_Seq_Receive_DMA()
(+++) At reception end of current frame transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
(++) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
add their own code by customization of function pointer HAL_I2C_ErrorCallback()
(++) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** Interrupt mode IO MEM operation ***
=======================================
[..]
(+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using
HAL_I2C_Mem_Write_IT()
(+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback()
(+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using
HAL_I2C_Mem_Read_IT()
(+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback()
(+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
add their own code by customization of function pointer HAL_I2C_ErrorCallback()
*** DMA mode IO operation ***
==============================
[..]
(+) Transmit in master mode an amount of data in non-blocking mode (DMA) using
HAL_I2C_Master_Transmit_DMA()
(+) At transmission end of transfer, HAL_I2C_MasterTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback()
(+) Receive in master mode an amount of data in non-blocking mode (DMA) using
HAL_I2C_Master_Receive_DMA()
(+) At reception end of transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback()
(+) Transmit in slave mode an amount of data in non-blocking mode (DMA) using
HAL_I2C_Slave_Transmit_DMA()
(+) At transmission end of transfer, HAL_I2C_SlaveTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback()
(+) Receive in slave mode an amount of data in non-blocking mode (DMA) using
HAL_I2C_Slave_Receive_DMA()
(+) At reception end of transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback()
(+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
add their own code by customization of function pointer HAL_I2C_ErrorCallback()
(+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT()
(+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_AbortCpltCallback()
(+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** DMA mode IO MEM operation ***
=================================
[..]
(+) Write an amount of data in non-blocking mode with DMA to a specific memory address using
HAL_I2C_Mem_Write_DMA()
(+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback()
(+) Read an amount of data in non-blocking mode with DMA from a specific memory address using
HAL_I2C_Mem_Read_DMA()
(+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can
add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback()
(+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can
add their own code by customization of function pointer HAL_I2C_ErrorCallback()
*** I2C HAL driver macros list ***
==================================
[..]
Below the list of most used macros in I2C HAL driver.
(+) __HAL_I2C_ENABLE: Enable the I2C peripheral
(+) __HAL_I2C_DISABLE: Disable the I2C peripheral
(+) __HAL_I2C_GENERATE_NACK: Generate a Non-Acknowledge I2C peripheral in Slave mode
(+) __HAL_I2C_GET_FLAG: Check whether the specified I2C flag is set or not
(+) __HAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag
(+) __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt
(+) __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt
*** Callback registration ***
=============================================
[..]
The compilation flag USE_HAL_I2C_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_I2C_RegisterCallback() or HAL_I2C_RegisterAddrCallback()
to register an interrupt callback.
[..]
Function HAL_I2C_RegisterCallback() allows to register following callbacks:
(+) MasterTxCpltCallback : callback for Master transmission end of transfer.
(+) MasterRxCpltCallback : callback for Master reception end of transfer.
(+) SlaveTxCpltCallback : callback for Slave transmission end of transfer.
(+) SlaveRxCpltCallback : callback for Slave reception end of transfer.
(+) ListenCpltCallback : callback for end of listen mode.
(+) MemTxCpltCallback : callback for Memory transmission end of transfer.
(+) MemRxCpltCallback : callback for Memory reception end of transfer.
(+) ErrorCallback : callback for error detection.
(+) AbortCpltCallback : callback for abort completion process.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
For specific callback AddrCallback use dedicated register callbacks : HAL_I2C_RegisterAddrCallback().
[..]
Use function HAL_I2C_UnRegisterCallback to reset a callback to the default
weak function.
HAL_I2C_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) MasterTxCpltCallback : callback for Master transmission end of transfer.
(+) MasterRxCpltCallback : callback for Master reception end of transfer.
(+) SlaveTxCpltCallback : callback for Slave transmission end of transfer.
(+) SlaveRxCpltCallback : callback for Slave reception end of transfer.
(+) ListenCpltCallback : callback for end of listen mode.
(+) MemTxCpltCallback : callback for Memory transmission end of transfer.
(+) MemRxCpltCallback : callback for Memory reception end of transfer.
(+) ErrorCallback : callback for error detection.
(+) AbortCpltCallback : callback for abort completion process.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
[..]
For callback AddrCallback use dedicated register callbacks : HAL_I2C_UnRegisterAddrCallback().
[..]
By default, after the HAL_I2C_Init() and when the state is HAL_I2C_STATE_RESET
all callbacks are set to the corresponding weak functions:
examples HAL_I2C_MasterTxCpltCallback(), HAL_I2C_MasterRxCpltCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the HAL_I2C_Init()/ HAL_I2C_DeInit() only when
these callbacks are null (not registered beforehand).
If MspInit or MspDeInit are not null, the HAL_I2C_Init()/ HAL_I2C_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
Then, the user first registers the MspInit/MspDeInit user callbacks
using HAL_I2C_RegisterCallback() before calling HAL_I2C_DeInit()
or HAL_I2C_Init() function.
[..]
When the compilation flag USE_HAL_I2C_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available and all callbacks
are set to the corresponding weak functions.
[..]
(@) You can refer to the I2C HAL driver header file for more useful macros
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup I2C I2C
* @brief I2C HAL module driver
* @{
*/
#ifdef HAL_I2C_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup I2C_Private_Define I2C Private Define
* @{
*/
#define TIMING_CLEAR_MASK (0xF0FFFFFFU) /*!< I2C TIMING clear register Mask */
#define I2C_TIMEOUT_ADDR (10000U) /*!< 10 s */
#define I2C_TIMEOUT_BUSY (25U) /*!< 25 ms */
#define I2C_TIMEOUT_DIR (25U) /*!< 25 ms */
#define I2C_TIMEOUT_RXNE (25U) /*!< 25 ms */
#define I2C_TIMEOUT_STOPF (25U) /*!< 25 ms */
#define I2C_TIMEOUT_TC (25U) /*!< 25 ms */
#define I2C_TIMEOUT_TCR (25U) /*!< 25 ms */
#define I2C_TIMEOUT_TXIS (25U) /*!< 25 ms */
#define I2C_TIMEOUT_FLAG (25U) /*!< 25 ms */
#define MAX_NBYTE_SIZE 255U
#define SLAVE_ADDR_SHIFT 7U
#define SLAVE_ADDR_MSK 0x06U
/* Private define for @ref PreviousState usage */
#define I2C_STATE_MSK ((uint32_t)((uint32_t)((uint32_t)HAL_I2C_STATE_BUSY_TX | \
(uint32_t)HAL_I2C_STATE_BUSY_RX) & \
(uint32_t)(~((uint32_t)HAL_I2C_STATE_READY))))
/*!< Mask State define, keep only RX and TX bits */
#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE))
/*!< Default Value */
#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_MASTER))
/*!< Master Busy TX, combinaison of State LSB and Mode enum */
#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_MASTER))
/*!< Master Busy RX, combinaison of State LSB and Mode enum */
#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_SLAVE))
/*!< Slave Busy TX, combinaison of State LSB and Mode enum */
#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_SLAVE))
/*!< Slave Busy RX, combinaison of State LSB and Mode enum */
#define I2C_STATE_MEM_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_MEM))
/*!< Memory Busy TX, combinaison of State LSB and Mode enum */
#define I2C_STATE_MEM_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \
(uint32_t)HAL_I2C_MODE_MEM))
/*!< Memory Busy RX, combinaison of State LSB and Mode enum */
/* Private define to centralize the enable/disable of Interrupts */
#define I2C_XFER_TX_IT (uint16_t)(0x0001U) /*!< Bit field can be combinated with
@ref I2C_XFER_LISTEN_IT */
#define I2C_XFER_RX_IT (uint16_t)(0x0002U) /*!< Bit field can be combinated with
@ref I2C_XFER_LISTEN_IT */
#define I2C_XFER_LISTEN_IT (uint16_t)(0x8000U) /*!< Bit field can be combinated with @ref I2C_XFER_TX_IT
and @ref I2C_XFER_RX_IT */
#define I2C_XFER_ERROR_IT (uint16_t)(0x0010U) /*!< Bit definition to manage addition of global Error
and NACK treatment */
#define I2C_XFER_CPLT_IT (uint16_t)(0x0020U) /*!< Bit definition to manage only STOP evenement */
#define I2C_XFER_RELOAD_IT (uint16_t)(0x0040U) /*!< Bit definition to manage only Reload of NBYTE */
/* Private define Sequential Transfer Options default/reset value */
#define I2C_NO_OPTION_FRAME (0xFFFF0000U)
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Macro to get remaining data to transfer on DMA side */
#define I2C_GET_DMA_REMAIN_DATA(__HANDLE__) __HAL_DMA_GET_COUNTER(__HANDLE__)
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup I2C_Private_Functions I2C Private Functions
* @{
*/
/* Private functions to handle DMA transfer */
static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma);
static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma);
static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma);
static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma);
static void I2C_DMAError(DMA_HandleTypeDef *hdma);
static void I2C_DMAAbort(DMA_HandleTypeDef *hdma);
/* Private functions to handle IT transfer */
static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c);
static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c);
static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags);
static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode);
/* Private functions to handle IT transfer */
static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
uint32_t Tickstart);
static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
uint32_t Tickstart);
/* Private functions for I2C transfer IRQ handler */
static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources);
static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources);
static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources);
static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources);
/* Private functions to handle flags during polling transfer */
static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status,
uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart);
static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart);
static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart);
static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart);
/* Private functions to centralize the enable/disable of Interrupts */
static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest);
static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest);
/* Private function to treat different error callback */
static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c);
/* Private function to flush TXDR register */
static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c);
/* Private function to handle start, restart or stop a transfer */
static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode,
uint32_t Request);
/* Private function to Convert Specific options */
static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup I2C_Exported_Functions I2C Exported Functions
* @{
*/
/** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
deinitialize the I2Cx peripheral:
(+) User must Implement HAL_I2C_MspInit() function in which he configures
all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
(+) Call the function HAL_I2C_Init() to configure the selected device with
the selected configuration:
(++) Clock Timing
(++) Own Address 1
(++) Addressing mode (Master, Slave)
(++) Dual Addressing mode
(++) Own Address 2
(++) Own Address 2 Mask
(++) General call mode
(++) Nostretch mode
(+) Call the function HAL_I2C_DeInit() to restore the default configuration
of the selected I2Cx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initializes the I2C according to the specified parameters
* in the I2C_InitTypeDef and initialize the associated handle.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
{
/* Check the I2C handle allocation */
if (hi2c == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1));
assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode));
assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode));
assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2));
assert_param(IS_I2C_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks));
assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode));
assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode));
if (hi2c->State == HAL_I2C_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hi2c->Lock = HAL_UNLOCKED;
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
/* Init the I2C Callback settings */
hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */
hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */
hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */
hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */
hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */
hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */
hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */
hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */
hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */
hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */
if (hi2c->MspInitCallback == NULL)
{
hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
hi2c->MspInitCallback(hi2c);
#else
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
HAL_I2C_MspInit(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the selected I2C peripheral */
__HAL_I2C_DISABLE(hi2c);
/*---------------------------- I2Cx TIMINGR Configuration ------------------*/
/* Configure I2Cx: Frequency range */
hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK;
/*---------------------------- I2Cx OAR1 Configuration ---------------------*/
/* Disable Own Address1 before set the Own Address1 configuration */
hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN;
/* Configure I2Cx: Own Address1 and ack own address1 mode */
if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
{
hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1);
}
else /* I2C_ADDRESSINGMODE_10BIT */
{
hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1);
}
/*---------------------------- I2Cx CR2 Configuration ----------------------*/
/* Configure I2Cx: Addressing Master mode */
if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
{
hi2c->Instance->CR2 = (I2C_CR2_ADD10);
}
/* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */
hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK);
/*---------------------------- I2Cx OAR2 Configuration ---------------------*/
/* Disable Own Address2 before set the Own Address2 configuration */
hi2c->Instance->OAR2 &= ~I2C_DUALADDRESS_ENABLE;
/* Configure I2Cx: Dual mode and Own Address2 */
hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | \
(hi2c->Init.OwnAddress2Masks << 8));
/*---------------------------- I2Cx CR1 Configuration ----------------------*/
/* Configure I2Cx: Generalcall and NoStretch mode */
hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode);
/* Enable the selected I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
hi2c->Mode = HAL_I2C_MODE_NONE;
return HAL_OK;
}
/**
* @brief DeInitialize the I2C peripheral.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
{
/* Check the I2C handle allocation */
if (hi2c == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the I2C Peripheral Clock */
__HAL_I2C_DISABLE(hi2c);
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
if (hi2c->MspDeInitCallback == NULL)
{
hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: GPIO, CLOCK, NVIC */
hi2c->MspDeInitCallback(hi2c);
#else
/* DeInit the low level hardware: GPIO, CLOCK, NVIC */
HAL_I2C_MspDeInit(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
hi2c->State = HAL_I2C_STATE_RESET;
hi2c->PreviousState = I2C_STATE_NONE;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Release Lock */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
/**
* @brief Initialize the I2C MSP.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize the I2C MSP.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MspDeInit could be implemented in the user file
*/
}
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User I2C Callback
* To be used instead of the weak predefined callback
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID
* @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID
* @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID
* @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID
* @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID
* @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID
* @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID
* @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID
* @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID
* @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID,
pI2C_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hi2c);
if (HAL_I2C_STATE_READY == hi2c->State)
{
switch (CallbackID)
{
case HAL_I2C_MASTER_TX_COMPLETE_CB_ID :
hi2c->MasterTxCpltCallback = pCallback;
break;
case HAL_I2C_MASTER_RX_COMPLETE_CB_ID :
hi2c->MasterRxCpltCallback = pCallback;
break;
case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID :
hi2c->SlaveTxCpltCallback = pCallback;
break;
case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID :
hi2c->SlaveRxCpltCallback = pCallback;
break;
case HAL_I2C_LISTEN_COMPLETE_CB_ID :
hi2c->ListenCpltCallback = pCallback;
break;
case HAL_I2C_MEM_TX_COMPLETE_CB_ID :
hi2c->MemTxCpltCallback = pCallback;
break;
case HAL_I2C_MEM_RX_COMPLETE_CB_ID :
hi2c->MemRxCpltCallback = pCallback;
break;
case HAL_I2C_ERROR_CB_ID :
hi2c->ErrorCallback = pCallback;
break;
case HAL_I2C_ABORT_CB_ID :
hi2c->AbortCpltCallback = pCallback;
break;
case HAL_I2C_MSPINIT_CB_ID :
hi2c->MspInitCallback = pCallback;
break;
case HAL_I2C_MSPDEINIT_CB_ID :
hi2c->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_I2C_STATE_RESET == hi2c->State)
{
switch (CallbackID)
{
case HAL_I2C_MSPINIT_CB_ID :
hi2c->MspInitCallback = pCallback;
break;
case HAL_I2C_MSPDEINIT_CB_ID :
hi2c->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2c);
return status;
}
/**
* @brief Unregister an I2C Callback
* I2C callback is redirected to the weak predefined callback
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* This parameter can be one of the following values:
* @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID
* @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID
* @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID
* @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID
* @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID
* @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID
* @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID
* @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID
* @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID
* @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hi2c);
if (HAL_I2C_STATE_READY == hi2c->State)
{
switch (CallbackID)
{
case HAL_I2C_MASTER_TX_COMPLETE_CB_ID :
hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */
break;
case HAL_I2C_MASTER_RX_COMPLETE_CB_ID :
hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */
break;
case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID :
hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */
break;
case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID :
hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */
break;
case HAL_I2C_LISTEN_COMPLETE_CB_ID :
hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */
break;
case HAL_I2C_MEM_TX_COMPLETE_CB_ID :
hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */
break;
case HAL_I2C_MEM_RX_COMPLETE_CB_ID :
hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */
break;
case HAL_I2C_ERROR_CB_ID :
hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_I2C_ABORT_CB_ID :
hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */
break;
case HAL_I2C_MSPINIT_CB_ID :
hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */
break;
case HAL_I2C_MSPDEINIT_CB_ID :
hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_I2C_STATE_RESET == hi2c->State)
{
switch (CallbackID)
{
case HAL_I2C_MSPINIT_CB_ID :
hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */
break;
case HAL_I2C_MSPDEINIT_CB_ID :
hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2c);
return status;
}
/**
* @brief Register the Slave Address Match I2C Callback
* To be used instead of the weak HAL_I2C_AddrCallback() predefined callback
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pCallback pointer to the Address Match Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hi2c);
if (HAL_I2C_STATE_READY == hi2c->State)
{
hi2c->AddrCallback = pCallback;
}
else
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2c);
return status;
}
/**
* @brief UnRegister the Slave Address Match I2C Callback
* Info Ready I2C Callback is redirected to the weak HAL_I2C_AddrCallback() predefined callback
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hi2c);
if (HAL_I2C_STATE_READY == hi2c->State)
{
hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */
}
else
{
/* Update the error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hi2c);
return status;
}
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup I2C_Exported_Functions_Group2 Input and Output operation functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the I2C data
transfers.
(#) There are two modes of transfer:
(++) Blocking mode : The communication is performed in the polling mode.
The status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode : The communication is performed using Interrupts
or DMA. These functions return the status of the transfer startup.
The end of the data processing will be indicated through the
dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
(#) Blocking mode functions are :
(++) HAL_I2C_Master_Transmit()
(++) HAL_I2C_Master_Receive()
(++) HAL_I2C_Slave_Transmit()
(++) HAL_I2C_Slave_Receive()
(++) HAL_I2C_Mem_Write()
(++) HAL_I2C_Mem_Read()
(++) HAL_I2C_IsDeviceReady()
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_I2C_Master_Transmit_IT()
(++) HAL_I2C_Master_Receive_IT()
(++) HAL_I2C_Slave_Transmit_IT()
(++) HAL_I2C_Slave_Receive_IT()
(++) HAL_I2C_Mem_Write_IT()
(++) HAL_I2C_Mem_Read_IT()
(++) HAL_I2C_Master_Seq_Transmit_IT()
(++) HAL_I2C_Master_Seq_Receive_IT()
(++) HAL_I2C_Slave_Seq_Transmit_IT()
(++) HAL_I2C_Slave_Seq_Receive_IT()
(++) HAL_I2C_EnableListen_IT()
(++) HAL_I2C_DisableListen_IT()
(++) HAL_I2C_Master_Abort_IT()
(#) No-Blocking mode functions with DMA are :
(++) HAL_I2C_Master_Transmit_DMA()
(++) HAL_I2C_Master_Receive_DMA()
(++) HAL_I2C_Slave_Transmit_DMA()
(++) HAL_I2C_Slave_Receive_DMA()
(++) HAL_I2C_Mem_Write_DMA()
(++) HAL_I2C_Mem_Read_DMA()
(++) HAL_I2C_Master_Seq_Transmit_DMA()
(++) HAL_I2C_Master_Seq_Receive_DMA()
(++) HAL_I2C_Slave_Seq_Transmit_DMA()
(++) HAL_I2C_Slave_Seq_Receive_DMA()
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_I2C_MasterTxCpltCallback()
(++) HAL_I2C_MasterRxCpltCallback()
(++) HAL_I2C_SlaveTxCpltCallback()
(++) HAL_I2C_SlaveRxCpltCallback()
(++) HAL_I2C_MemTxCpltCallback()
(++) HAL_I2C_MemRxCpltCallback()
(++) HAL_I2C_AddrCallback()
(++) HAL_I2C_ListenCpltCallback()
(++) HAL_I2C_ErrorCallback()
(++) HAL_I2C_AbortCpltCallback()
@endverbatim
* @{
*/
/**
* @brief Transmits in master mode an amount of data in blocking mode.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart;
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferISR = NULL;
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_GENERATE_START_WRITE);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_WRITE);
}
while (hi2c->XferCount > 0U)
{
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Write data to TXDR */
hi2c->Instance->TXDR = *hi2c->pBuffPtr;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
hi2c->XferSize--;
if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
{
/* Wait until TCR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_NO_STARTSTOP);
}
}
}
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives in master mode an amount of data in blocking mode.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart;
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferISR = NULL;
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_GENERATE_START_READ);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_READ);
}
while (hi2c->XferCount > 0U)
{
/* Wait until RXNE flag is set */
if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferSize--;
hi2c->XferCount--;
if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
{
/* Wait until TCR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_NO_STARTSTOP);
}
}
}
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmits in slave mode an amount of data in blocking mode.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t Timeout)
{
uint32_t tickstart;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferISR = NULL;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Wait until ADDR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Clear ADDR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
/* If 10bit addressing mode is selected */
if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
{
/* Wait until ADDR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Clear ADDR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
}
/* Wait until DIR flag is set Transmitter mode */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
while (hi2c->XferCount > 0U)
{
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Write data to TXDR */
hi2c->Instance->TXDR = *hi2c->pBuffPtr;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
}
/* Wait until AF flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* Clear AF flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Wait until STOP flag is set */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Clear STOP flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Wait until BUSY flag is reset */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in blocking mode
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t Timeout)
{
uint32_t tickstart;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferISR = NULL;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Wait until ADDR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Clear ADDR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
/* Wait until DIR flag is reset Receiver mode */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
while (hi2c->XferCount > 0U)
{
/* Wait until RXNE flag is set */
if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
/* Store Last receive data if any */
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
{
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
hi2c->XferSize--;
}
return HAL_ERROR;
}
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
hi2c->XferSize--;
}
/* Wait until STOP flag is set */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Clear STOP flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Wait until BUSY flag is reset */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
return HAL_ERROR;
}
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size)
{
uint32_t xfermode;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_IT;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in master mode an amount of data in non-blocking mode with Interrupt
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size)
{
uint32_t xfermode;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_IT;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
{
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Slave_ISR_IT;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
{
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Slave_ISR_IT;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in master mode an amount of data in non-blocking mode with DMA
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size)
{
uint32_t xfermode;
HAL_StatusTypeDef dmaxferstatus;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_DMA;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
if (hi2c->XferSize > 0U)
{
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
else
{
/* Update Transfer ISR function pointer */
hi2c->XferISR = I2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to write and generate START condition */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_WRITE);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in master mode an amount of data in non-blocking mode with DMA
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size)
{
uint32_t xfermode;
HAL_StatusTypeDef dmaxferstatus;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_DMA;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
if (hi2c->XferSize > 0U)
{
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
/* Set the DMA error callback */
hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Send Slave Address */
/* Set NBYTES to read and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
else
{
/* Update Transfer ISR function pointer */
hi2c->XferISR = I2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to read and generate START condition */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in slave mode an amount of data in non-blocking mode with DMA
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
{
HAL_StatusTypeDef dmaxferstatus;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Slave_ISR_DMA;
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt;
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, STOP, NACK, ADDR interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in non-blocking mode with DMA
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
{
HAL_StatusTypeDef dmaxferstatus;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Slave_ISR_DMA;
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt;
/* Set the DMA error callback */
hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, STOP, NACK, ADDR interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in blocking mode to a specific memory address
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferISR = NULL;
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
}
do
{
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Write data to TXDR */
hi2c->Instance->TXDR = *hi2c->pBuffPtr;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
hi2c->XferSize--;
if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
{
/* Wait until TCR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_NO_STARTSTOP);
}
}
} while (hi2c->XferCount > 0U);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is reset */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Read an amount of data in blocking mode from a specific memory address
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferISR = NULL;
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE,
I2C_GENERATE_START_READ);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_READ);
}
do
{
/* Wait until RXNE flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferSize--;
hi2c->XferCount--;
if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
{
/* Wait until TCR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t) hi2c->XferSize, I2C_RELOAD_MODE,
I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_NO_STARTSTOP);
}
}
} while (hi2c->XferCount > 0U);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is reset */
if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart;
uint32_t xfermode;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_IT;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart)
!= HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart;
uint32_t xfermode;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_IT;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in non-blocking mode with DMA to a specific memory address
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart;
uint32_t xfermode;
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_DMA;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart)
!= HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Send Slave Address */
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress,
uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart;
uint32_t xfermode;
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferISR = I2C_Master_ISR_DMA;
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = I2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
/* Set the DMA error callback */
hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Checks if target device is ready for communication.
* @note This function is used with Memory devices
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param Trials Number of trials
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials,
uint32_t Timeout)
{
uint32_t tickstart;
__IO uint32_t I2C_Trials = 0UL;
FlagStatus tmp1;
FlagStatus tmp2;
if (hi2c->State == HAL_I2C_STATE_READY)
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
do
{
/* Generate Start */
hi2c->Instance->CR2 = I2C_GENERATE_START(hi2c->Init.AddressingMode, DevAddress);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set or a NACK flag is set*/
tickstart = HAL_GetTick();
tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF);
tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
while ((tmp1 == RESET) && (tmp2 == RESET))
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF);
tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
}
/* Check if the NACKF flag has not been set */
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET)
{
/* Wait until STOPF flag is reset */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Device is ready */
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
/* Wait until STOPF flag is reset */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Clear STOP Flag, auto generated with autoend*/
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
}
/* Check if the maximum allowed number of trials has been reached */
if (I2C_Trials == Trials)
{
/* Generate Stop */
hi2c->Instance->CR2 |= I2C_CR2_STOP;
/* Wait until STOPF flag is reset */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
}
/* Increment Trials */
I2C_Trials++;
} while (I2C_Trials < Trials);
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt.
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode;
uint32_t xferrequest = I2C_GENERATE_START_WRITE;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Master_ISR_IT;
/* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = hi2c->XferOptions;
}
/* If transfer direction not change and there is no request to start another frame,
do not generate Restart Condition */
/* Mean Previous state is same as current state */
if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \
(IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
{
xferrequest = I2C_NO_STARTSTOP;
}
else
{
/* Convert OTHER_xxx XferOptions if any */
I2C_ConvertOtherXferOptions(hi2c);
/* Update xfermode accordingly if no reload is necessary */
if (hi2c->XferCount <= MAX_NBYTE_SIZE)
{
xfermode = hi2c->XferOptions;
}
}
/* Send Slave Address and set NBYTES to write */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA.
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode;
uint32_t xferrequest = I2C_GENERATE_START_WRITE;
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Master_ISR_DMA;
/* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = hi2c->XferOptions;
}
/* If transfer direction not change and there is no request to start another frame,
do not generate Restart Condition */
/* Mean Previous state is same as current state */
if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \
(IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
{
xferrequest = I2C_NO_STARTSTOP;
}
else
{
/* Convert OTHER_xxx XferOptions if any */
I2C_ConvertOtherXferOptions(hi2c);
/* Update xfermode accordingly if no reload is necessary */
if (hi2c->XferCount <= MAX_NBYTE_SIZE)
{
xfermode = hi2c->XferOptions;
}
}
if (hi2c->XferSize > 0U)
{
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt;
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Send Slave Address and set NBYTES to write */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
else
{
/* Update Transfer ISR function pointer */
hi2c->XferISR = I2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to write and generate START condition */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_WRITE);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode;
uint32_t xferrequest = I2C_GENERATE_START_READ;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Master_ISR_IT;
/* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = hi2c->XferOptions;
}
/* If transfer direction not change and there is no request to start another frame,
do not generate Restart Condition */
/* Mean Previous state is same as current state */
if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \
(IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
{
xferrequest = I2C_NO_STARTSTOP;
}
else
{
/* Convert OTHER_xxx XferOptions if any */
I2C_ConvertOtherXferOptions(hi2c);
/* Update xfermode accordingly if no reload is necessary */
if (hi2c->XferCount <= MAX_NBYTE_SIZE)
{
xfermode = hi2c->XferOptions;
}
}
/* Send Slave Address and set NBYTES to read */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with DMA
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData,
uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode;
uint32_t xferrequest = I2C_GENERATE_START_READ;
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Master_ISR_DMA;
/* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
xfermode = hi2c->XferOptions;
}
/* If transfer direction not change and there is no request to start another frame,
do not generate Restart Condition */
/* Mean Previous state is same as current state */
if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \
(IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0))
{
xferrequest = I2C_NO_STARTSTOP;
}
else
{
/* Convert OTHER_xxx XferOptions if any */
I2C_ConvertOtherXferOptions(hi2c);
/* Update xfermode accordingly if no reload is necessary */
if (hi2c->XferCount <= MAX_NBYTE_SIZE)
{
xfermode = hi2c->XferOptions;
}
}
if (hi2c->XferSize > 0U)
{
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt;
/* Set the DMA error callback */
hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Send Slave Address and set NBYTES to read */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
else
{
/* Update Transfer ISR function pointer */
hi2c->XferISR = I2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to read and generate START condition */
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE,
I2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI |
I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t XferOptions)
{
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
/* Process Locked */
__HAL_LOCK(hi2c);
/* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave RX state to TX state */
if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
{
/* Disable associated Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
/* Abort DMA Xfer if any */
if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
}
}
}
}
hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Slave_ISR_IT;
if (I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* REnable ADDR interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with DMA
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t XferOptions)
{
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
/* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave RX state to TX state */
if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
{
/* Disable associated Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
{
/* Abort DMA Xfer if any */
if (hi2c->hdmarx != NULL)
{
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
}
}
}
}
else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
{
if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
/* Abort DMA Xfer if any */
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
}
}
}
}
else
{
/* Nothing to do */
}
hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Slave_ISR_DMA;
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt;
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Reset XferSize */
hi2c->XferSize = 0;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* Enable ERR, STOP, NACK, ADDR interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t XferOptions)
{
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
/* Process Locked */
__HAL_LOCK(hi2c);
/* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave TX state to RX state */
if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
{
/* Disable associated Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
/* Abort DMA Xfer if any */
if (hi2c->hdmatx != NULL)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
}
}
}
}
hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Slave_ISR_IT;
if (I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* REnable ADDR interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with DMA
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size,
uint32_t XferOptions)
{
HAL_StatusTypeDef dmaxferstatus;
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
/* Process Locked */
__HAL_LOCK(hi2c);
/* I2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave TX state to RX state */
if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
{
/* Disable associated Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
{
/* Abort DMA Xfer if any */
if (hi2c->hdmatx != NULL)
{
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
}
}
}
}
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
{
if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
/* Abort DMA Xfer if any */
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
}
}
}
}
else
{
/* Nothing to do */
}
hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN;
hi2c->Mode = HAL_I2C_MODE_SLAVE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Enable Address Acknowledge */
hi2c->Instance->CR2 &= ~I2C_CR2_NACK;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = hi2c->XferCount;
hi2c->XferOptions = XferOptions;
hi2c->XferISR = I2C_Slave_ISR_DMA;
if (hi2c->hdmarx != NULL)
{
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt;
/* Set the DMA error callback */
hi2c->hdmarx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR,
(uint32_t)pData, hi2c->XferSize);
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (dmaxferstatus == HAL_OK)
{
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Reset XferSize */
hi2c->XferSize = 0;
}
else
{
/* Update I2C state */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Update I2C error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
if (I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Enable DMA Request */
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
/* REnable ADDR interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Enable the Address listen mode with Interrupt.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c)
{
if (hi2c->State == HAL_I2C_STATE_READY)
{
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->XferISR = I2C_Slave_ISR_IT;
/* Enable the Address Match interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Disable the Address listen mode with Interrupt.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c)
{
/* Declaration of tmp to prevent undefined behavior of volatile usage */
uint32_t tmp;
/* Disable Address listen mode only if a transfer is not ongoing */
if (hi2c->State == HAL_I2C_STATE_LISTEN)
{
tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK;
hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
hi2c->XferISR = NULL;
/* Disable the Address Match interrupt */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Abort a master I2C IT or DMA process communication with Interrupt.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress)
{
if (hi2c->Mode == HAL_I2C_MODE_MASTER)
{
/* Process Locked */
__HAL_LOCK(hi2c);
/* Disable Interrupts and Store Previous state */
if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
{
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
}
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
{
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
}
else
{
/* Do nothing */
}
/* Set State at HAL_I2C_STATE_ABORT */
hi2c->State = HAL_I2C_STATE_ABORT;
/* Set NBYTES to 1 to generate a dummy read on I2C peripheral */
/* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */
I2C_TransferConfig(hi2c, DevAddress, 1, I2C_AUTOEND_MODE, I2C_GENERATE_STOP);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
return HAL_OK;
}
else
{
/* Wrong usage of abort function */
/* This function should be used only in case of abort monitored by master device */
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks
* @{
*/
/**
* @brief This function handles I2C event interrupt request.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c)
{
/* Get current IT Flags and IT sources value */
uint32_t itflags = READ_REG(hi2c->Instance->ISR);
uint32_t itsources = READ_REG(hi2c->Instance->CR1);
/* I2C events treatment -------------------------------------*/
if (hi2c->XferISR != NULL)
{
hi2c->XferISR(hi2c, itflags, itsources);
}
}
/**
* @brief This function handles I2C error interrupt request.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
{
uint32_t itflags = READ_REG(hi2c->Instance->ISR);
uint32_t itsources = READ_REG(hi2c->Instance->CR1);
uint32_t tmperror;
/* I2C Bus error interrupt occurred ------------------------------------*/
if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_BERR) != RESET) && \
(I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_BERR;
/* Clear BERR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
}
/* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/
if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_OVR) != RESET) && \
(I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_OVR;
/* Clear OVR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
}
/* I2C Arbitration Loss error interrupt occurred -------------------------------------*/
if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_ARLO) != RESET) && \
(I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO;
/* Clear ARLO flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
}
/* Store current volatile hi2c->ErrorCode, misra rule */
tmperror = hi2c->ErrorCode;
/* Call the Error Callback in case of Error detected */
if ((tmperror & (HAL_I2C_ERROR_BERR | HAL_I2C_ERROR_OVR | HAL_I2C_ERROR_ARLO)) != HAL_I2C_ERROR_NONE)
{
I2C_ITError(hi2c, tmperror);
}
}
/**
* @brief Master Tx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MasterTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Master Rx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MasterRxCpltCallback could be implemented in the user file
*/
}
/** @brief Slave Tx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_SlaveTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Slave Rx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_SlaveRxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Slave Address Match callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XFERDIRECTION
* @param AddrMatchCode Address Match Code
* @retval None
*/
__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
UNUSED(TransferDirection);
UNUSED(AddrMatchCode);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_AddrCallback() could be implemented in the user file
*/
}
/**
* @brief Listen Complete callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_ListenCpltCallback() could be implemented in the user file
*/
}
/**
* @brief Memory Tx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MemTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Memory Rx Transfer completed callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_MemRxCpltCallback could be implemented in the user file
*/
}
/**
* @brief I2C error callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_ErrorCallback could be implemented in the user file
*/
}
/**
* @brief I2C abort callback.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval None
*/
__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_I2C_AbortCpltCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions
* @brief Peripheral State, Mode and Error functions
*
@verbatim
===============================================================================
##### Peripheral State, Mode and Error functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the I2C handle state.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval HAL state
*/
HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c)
{
/* Return I2C handle state */
return hi2c->State;
}
/**
* @brief Returns the I2C Master, Slave, Memory or no mode.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for I2C module
* @retval HAL mode
*/
HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c)
{
return hi2c->Mode;
}
/**
* @brief Return the I2C error code.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @retval I2C Error Code
*/
uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c)
{
return hi2c->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup I2C_Private_Functions
* @{
*/
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with Interrupt.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources)
{
uint16_t devaddress;
uint32_t tmpITFlags = ITFlags;
/* Process Locked */
__HAL_LOCK(hi2c);
if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Set corresponding Error Code */
/* No need to generate STOP, it is automatically done */
/* Error callback will be send during stop flag treatment */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET))
{
/* Remove RXNE flag on temporary variable as read done */
tmpITFlags &= ~I2C_FLAG_RXNE;
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferSize--;
hi2c->XferCount--;
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
{
/* Write data to TXDR */
hi2c->Instance->TXDR = *hi2c->pBuffPtr;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferSize--;
hi2c->XferCount--;
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
{
if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U))
{
devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD);
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP);
}
else
{
hi2c->XferSize = hi2c->XferCount;
if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
{
I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize,
hi2c->XferOptions, I2C_NO_STARTSTOP);
}
else
{
I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize,
I2C_AUTOEND_MODE, I2C_NO_STARTSTOP);
}
}
}
else
{
/* Call TxCpltCallback() if no stop mode is set */
if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
{
/* Call I2C Master Sequential complete process */
I2C_ITMasterSeqCplt(hi2c);
}
else
{
/* Wrong size Status regarding TCR flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
}
}
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
{
if (hi2c->XferCount == 0U)
{
if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
{
/* Generate a stop condition in case of no transfer option */
if (hi2c->XferOptions == I2C_NO_OPTION_FRAME)
{
/* Generate Stop */
hi2c->Instance->CR2 |= I2C_CR2_STOP;
}
else
{
/* Call I2C Master Sequential complete process */
I2C_ITMasterSeqCplt(hi2c);
}
}
}
else
{
/* Wrong size Status regarding TC flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
}
}
else
{
/* Nothing to do */
}
if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
{
/* Call I2C Master complete process */
I2C_ITMasterCplt(hi2c, tmpITFlags);
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with Interrupt.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources)
{
uint32_t tmpoptions = hi2c->XferOptions;
uint32_t tmpITFlags = ITFlags;
/* Process locked */
__HAL_LOCK(hi2c);
/* Check if STOPF is set */
if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
{
/* Call I2C Slave complete process */
I2C_ITSlaveCplt(hi2c, tmpITFlags);
}
if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
{
/* Check that I2C transfer finished */
/* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
/* Mean XferCount == 0*/
/* So clear Flag NACKF only */
if (hi2c->XferCount == 0U)
{
if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME))
/* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for
Warning[Pa134]: left and right operands are identical */
{
/* Call I2C Listen complete process */
I2C_ITListenCplt(hi2c, tmpITFlags);
}
else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME))
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* Last Byte is Transmitted */
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
else
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
}
}
else
{
/* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Set ErrorCode corresponding to a Non-Acknowledge */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME))
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, hi2c->ErrorCode);
}
}
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET))
{
if (hi2c->XferCount > 0U)
{
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferSize--;
hi2c->XferCount--;
}
if ((hi2c->XferCount == 0U) && \
(tmpoptions != I2C_NO_OPTION_FRAME))
{
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_ADDR) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET))
{
I2C_ITAddrCplt(hi2c, tmpITFlags);
}
else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET))
{
/* Write data to TXDR only if XferCount not reach "0" */
/* A TXIS flag can be set, during STOP treatment */
/* Check if all Data have already been sent */
/* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */
if (hi2c->XferCount > 0U)
{
/* Write data to TXDR */
hi2c->Instance->TXDR = *hi2c->pBuffPtr;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
hi2c->XferCount--;
hi2c->XferSize--;
}
else
{
if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME))
{
/* Last Byte is Transmitted */
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
}
}
else
{
/* Nothing to do */
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with DMA.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources)
{
uint16_t devaddress;
uint32_t xfermode;
/* Process Locked */
__HAL_LOCK(hi2c);
if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Set corresponding Error Code */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
/* No need to generate STOP, it is automatically done */
/* But enable STOP interrupt, to treat it */
/* Error callback will be send during stop flag treatment */
I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
}
else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
{
/* Disable TC interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_TCI);
if (hi2c->XferCount != 0U)
{
/* Recover Slave address */
devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD);
/* Prepare the new XferSize to transfer */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = I2C_RELOAD_MODE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
{
xfermode = hi2c->XferOptions;
}
else
{
xfermode = I2C_AUTOEND_MODE;
}
}
/* Set the new XferSize in Nbytes register */
I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP);
/* Update XferCount value */
hi2c->XferCount -= hi2c->XferSize;
/* Enable DMA Request */
if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
{
hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN;
}
else
{
hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN;
}
}
else
{
/* Call TxCpltCallback() if no stop mode is set */
if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
{
/* Call I2C Master Sequential complete process */
I2C_ITMasterSeqCplt(hi2c);
}
else
{
/* Wrong size Status regarding TCR flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
}
}
}
else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET))
{
if (hi2c->XferCount == 0U)
{
if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE)
{
/* Generate a stop condition in case of no transfer option */
if (hi2c->XferOptions == I2C_NO_OPTION_FRAME)
{
/* Generate Stop */
hi2c->Instance->CR2 |= I2C_CR2_STOP;
}
else
{
/* Call I2C Master Sequential complete process */
I2C_ITMasterSeqCplt(hi2c);
}
}
}
else
{
/* Wrong size Status regarding TC flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE);
}
}
else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
{
/* Call I2C Master complete process */
I2C_ITMasterCplt(hi2c, ITFlags);
}
else
{
/* Nothing to do */
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with DMA.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags,
uint32_t ITSources)
{
uint32_t tmpoptions = hi2c->XferOptions;
uint32_t treatdmanack = 0U;
HAL_I2C_StateTypeDef tmpstate;
/* Process locked */
__HAL_LOCK(hi2c);
/* Check if STOPF is set */
if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET))
{
/* Call I2C Slave complete process */
I2C_ITSlaveCplt(hi2c, ITFlags);
}
if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET))
{
/* Check that I2C transfer finished */
/* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
/* Mean XferCount == 0 */
/* So clear Flag NACKF only */
if ((I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) ||
(I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET))
{
/* Split check of hdmarx, for MISRA compliance */
if (hi2c->hdmarx != NULL)
{
if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET)
{
if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U)
{
treatdmanack = 1U;
}
}
}
/* Split check of hdmatx, for MISRA compliance */
if (hi2c->hdmatx != NULL)
{
if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET)
{
if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx) == 0U)
{
treatdmanack = 1U;
}
}
}
if (treatdmanack == 1U)
{
if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME))
/* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for
Warning[Pa134]: left and right operands are identical */
{
/* Call I2C Listen complete process */
I2C_ITListenCplt(hi2c, ITFlags);
}
else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME))
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* Last Byte is Transmitted */
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
else
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
}
}
else
{
/* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Set ErrorCode corresponding to a Non-Acknowledge */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
/* Store current hi2c->State, solve MISRA2012-Rule-13.5 */
tmpstate = hi2c->State;
if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME))
{
if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN))
{
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
}
else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
{
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
}
else
{
/* Do nothing */
}
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, hi2c->ErrorCode);
}
}
}
else
{
/* Only Clear NACK Flag, no DMA treatment is pending */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
}
}
else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_ADDR) != RESET) && \
(I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET))
{
I2C_ITAddrCplt(hi2c, ITFlags);
}
else
{
/* Nothing to do */
}
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
/**
* @brief Master sends target device address followed by internal memory address for write request.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
uint32_t Tickstart)
{
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE);
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* If Memory address size is 8Bit */
if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
{
/* Send Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
else
{
/* Send MSB of Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Send LSB of Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
}
/* Wait until TCR flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Master sends target device address followed by internal memory address for read request.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param DevAddress Target device address: The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout,
uint32_t Tickstart)
{
I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE);
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* If Memory address size is 8Bit */
if (MemAddSize == I2C_MEMADD_SIZE_8BIT)
{
/* Send Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
else
{
/* Send MSB of Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXIS flag is set */
if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Send LSB of Memory Address */
hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress);
}
/* Wait until TC flag is set */
if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief I2C Address complete process callback.
* @param hi2c I2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
{
uint8_t transferdirection;
uint16_t slaveaddrcode;
uint16_t ownadd1code;
uint16_t ownadd2code;
/* Prevent unused argument(s) compilation warning */
UNUSED(ITFlags);
/* In case of Listen state, need to inform upper layer of address match code event */
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN)
{
transferdirection = I2C_GET_DIR(hi2c);
slaveaddrcode = I2C_GET_ADDR_MATCH(hi2c);
ownadd1code = I2C_GET_OWN_ADDRESS1(hi2c);
ownadd2code = I2C_GET_OWN_ADDRESS2(hi2c);
/* If 10bits addressing mode is selected */
if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
{
if ((slaveaddrcode & SLAVE_ADDR_MSK) == ((ownadd1code >> SLAVE_ADDR_SHIFT) & SLAVE_ADDR_MSK))
{
slaveaddrcode = ownadd1code;
hi2c->AddrEventCount++;
if (hi2c->AddrEventCount == 2U)
{
/* Reset Address Event counter */
hi2c->AddrEventCount = 0U;
/* Clear ADDR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call Slave Addr callback */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
#else
HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
else
{
slaveaddrcode = ownadd2code;
/* Disable ADDR Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call Slave Addr callback */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
#else
HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/* else 7 bits addressing mode is selected */
else
{
/* Disable ADDR Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call Slave Addr callback */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode);
#else
HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/* Else clear address flag only */
else
{
/* Clear ADDR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
}
}
/**
* @brief I2C Master sequential complete process.
* @param hi2c I2C handle.
* @retval None
*/
static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c)
{
/* Reset I2C handle mode */
hi2c->Mode = HAL_I2C_MODE_NONE;
/* No Generate Stop, to permit restart mode */
/* The stop will be done at the end of transfer, when I2C_AUTOEND_MODE enable */
if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
hi2c->XferISR = NULL;
/* Disable Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MasterTxCpltCallback(hi2c);
#else
HAL_I2C_MasterTxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
/* hi2c->State == HAL_I2C_STATE_BUSY_RX */
else
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
hi2c->XferISR = NULL;
/* Disable Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MasterRxCpltCallback(hi2c);
#else
HAL_I2C_MasterRxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/**
* @brief I2C Slave sequential complete process.
* @param hi2c I2C handle.
* @retval None
*/
static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c)
{
uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1);
/* Reset I2C handle mode */
hi2c->Mode = HAL_I2C_MODE_NONE;
/* If a DMA is ongoing, Update handle size context */
if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET)
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
}
else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET)
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
}
else
{
/* Do nothing */
}
if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN)
{
/* Remove HAL_I2C_STATE_SLAVE_BUSY_TX, keep only HAL_I2C_STATE_LISTEN */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
/* Disable Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->SlaveTxCpltCallback(hi2c);
#else
HAL_I2C_SlaveTxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)
{
/* Remove HAL_I2C_STATE_SLAVE_BUSY_RX, keep only HAL_I2C_STATE_LISTEN */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
/* Disable Interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->SlaveRxCpltCallback(hi2c);
#else
HAL_I2C_SlaveRxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else
{
/* Nothing to do */
}
}
/**
* @brief I2C Master complete process.
* @param hi2c I2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
{
uint32_t tmperror;
uint32_t tmpITFlags = ITFlags;
__IO uint32_t tmpreg;
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Disable Interrupts and Store Previous state */
if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
{
I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT);
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
}
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
{
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT);
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX;
}
else
{
/* Do nothing */
}
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
/* Reset handle parameters */
hi2c->XferISR = NULL;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET)
{
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Set acknowledge error code */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
}
/* Fetch Last receive data if any */
if ((hi2c->State == HAL_I2C_STATE_ABORT) && (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET))
{
/* Read data from RXDR */
tmpreg = (uint8_t)hi2c->Instance->RXDR;
UNUSED(tmpreg);
}
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* Store current volatile hi2c->ErrorCode, misra rule */
tmperror = hi2c->ErrorCode;
/* Call the corresponding callback to inform upper layer of End of Transfer */
if ((hi2c->State == HAL_I2C_STATE_ABORT) || (tmperror != HAL_I2C_ERROR_NONE))
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, hi2c->ErrorCode);
}
/* hi2c->State == HAL_I2C_STATE_BUSY_TX */
else if (hi2c->State == HAL_I2C_STATE_BUSY_TX)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
if (hi2c->Mode == HAL_I2C_MODE_MEM)
{
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MemTxCpltCallback(hi2c);
#else
HAL_I2C_MemTxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else
{
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MasterTxCpltCallback(hi2c);
#else
HAL_I2C_MasterTxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/* hi2c->State == HAL_I2C_STATE_BUSY_RX */
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
if (hi2c->Mode == HAL_I2C_MODE_MEM)
{
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MemRxCpltCallback(hi2c);
#else
HAL_I2C_MemRxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else
{
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->MasterRxCpltCallback(hi2c);
#else
HAL_I2C_MasterRxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
else
{
/* Nothing to do */
}
}
/**
* @brief I2C Slave complete process.
* @param hi2c I2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
{
uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1);
uint32_t tmpITFlags = ITFlags;
HAL_I2C_StateTypeDef tmpstate = hi2c->State;
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Disable Interrupts and Store Previous state */
if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN))
{
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT);
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
}
else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
{
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT);
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
}
else
{
/* Do nothing */
}
/* Disable Address Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* If a DMA is ongoing, Update handle size context */
if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET)
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
if (hi2c->hdmatx != NULL)
{
hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx);
}
}
else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET)
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
if (hi2c->hdmarx != NULL)
{
hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx);
}
}
else
{
/* Do nothing */
}
/* Store Last receive data if any */
if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET)
{
/* Remove RXNE flag on temporary variable as read done */
tmpITFlags &= ~I2C_FLAG_RXNE;
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
if ((hi2c->XferSize > 0U))
{
hi2c->XferSize--;
hi2c->XferCount--;
}
}
/* All data are not transferred, so set error code accordingly */
if (hi2c->XferCount != 0U)
{
/* Set ErrorCode corresponding to a Non-Acknowledge */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
}
hi2c->Mode = HAL_I2C_MODE_NONE;
hi2c->XferISR = NULL;
if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, hi2c->ErrorCode);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
if (hi2c->State == HAL_I2C_STATE_LISTEN)
{
/* Call I2C Listen complete process */
I2C_ITListenCplt(hi2c, tmpITFlags);
}
}
else if (hi2c->XferOptions != I2C_NO_OPTION_FRAME)
{
/* Call the Sequential Complete callback, to inform upper layer of the end of Transfer */
I2C_ITSlaveSeqCplt(hi2c);
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->ListenCpltCallback(hi2c);
#else
HAL_I2C_ListenCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
/* Call the corresponding callback to inform upper layer of End of Transfer */
else if (hi2c->State == HAL_I2C_STATE_BUSY_RX)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->SlaveRxCpltCallback(hi2c);
#else
HAL_I2C_SlaveRxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->SlaveTxCpltCallback(hi2c);
#else
HAL_I2C_SlaveTxCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/**
* @brief I2C Listen complete process.
* @param hi2c I2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags)
{
/* Reset handle parameters */
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->PreviousState = I2C_STATE_NONE;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
hi2c->XferISR = NULL;
/* Store Last receive data if any */
if (I2C_CHECK_FLAG(ITFlags, I2C_FLAG_RXNE) != RESET)
{
/* Read data from RXDR */
*hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR;
/* Increment Buffer pointer */
hi2c->pBuffPtr++;
if ((hi2c->XferSize > 0U))
{
hi2c->XferSize--;
hi2c->XferCount--;
/* Set ErrorCode corresponding to a Non-Acknowledge */
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
}
}
/* Disable all Interrupts*/
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT);
/* Clear NACK Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->ListenCpltCallback(hi2c);
#else
HAL_I2C_ListenCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
/**
* @brief I2C interrupts error process.
* @param hi2c I2C handle.
* @param ErrorCode Error code to handle.
* @retval None
*/
static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode)
{
HAL_I2C_StateTypeDef tmpstate = hi2c->State;
uint32_t tmppreviousstate;
/* Reset handle parameters */
hi2c->Mode = HAL_I2C_MODE_NONE;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferCount = 0U;
/* Set new error code */
hi2c->ErrorCode |= ErrorCode;
/* Disable Interrupts */
if ((tmpstate == HAL_I2C_STATE_LISTEN) ||
(tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN) ||
(tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN))
{
/* Disable all interrupts, except interrupts related to LISTEN state */
I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_TX_IT);
/* keep HAL_I2C_STATE_LISTEN if set */
hi2c->State = HAL_I2C_STATE_LISTEN;
hi2c->XferISR = I2C_Slave_ISR_IT;
}
else
{
/* Disable all interrupts */
I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT);
/* If state is an abort treatment on going, don't change state */
/* This change will be do later */
if (hi2c->State != HAL_I2C_STATE_ABORT)
{
/* Set HAL_I2C_STATE_READY */
hi2c->State = HAL_I2C_STATE_READY;
}
hi2c->XferISR = NULL;
}
/* Abort DMA TX transfer if any */
tmppreviousstate = hi2c->PreviousState;
if ((hi2c->hdmatx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_TX) || \
(tmppreviousstate == I2C_STATE_SLAVE_BUSY_TX)))
{
if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
}
if (HAL_DMA_GetState(hi2c->hdmatx) != HAL_DMA_STATE_READY)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
}
}
else
{
I2C_TreatErrorCallback(hi2c);
}
}
/* Abort DMA RX transfer if any */
else if ((hi2c->hdmarx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_RX) || \
(tmppreviousstate == I2C_STATE_SLAVE_BUSY_RX)))
{
if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN)
{
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
}
if (HAL_DMA_GetState(hi2c->hdmarx) != HAL_DMA_STATE_READY)
{
/* Set the I2C DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
{
/* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */
hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
}
}
else
{
I2C_TreatErrorCallback(hi2c);
}
}
else
{
I2C_TreatErrorCallback(hi2c);
}
}
/**
* @brief I2C Error callback treatment.
* @param hi2c I2C handle.
* @retval None
*/
static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c)
{
if (hi2c->State == HAL_I2C_STATE_ABORT)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->AbortCpltCallback(hi2c);
#else
HAL_I2C_AbortCpltCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
else
{
hi2c->PreviousState = I2C_STATE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1)
hi2c->ErrorCallback(hi2c);
#else
HAL_I2C_ErrorCallback(hi2c);
#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */
}
}
/**
* @brief I2C Tx data register flush process.
* @param hi2c I2C handle.
* @retval None
*/
static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c)
{
/* If a pending TXIS flag is set */
/* Write a dummy data in TXDR to clear it */
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) != RESET)
{
hi2c->Instance->TXDR = 0x00U;
}
/* Flush TX register if not empty */
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET)
{
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_TXE);
}
}
/**
* @brief DMA I2C master transmit process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
/* If last transfer, enable STOP interrupt */
if (hi2c->XferCount == 0U)
{
/* Enable STOP interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
}
/* else prepare a new DMA transfer and enable TCReload interrupt */
else
{
/* Update Buffer pointer */
hi2c->pBuffPtr += hi2c->XferSize;
/* Set the XferSize to transfer */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
}
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR,
hi2c->XferSize) != HAL_OK)
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
}
else
{
/* Enable TC interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT);
}
}
}
/**
* @brief DMA I2C slave transmit process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
uint32_t tmpoptions = hi2c->XferOptions;
if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME))
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN;
/* Last Byte is Transmitted */
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
else
{
/* No specific action, Master fully manage the generation of STOP condition */
/* Mean that this generation can arrive at any time, at the end or during DMA process */
/* So STOP condition should be manage through Interrupt treatment */
}
}
/**
* @brief DMA I2C master receive process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
/* If last transfer, enable STOP interrupt */
if (hi2c->XferCount == 0U)
{
/* Enable STOP interrupt */
I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT);
}
/* else prepare a new DMA transfer and enable TCReload interrupt */
else
{
/* Update Buffer pointer */
hi2c->pBuffPtr += hi2c->XferSize;
/* Set the XferSize to transfer */
if (hi2c->XferCount > MAX_NBYTE_SIZE)
{
hi2c->XferSize = MAX_NBYTE_SIZE;
}
else
{
hi2c->XferSize = hi2c->XferCount;
}
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr,
hi2c->XferSize) != HAL_OK)
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
}
else
{
/* Enable TC interrupts */
I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT);
}
}
}
/**
* @brief DMA I2C slave receive process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
uint32_t tmpoptions = hi2c->XferOptions;
if ((I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) && \
(tmpoptions != I2C_NO_OPTION_FRAME))
{
/* Disable DMA Request */
hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN;
/* Call I2C Slave Sequential complete process */
I2C_ITSlaveSeqCplt(hi2c);
}
else
{
/* No specific action, Master fully manage the generation of STOP condition */
/* Mean that this generation can arrive at any time, at the end or during DMA process */
/* So STOP condition should be manage through Interrupt treatment */
}
}
/**
* @brief DMA I2C communication error callback.
* @param hdma DMA handle
* @retval None
*/
static void I2C_DMAError(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
/* Disable Acknowledge */
hi2c->Instance->CR2 |= I2C_CR2_NACK;
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c, HAL_I2C_ERROR_DMA);
}
/**
* @brief DMA I2C communication abort callback
* (To be called at end of DMA Abort procedure).
* @param hdma DMA handle.
* @retval None
*/
static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
{
/* Derogation MISRAC2012-Rule-11.5 */
I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent);
/* Reset AbortCpltCallback */
if (hi2c->hdmatx != NULL)
{
hi2c->hdmatx->XferAbortCallback = NULL;
}
if (hi2c->hdmarx != NULL)
{
hi2c->hdmarx->XferAbortCallback = NULL;
}
I2C_TreatErrorCallback(hi2c);
}
/**
* @brief This function handles I2C Communication Timeout. It waits
* until a flag is no longer in the specified status.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param Flag Specifies the I2C flag to check.
* @param Status The actual Flag status (SET or RESET).
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status,
uint32_t Timeout, uint32_t Tickstart)
{
while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status)
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
}
return HAL_OK;
}
/**
* @brief This function handles I2C Communication Timeout for specific usage of TXIS flag.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart)
{
while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET)
{
/* Check if an error is detected */
if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
}
return HAL_OK;
}
/**
* @brief This function handles I2C Communication Timeout for specific usage of STOP flag.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart)
{
while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)
{
/* Check if an error is detected */
if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check for the Timeout */
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
return HAL_OK;
}
/**
* @brief This function handles I2C Communication Timeout for specific usage of RXNE flag.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout,
uint32_t Tickstart)
{
while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET)
{
/* Check if an error is detected */
if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check if a STOPF is detected */
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET)
{
/* Check if an RXNE is pending */
/* Store Last receive data if any */
if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) && (hi2c->XferSize > 0U))
{
/* Return HAL_OK */
/* The Reading of data from RXDR will be done in caller function */
return HAL_OK;
}
else
{
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
{
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
hi2c->ErrorCode = HAL_I2C_ERROR_AF;
}
else
{
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
}
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
/* Check for the Timeout */
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
}
return HAL_OK;
}
/**
* @brief This function handles errors detection during an I2C Communication.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t itflag = hi2c->Instance->ISR;
uint32_t error_code = 0;
uint32_t tickstart = Tickstart;
uint32_t tmp1;
HAL_I2C_ModeTypeDef tmp2;
if (HAL_IS_BIT_SET(itflag, I2C_FLAG_AF))
{
/* Clear NACKF Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Wait until STOP Flag is set or timeout occurred */
/* AutoEnd should be initiate after AF */
while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (status == HAL_OK))
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
tmp1 = (uint32_t)(hi2c->Instance->CR2 & I2C_CR2_STOP);
tmp2 = hi2c->Mode;
/* In case of I2C still busy, try to regenerate a STOP manually */
if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && \
(tmp1 != I2C_CR2_STOP) && \
(tmp2 != HAL_I2C_MODE_SLAVE))
{
/* Generate Stop */
hi2c->Instance->CR2 |= I2C_CR2_STOP;
/* Update Tick with new reference */
tickstart = HAL_GetTick();
}
while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > I2C_TIMEOUT_STOPF)
{
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
status = HAL_ERROR;
}
}
}
}
}
/* In case STOP Flag is detected, clear it */
if (status == HAL_OK)
{
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
}
error_code |= HAL_I2C_ERROR_AF;
status = HAL_ERROR;
}
/* Refresh Content of Status register */
itflag = hi2c->Instance->ISR;
/* Then verify if an additional errors occurs */
/* Check if a Bus error occurred */
if (HAL_IS_BIT_SET(itflag, I2C_FLAG_BERR))
{
error_code |= HAL_I2C_ERROR_BERR;
/* Clear BERR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR);
status = HAL_ERROR;
}
/* Check if an Over-Run/Under-Run error occurred */
if (HAL_IS_BIT_SET(itflag, I2C_FLAG_OVR))
{
error_code |= HAL_I2C_ERROR_OVR;
/* Clear OVR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
status = HAL_ERROR;
}
/* Check if an Arbitration Loss error occurred */
if (HAL_IS_BIT_SET(itflag, I2C_FLAG_ARLO))
{
error_code |= HAL_I2C_ERROR_ARLO;
/* Clear ARLO flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO);
status = HAL_ERROR;
}
if (status != HAL_OK)
{
/* Flush TX register */
I2C_Flush_TXDR(hi2c);
/* Clear Configuration Register 2 */
I2C_RESET_CR2(hi2c);
hi2c->ErrorCode |= error_code;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
}
return status;
}
/**
* @brief Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set).
* @param hi2c I2C handle.
* @param DevAddress Specifies the slave address to be programmed.
* @param Size Specifies the number of bytes to be programmed.
* This parameter must be a value between 0 and 255.
* @param Mode New state of the I2C START condition generation.
* This parameter can be one of the following values:
* @arg @ref I2C_RELOAD_MODE Enable Reload mode .
* @arg @ref I2C_AUTOEND_MODE Enable Automatic end mode.
* @arg @ref I2C_SOFTEND_MODE Enable Software end mode.
* @param Request New state of the I2C START condition generation.
* This parameter can be one of the following values:
* @arg @ref I2C_NO_STARTSTOP Don't Generate stop and start condition.
* @arg @ref I2C_GENERATE_STOP Generate stop condition (Size should be set to 0).
* @arg @ref I2C_GENERATE_START_READ Generate Restart for read request.
* @arg @ref I2C_GENERATE_START_WRITE Generate Restart for write request.
* @retval None
*/
static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode,
uint32_t Request)
{
/* Check the parameters */
assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
assert_param(IS_TRANSFER_MODE(Mode));
assert_param(IS_TRANSFER_REQUEST(Request));
/* Declaration of tmp to prevent undefined behavior of volatile usage */
uint32_t tmp = ((uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \
(((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \
(uint32_t)Mode | (uint32_t)Request) & (~0x80000000U));
/* update CR2 register */
MODIFY_REG(hi2c->Instance->CR2, \
((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \
(I2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - I2C_CR2_RD_WRN_Pos))) | \
I2C_CR2_START | I2C_CR2_STOP)), tmp);
}
/**
* @brief Manage the enabling of Interrupts.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition.
* @retval None
*/
static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest)
{
uint32_t tmpisr = 0U;
if ((hi2c->XferISR == I2C_Master_ISR_DMA) || \
(hi2c->XferISR == I2C_Slave_ISR_DMA))
{
if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
{
/* Enable ERR, STOP, NACK and ADDR interrupts */
tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
}
if (InterruptRequest == I2C_XFER_ERROR_IT)
{
/* Enable ERR and NACK interrupts */
tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI;
}
if (InterruptRequest == I2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= (I2C_IT_STOPI | I2C_IT_TCI);
}
if (InterruptRequest == I2C_XFER_RELOAD_IT)
{
/* Enable TC interrupts */
tmpisr |= I2C_IT_TCI;
}
}
else
{
if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
{
/* Enable ERR, STOP, NACK, and ADDR interrupts */
tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
}
if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT)
{
/* Enable ERR, TC, STOP, NACK and RXI interrupts */
tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI;
}
if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT)
{
/* Enable ERR, TC, STOP, NACK and TXI interrupts */
tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI;
}
if (InterruptRequest == I2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= I2C_IT_STOPI;
}
}
/* Enable interrupts only at the end */
/* to avoid the risk of I2C interrupt handle execution before */
/* all interrupts requested done */
__HAL_I2C_ENABLE_IT(hi2c, tmpisr);
}
/**
* @brief Manage the disabling of Interrupts.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2C.
* @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition.
* @retval None
*/
static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest)
{
uint32_t tmpisr = 0U;
if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT)
{
/* Disable TC and TXI interrupts */
tmpisr |= I2C_IT_TCI | I2C_IT_TXI;
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN)
{
/* Disable NACK and STOP interrupts */
tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
}
}
if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT)
{
/* Disable TC and RXI interrupts */
tmpisr |= I2C_IT_TCI | I2C_IT_RXI;
if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN)
{
/* Disable NACK and STOP interrupts */
tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
}
}
if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT)
{
/* Disable ADDR, NACK and STOP interrupts */
tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI;
}
if (InterruptRequest == I2C_XFER_ERROR_IT)
{
/* Enable ERR and NACK interrupts */
tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI;
}
if (InterruptRequest == I2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= I2C_IT_STOPI;
}
if (InterruptRequest == I2C_XFER_RELOAD_IT)
{
/* Enable TC interrupts */
tmpisr |= I2C_IT_TCI;
}
/* Disable interrupts only at the end */
/* to avoid a breaking situation like at "t" time */
/* all disable interrupts request are not done */
__HAL_I2C_DISABLE_IT(hi2c, tmpisr);
}
/**
* @brief Convert I2Cx OTHER_xxx XferOptions to functional XferOptions.
* @param hi2c I2C handle.
* @retval None
*/
static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c)
{
/* if user set XferOptions to I2C_OTHER_FRAME */
/* it request implicitly to generate a restart condition */
/* set XferOptions to I2C_FIRST_FRAME */
if (hi2c->XferOptions == I2C_OTHER_FRAME)
{
hi2c->XferOptions = I2C_FIRST_FRAME;
}
/* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */
/* it request implicitly to generate a restart condition */
/* then generate a stop condition at the end of transfer */
/* set XferOptions to I2C_FIRST_AND_LAST_FRAME */
else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME)
{
hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME;
}
else
{
/* Nothing to do */
}
}
/**
* @}
*/
#endif /* HAL_I2C_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 224,605 |
C
| 31.622513 | 117 | 0.612141 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_hrtim.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_hrtim.c
* @author MCD Application Team
* @brief HRTIM LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_hrtim.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (HRTIM1)
/** @addtogroup HRTIM_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup HRTIM_LL_Exported_Functions
* @{
*/
/**
* @brief Set HRTIM instance registers to their reset values.
* @param HRTIMx High Resolution Timer instance
* @retval ErrorStatus enumeration value:
* - SUCCESS: HRTIMx registers are de-initialized
* - ERROR: invalid HRTIMx instance
*/
ErrorStatus LL_HRTIM_DeInit(HRTIM_TypeDef *HRTIMx)
{
ErrorStatus result = SUCCESS;
/* Check the parameters */
assert_param(IS_HRTIM_ALL_INSTANCE(HRTIMx));
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_HRTIM1);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_HRTIM1);
return result;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HRTIM1 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 2,256 |
C
| 26.864197 | 80 | 0.468085 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_usb.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_LL_USB_DRIVER
* @{
*/
#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED)
#if defined (USB)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the USB Core
* @param USBx USB Instance
* @param cfg pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_CoreInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(USBx);
UNUSED(cfg);
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_EnableGlobalInt
* Enables the controller's Global Int in the AHB Config reg
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_EnableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask;
/* Clear pending interrupts */
USBx->ISTR = 0U;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM |
USB_CNTR_SUSPM | USB_CNTR_ERRM |
USB_CNTR_SOFM | USB_CNTR_ESOFM |
USB_CNTR_RESETM | USB_CNTR_L1REQM;
/* Set interrupt mask */
USBx->CNTR = (uint16_t)winterruptmask;
return HAL_OK;
}
/**
* @brief USB_DisableGlobalInt
* Disable the controller's Global Int in the AHB Config reg
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DisableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM |
USB_CNTR_SUSPM | USB_CNTR_ERRM |
USB_CNTR_SOFM | USB_CNTR_ESOFM |
USB_CNTR_RESETM | USB_CNTR_L1REQM;
/* Clear interrupt mask */
USBx->CNTR &= (uint16_t)(~winterruptmask);
return HAL_OK;
}
/**
* @brief USB_SetCurrentMode Set functional mode
* @param USBx Selected device
* @param mode current core mode
* This parameter can be one of the these values:
* @arg USB_DEVICE_MODE Peripheral mode
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx, USB_ModeTypeDef mode)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(USBx);
UNUSED(mode);
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_DevInit Initializes the USB controller registers
* for device mode
* @param USBx Selected device
* @param cfg pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(cfg);
/* Init Device */
/* CNTR_FRES = 1 */
USBx->CNTR = (uint16_t)USB_CNTR_FRES;
/* CNTR_FRES = 0 */
USBx->CNTR = 0U;
/* Clear pending interrupts */
USBx->ISTR = 0U;
/*Set Btable Address*/
USBx->BTABLE = BTABLE_ADDRESS;
return HAL_OK;
}
#if defined (HAL_PCD_MODULE_ENABLED)
/**
* @brief Activate and configure an endpoint
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
HAL_StatusTypeDef ret = HAL_OK;
uint16_t wEpRegVal;
wEpRegVal = PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_T_MASK;
/* initialize Endpoint */
switch (ep->type)
{
case EP_TYPE_CTRL:
wEpRegVal |= USB_EP_CONTROL;
break;
case EP_TYPE_BULK:
wEpRegVal |= USB_EP_BULK;
break;
case EP_TYPE_INTR:
wEpRegVal |= USB_EP_INTERRUPT;
break;
case EP_TYPE_ISOC:
wEpRegVal |= USB_EP_ISOCHRONOUS;
break;
default:
ret = HAL_ERROR;
break;
}
PCD_SET_ENDPOINT(USBx, ep->num, (wEpRegVal | USB_EP_CTR_RX | USB_EP_CTR_TX));
PCD_SET_EP_ADDRESS(USBx, ep->num, ep->num);
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
/*Set the endpoint Transmit buffer address */
PCD_SET_EP_TX_ADDRESS(USBx, ep->num, ep->pmaadress);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
else
{
/* Configure TX Endpoint to disabled state */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
}
else
{
/* Set the endpoint Receive buffer address */
PCD_SET_EP_RX_ADDRESS(USBx, ep->num, ep->pmaadress);
/* Set the endpoint Receive buffer counter */
PCD_SET_EP_RX_CNT(USBx, ep->num, ep->maxpacket);
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure VALID status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/* Double Buffer */
else
{
if (ep->type == EP_TYPE_BULK)
{
/* Set bulk endpoint as double buffered */
PCD_SET_BULK_EP_DBUF(USBx, ep->num);
}
else
{
/* Set the ISOC endpoint in double buffer mode */
PCD_CLEAR_EP_KIND(USBx, ep->num);
}
/* Set buffer address for double buffered mode */
PCD_SET_EP_DBUF_ADDR(USBx, ep->num, ep->pmaaddr0, ep->pmaaddr1);
if (ep->is_in == 0U)
{
/* Clear the data toggle bits for the endpoint IN/OUT */
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT */
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
else
{
/* Configure TX Endpoint to disabled state */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return ret;
}
/**
* @brief De-activate and de-initialize an endpoint
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/* Double Buffer */
else
{
if (ep->is_in == 0U)
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Reset value of the data toggle bits for the endpoint out*/
PCD_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return HAL_OK;
}
/**
* @brief USB_EPStartXfer setup and starts a transfer over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPStartXfer(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
uint32_t len;
#if (USE_USB_DOUBLE_BUFFER == 1U)
uint16_t pmabuffer;
uint16_t wEPVal;
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/* IN endpoint */
if (ep->is_in == 1U)
{
/*Multi packet transfer*/
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
}
else
{
len = ep->xfer_len;
}
/* configure and validate Tx endpoint */
if (ep->doublebuffer == 0U)
{
USB_WritePMA(USBx, ep->xfer_buff, ep->pmaadress, (uint16_t)len);
PCD_SET_EP_TX_CNT(USBx, ep->num, len);
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else
{
/* double buffer bulk management */
if (ep->type == EP_TYPE_BULK)
{
if (ep->xfer_len_db > ep->maxpacket)
{
/* enable double buffer */
PCD_SET_BULK_EP_DBUF(USBx, ep->num);
/* each Time to write in PMA xfer_len_db will */
ep->xfer_len_db -= len;
/* Fill the two first buffer in the Buffer0 & Buffer1 */
if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U)
{
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
ep->xfer_buff += len;
if (ep->xfer_len_db > ep->maxpacket)
{
ep->xfer_len_db -= len;
}
else
{
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
}
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
else
{
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
ep->xfer_buff += len;
if (ep->xfer_len_db > ep->maxpacket)
{
ep->xfer_len_db -= len;
}
else
{
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
}
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
/* auto Switch to single buffer mode when transfer <Mps no need to manage in double buffer */
else
{
len = ep->xfer_len_db;
/* disable double buffer mode for Bulk endpoint */
PCD_CLEAR_BULK_EP_DBUF(USBx, ep->num);
/* Set Tx count with nbre of byte to be transmitted */
PCD_SET_EP_TX_CNT(USBx, ep->num, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
else /* manage isochronous double buffer IN mode */
{
/* each Time to write in PMA xfer_len_db will */
ep->xfer_len_db -= len;
/* Fill the data buffer */
if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U)
{
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
else
{
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
/* Write the user buffer to USB PMA */
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len);
}
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_VALID);
}
else /* OUT endpoint */
{
if (ep->doublebuffer == 0U)
{
/* Multi packet transfer */
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len -= len;
}
else
{
len = ep->xfer_len;
ep->xfer_len = 0U;
}
/* configure and validate Rx endpoint */
PCD_SET_EP_RX_CNT(USBx, ep->num, len);
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else
{
/* First Transfer Coming From HAL_PCD_EP_Receive & From ISR */
/* Set the Double buffer counter */
if (ep->type == EP_TYPE_BULK)
{
PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, ep->maxpacket);
/* Coming from ISR */
if (ep->xfer_count != 0U)
{
/* update last value to check if there is blocking state */
wEPVal = PCD_GET_ENDPOINT(USBx, ep->num);
/*Blocking State */
if ((((wEPVal & USB_EP_DTOG_RX) != 0U) && ((wEPVal & USB_EP_DTOG_TX) != 0U)) ||
(((wEPVal & USB_EP_DTOG_RX) == 0U) && ((wEPVal & USB_EP_DTOG_TX) == 0U)))
{
PCD_FREE_USER_BUFFER(USBx, ep->num, 0U);
}
}
}
/* iso out double */
else if (ep->type == EP_TYPE_ISOC)
{
/* Multi packet transfer */
if (ep->xfer_len > ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len -= len;
}
else
{
len = ep->xfer_len;
ep->xfer_len = 0U;
}
PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, len);
}
else
{
return HAL_ERROR;
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
return HAL_OK;
}
/**
* @brief USB_EPSetStall set a stall condition over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPSetStall(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->is_in != 0U)
{
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_STALL);
}
else
{
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_STALL);
}
return HAL_OK;
}
/**
* @brief USB_EPClearStall Clear a stall condition over an EP
* @param USBx Selected device
* @param ep pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPClearStall(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->doublebuffer == 0U)
{
if (ep->is_in != 0U)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
if (ep->type != EP_TYPE_ISOC)
{
/* Configure NAK status for the Endpoint */
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure VALID status for the Endpoint */
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
}
return HAL_OK;
}
#endif /* defined (HAL_PCD_MODULE_ENABLED) */
/**
* @brief USB_StopDevice Stop the usb device mode
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_StopDevice(USB_TypeDef *USBx)
{
/* disable all interrupts and force USB reset */
USBx->CNTR = (uint16_t)USB_CNTR_FRES;
/* clear interrupt status register */
USBx->ISTR = 0U;
/* switch-off device */
USBx->CNTR = (uint16_t)(USB_CNTR_FRES | USB_CNTR_PDWN);
return HAL_OK;
}
/**
* @brief USB_SetDevAddress Stop the usb device mode
* @param USBx Selected device
* @param address new device address to be assigned
* This parameter can be a value from 0 to 255
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetDevAddress(USB_TypeDef *USBx, uint8_t address)
{
if (address == 0U)
{
/* set device address and enable function */
USBx->DADDR = (uint16_t)USB_DADDR_EF;
}
return HAL_OK;
}
/**
* @brief USB_DevConnect Connect the USB device by enabling the pull-up/pull-down
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevConnect(USB_TypeDef *USBx)
{
/* Enabling DP Pull-UP bit to Connect internal PU resistor on USB DP line */
USBx->BCDR |= (uint16_t)USB_BCDR_DPPU;
return HAL_OK;
}
/**
* @brief USB_DevDisconnect Disconnect the USB device by disabling the pull-up/pull-down
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevDisconnect(USB_TypeDef *USBx)
{
/* Disable DP Pull-Up bit to disconnect the Internal PU resistor on USB DP line */
USBx->BCDR &= (uint16_t)(~(USB_BCDR_DPPU));
return HAL_OK;
}
/**
* @brief USB_ReadInterrupts return the global USB interrupt status
* @param USBx Selected device
* @retval HAL status
*/
uint32_t USB_ReadInterrupts(USB_TypeDef *USBx)
{
uint32_t tmpreg;
tmpreg = USBx->ISTR;
return tmpreg;
}
/**
* @brief USB_ActivateRemoteWakeup : active remote wakeup signalling
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR |= (uint16_t)USB_CNTR_RESUME;
return HAL_OK;
}
/**
* @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling
* @param USBx Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR &= (uint16_t)(~USB_CNTR_RESUME);
return HAL_OK;
}
/**
* @brief Copy a buffer from user memory area to packet memory area (PMA)
* @param USBx USB peripheral instance register address.
* @param pbUsrBuf pointer to user memory area.
* @param wPMABufAddr address into PMA.
* @param wNBytes no. of bytes to be copied.
* @retval None
*/
void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = ((uint32_t)wNBytes + 1U) >> 1;
uint32_t BaseAddr = (uint32_t)USBx;
uint32_t i;
uint32_t temp1;
uint32_t temp2;
__IO uint16_t *pdwVal;
uint8_t *pBuf = pbUsrBuf;
pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS));
for (i = n; i != 0U; i--)
{
temp1 = *pBuf;
pBuf++;
temp2 = temp1 | ((uint16_t)((uint16_t) *pBuf << 8));
*pdwVal = (uint16_t)temp2;
pdwVal++;
#if PMA_ACCESS > 1U
pdwVal++;
#endif /* PMA_ACCESS */
pBuf++;
}
}
/**
* @brief Copy data from packet memory area (PMA) to user memory buffer
* @param USBx USB peripheral instance register address.
* @param pbUsrBuf pointer to user memory area.
* @param wPMABufAddr address into PMA.
* @param wNBytes no. of bytes to be copied.
* @retval None
*/
void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = (uint32_t)wNBytes >> 1;
uint32_t BaseAddr = (uint32_t)USBx;
uint32_t i;
uint32_t temp;
__IO uint16_t *pdwVal;
uint8_t *pBuf = pbUsrBuf;
pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS));
for (i = n; i != 0U; i--)
{
temp = *(__IO uint16_t *)pdwVal;
pdwVal++;
*pBuf = (uint8_t)((temp >> 0) & 0xFFU);
pBuf++;
*pBuf = (uint8_t)((temp >> 8) & 0xFFU);
pBuf++;
#if PMA_ACCESS > 1U
pdwVal++;
#endif /* PMA_ACCESS */
}
if ((wNBytes % 2U) != 0U)
{
temp = *pdwVal;
*pBuf = (uint8_t)((temp >> 0) & 0xFFU);
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */
/**
* @}
*/
| 22,348 |
C
| 26.155529 | 101 | 0.561795 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_smbus_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 STM32G4xx
devices contains the following additional features
(+) Disable or enable wakeup from Stop mode(s)
(+) Disable or enable Fast Mode Plus
##### 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_EnableFastModePlus()
(++) HAL_SMBUSEx_DisableFastModePlus()
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 Enable the SMBUS fast mode plus driving capability.
* @param ConfigFastModePlus Selects the pin.
* This parameter can be one of the @ref SMBUSEx_FastModePlus values
* @note For I2C1, fast mode plus driving capability can be enabled on all selected
* I2C1 pins using SMBUS_FASTMODEPLUS_I2C1 parameter or independently
* on each one of the following pins PB6, PB7, PB8 and PB9.
* @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability
* can be enabled only by using SMBUS_FASTMODEPLUS_I2C1 parameter.
* @note For all I2C2 pins fast mode plus driving capability can be enabled
* only by using SMBUS_FASTMODEPLUS_I2C2 parameter.
* @note For all I2C3 pins fast mode plus driving capability can be enabled
* only by using SMBUS_FASTMODEPLUS_I2C3 parameter.
* @note For all I2C4 pins fast mode plus driving capability can be enabled
* only by using SMBUS_FASTMODEPLUS_I2C4 parameter.
* @retval None
*/
void HAL_SMBUSEx_EnableFastModePlus(uint32_t ConfigFastModePlus)
{
/* Check the parameter */
assert_param(IS_SMBUS_FASTMODEPLUS(ConfigFastModePlus));
/* Enable SYSCFG clock */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* Enable fast mode plus driving capability for selected pin */
SET_BIT(SYSCFG->CFGR1, (uint32_t)ConfigFastModePlus);
}
/**
* @brief Disable the SMBUS fast mode plus driving capability.
* @param ConfigFastModePlus Selects the pin.
* This parameter can be one of the @ref SMBUSEx_FastModePlus values
* @note For I2C1, fast mode plus driving capability can be disabled on all selected
* I2C1 pins using SMBUS_FASTMODEPLUS_I2C1 parameter or independently
* on each one of the following pins PB6, PB7, PB8 and PB9.
* @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability
* can be disabled only by using SMBUS_FASTMODEPLUS_I2C1 parameter.
* @note For all I2C2 pins fast mode plus driving capability can be disabled
* only by using SMBUS_FASTMODEPLUS_I2C2 parameter.
* @note For all I2C3 pins fast mode plus driving capability can be disabled
* only by using SMBUS_FASTMODEPLUS_I2C3 parameter.
* @note For all I2C4 pins fast mode plus driving capability can be disabled
* only by using SMBUS_FASTMODEPLUS_I2C4 parameter.
* @retval None
*/
void HAL_SMBUSEx_DisableFastModePlus(uint32_t ConfigFastModePlus)
{
/* Check the parameter */
assert_param(IS_SMBUS_FASTMODEPLUS(ConfigFastModePlus));
/* Enable SYSCFG clock */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* Disable fast mode plus driving capability for selected pin */
CLEAR_BIT(SYSCFG->CFGR1, (uint32_t)ConfigFastModePlus);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_SMBUS_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 8,319 |
C
| 31.627451 | 98 | 0.568939 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_rtc.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_rtc.c
* @author MCD Application Team
* @brief RTC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_rtc.h"
#include "stm32g4xx_ll_cortex.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else /* USE_FULL_ASSERT */
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined(RTC)
/** @addtogroup RTC_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Constants
* @{
*/
/* Default values used for prescaler */
#define RTC_ASYNCH_PRESC_DEFAULT ((uint32_t) 0x0000007FU)
#define RTC_SYNCH_PRESC_DEFAULT ((uint32_t) 0x000000FFU)
/* Values used for timeout */
#define RTC_INITMODE_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */
#define RTC_SYNCHRO_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Macros
* @{
*/
#define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \
|| ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM))
#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU)
#define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU)
#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \
|| ((__VALUE__) == LL_RTC_FORMAT_BCD))
#define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \
|| ((__VALUE__) == LL_RTC_TIME_FORMAT_PM))
#define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U))
#define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U)
#define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U)
#define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U)
#define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY))
#define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= (uint32_t)1U) && ((__DAY__) <= (uint32_t)31U))
#define IS_LL_RTC_MONTH(__MONTH__) (((__MONTH__) >= 1U) && ((__MONTH__) <= 12U))
#define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U)
#define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_ALL))
#define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \
|| ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \
|| ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \
|| ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \
|| ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \
|| ((__VALUE__) == LL_RTC_ALMB_MASK_ALL))
#define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \
((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY))
#define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \
((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RTC_LL_Exported_Functions
* @{
*/
/** @addtogroup RTC_LL_EF_Init
* @{
*/
/**
* @brief De-Initializes the RTC registers to their default reset values.
* @note This function does not reset the RTC Clock source and RTC Backup Data
* registers.
* @param RTCx RTC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC registers are de-initialized
* - ERROR: RTC registers are not de-initialized
*/
ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx)
{
ErrorStatus status = ERROR;
/* Check the parameter */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_TAMP_ALL_INSTANCE(TAMP));
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Reset TR, DR and CR registers */
WRITE_REG(RTCx->TR, 0x00000000U);
#if defined(RTC_WAKEUP_SUPPORT)
WRITE_REG(RTCx->WUTR, RTC_WUTR_WUT);
#endif /* RTC_WAKEUP_SUPPORT */
WRITE_REG(RTCx->DR, (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0));
/* Reset All CR bits except CR[2:0] */
#if defined(RTC_WAKEUP_SUPPORT)
WRITE_REG(RTCx->CR, (READ_REG(RTCx->CR) & RTC_CR_WUCKSEL));
#else
WRITE_REG(RTCx->CR, 0x00000000U);
#endif /* RTC_WAKEUP_SUPPORT */
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, 0xFFFF0000U);
WRITE_REG(TAMP->CR2, 0x00000000U);
#if defined (RTC_OTHER_SUPPORT)
WRITE_REG(TAMP->CR3, 0x00000000U);
WRITE_REG(TAMP->SMCR, 0x00000000U);
WRITE_REG(TAMP->PRIVCR, 0x00000000U);
#endif /* RTC_OTHER_SUPPORT */
WRITE_REG(TAMP->FLTCR, 0x00000000U);
#if defined (RTC_ACTIVE_TAMPER_SUPPORT)
WRITE_REG(TAMP->ATCR1, 0x00000000U);
WRITE_REG(TAMP->ATCR2, 0x00000000U);
#endif /* RTC_ACTIVE_TAMPER_SUPPORT */
WRITE_REG(TAMP->IER, 0x00000000U);
WRITE_REG(TAMP->SCR, 0xFFFFFFFFU);
#if defined (RTC_OPTION_REG_SUPPORT)
WRITE_REG(TAMP->OR, 0x00000000U);
#endif /* RTC_OPTION_REG_SUPPORT */
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 prescaler factor */
LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler);
/* Configure Asynchronous prescaler factor */
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)(RTC_DateStruct->Month & (uint8_t)~(0x10U)) + 0x0AU;
}
if (RTC_Format == LL_RTC_FORMAT_BIN)
{
assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year));
assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month));
assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day));
}
else
{
assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year)));
assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month)));
assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day)));
}
assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay));
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Check the input parameters format */
if (RTC_Format != LL_RTC_FORMAT_BIN)
{
LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year);
}
else
{
LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day),
__LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year));
}
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTCx);
/* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U)
{
status = LL_RTC_WaitForSynchro(RTCx);
}
else
{
status = SUCCESS;
}
}
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return status;
}
/**
* @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00)
* @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized.
* @retval None
*/
void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct)
{
/* Monday, January 01 xx00 */
RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY;
RTC_DateStruct->Day = 1U;
RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY;
RTC_DateStruct->Year = 0U;
}
/**
* @brief Set the RTC Alarm A.
* @note The Alarm register can only be written when the corresponding Alarm
* is disabled (Use @ref LL_RTC_ALMA_Disable function).
* @param RTCx RTC Instance
* @param RTC_Format This parameter can be one of the following values:
* @arg @ref LL_RTC_FORMAT_BIN
* @arg @ref LL_RTC_FORMAT_BCD
* @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that
* contains the alarm configuration parameters.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ALARMA registers are configured
* - ERROR: ALARMA registers are not configured
*/
ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_LL_RTC_FORMAT(RTC_Format));
assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask));
assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel));
if (RTC_Format == LL_RTC_FORMAT_BIN)
{
/* initialize the AlarmTime for Binary format */
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
{
/* initialize the AlarmTime for BCD format */
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)
{
/* initialize the AlarmTime for Binary format */
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
{
/* initialize the AlarmTime for BCD format */
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 ALARMB 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 */
| 31,374 |
C
| 34.532276 | 122 | 0.621502 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_usart.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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);
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_TX;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
husart->TxXferSize = Size;
husart->TxXferCount = Size;
/* In case of 9bits/No Parity transfer, pTxData needs to be handled as a uint16_t pointer */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
ptxdata8bits = NULL;
ptxdata16bits = (const uint16_t *) pTxData;
}
else
{
ptxdata8bits = pTxData;
ptxdata16bits = NULL;
}
/* Check the remaining data to be sent */
while (husart->TxXferCount > 0U)
{
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (ptxdata8bits == NULL)
{
husart->Instance->TDR = (uint16_t)(*ptxdata16bits & 0x01FFU);
ptxdata16bits++;
}
else
{
husart->Instance->TDR = (uint8_t)(*ptxdata8bits & 0xFFU);
ptxdata8bits++;
}
husart->TxXferCount--;
}
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Clear Transmission Complete Flag */
__HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF);
/* Clear overrun flag and discard the received data */
__HAL_USART_CLEAR_OREFLAG(husart);
__HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST);
__HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST);
/* At end of Tx process, restore husart->State to Ready */
husart->State = HAL_USART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(husart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in blocking mode.
* @note To receive synchronous data, dummy data are simultaneously transmitted.
* @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the received data is handled as a set of u16. In this case, Size must indicate the number
* of u16 available through pRxData.
* @param husart USART handle.
* @param pRxData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be received.
* @param Timeout Timeout duration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)
{
uint8_t *prxdata8bits;
uint16_t *prxdata16bits;
uint16_t uhMask;
uint32_t tickstart;
if (husart->State == HAL_USART_STATE_READY)
{
if ((pRxData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(husart);
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_RX;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
husart->RxXferSize = Size;
husart->RxXferCount = Size;
/* Computation of USART mask to apply to RDR register */
USART_MASK_COMPUTATION(husart);
uhMask = husart->Mask;
/* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
prxdata8bits = NULL;
prxdata16bits = (uint16_t *) pRxData;
}
else
{
prxdata8bits = pRxData;
prxdata16bits = NULL;
}
/* as long as data have to be received */
while (husart->RxXferCount > 0U)
{
if (husart->SlaveMode == USART_SLAVEMODE_DISABLE)
{
/* Wait until TXE flag is set to send dummy byte in order to generate the
* clock for the slave to send data.
* Whatever the frame length (7, 8 or 9-bit long), the same dummy value
* can be written for all the cases. */
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x0FF);
}
/* Wait for RXNE Flag */
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (prxdata8bits == NULL)
{
*prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask);
prxdata16bits++;
}
else
{
*prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU));
prxdata8bits++;
}
husart->RxXferCount--;
}
/* Clear SPI slave underrun flag and discard transmit data */
if (husart->SlaveMode == USART_SLAVEMODE_ENABLE)
{
__HAL_USART_CLEAR_UDRFLAG(husart);
__HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST);
}
/* At end of Rx process, restore husart->State to Ready */
husart->State = HAL_USART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(husart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Full-Duplex Send and Receive an amount of data in blocking mode.
* @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number
* of u16 available through pTxData and through pRxData.
* @param husart USART handle.
* @param pTxData pointer to TX data buffer (u8 or u16 data elements).
* @param pRxData pointer to RX data buffer (u8 or u16 data elements).
* @param Size amount of data elements (u8 or u16) to be sent (same amount to be received).
* @param Timeout Timeout duration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData,
uint16_t Size, uint32_t Timeout)
{
uint8_t *prxdata8bits;
uint16_t *prxdata16bits;
const uint8_t *ptxdata8bits;
const uint16_t *ptxdata16bits;
uint16_t uhMask;
uint16_t rxdatacount;
uint32_t tickstart;
if (husart->State == HAL_USART_STATE_READY)
{
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(husart);
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_RX;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
husart->RxXferSize = Size;
husart->TxXferSize = Size;
husart->TxXferCount = Size;
husart->RxXferCount = Size;
/* Computation of USART mask to apply to RDR register */
USART_MASK_COMPUTATION(husart);
uhMask = husart->Mask;
/* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
prxdata8bits = NULL;
ptxdata8bits = NULL;
ptxdata16bits = (const uint16_t *) pTxData;
prxdata16bits = (uint16_t *) pRxData;
}
else
{
prxdata8bits = pRxData;
ptxdata8bits = pTxData;
ptxdata16bits = NULL;
prxdata16bits = NULL;
}
if ((husart->TxXferCount == 0x01U) || (husart->SlaveMode == USART_SLAVEMODE_ENABLE))
{
/* Wait until TXE flag is set to send data */
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (ptxdata8bits == NULL)
{
husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask);
ptxdata16bits++;
}
else
{
husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU));
ptxdata8bits++;
}
husart->TxXferCount--;
}
/* Check the remain data to be sent */
/* rxdatacount is a temporary variable for MISRAC2012-Rule-13.5 */
rxdatacount = husart->RxXferCount;
while ((husart->TxXferCount > 0U) || (rxdatacount > 0U))
{
if (husart->TxXferCount > 0U)
{
/* Wait until TXE flag is set to send data */
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (ptxdata8bits == NULL)
{
husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask);
ptxdata16bits++;
}
else
{
husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU));
ptxdata8bits++;
}
husart->TxXferCount--;
}
if (husart->RxXferCount > 0U)
{
/* Wait for RXNE Flag */
if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (prxdata8bits == NULL)
{
*prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask);
prxdata16bits++;
}
else
{
*prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU));
prxdata8bits++;
}
husart->RxXferCount--;
}
rxdatacount = husart->RxXferCount;
}
/* At end of TxRx process, restore husart->State to Ready */
husart->State = HAL_USART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(husart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Send an amount of data in interrupt mode.
* @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data is handled as a set of u16. In this case, Size must indicate the number
* of u16 provided through pTxData.
* @param husart USART handle.
* @param pTxData pointer to data buffer (u8 or u16 data elements).
* @param Size amount of data elements (u8 or u16) to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size)
{
if (husart->State == HAL_USART_STATE_READY)
{
if ((pTxData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(husart);
husart->pTxBuffPtr = pTxData;
husart->TxXferSize = Size;
husart->TxXferCount = Size;
husart->TxISR = NULL;
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_TX;
/* The USART Error Interrupts: (Frame error, noise error, overrun error)
are not managed by the USART Transmit Process to avoid the overrun interrupt
when the usart mode is configured for transmit and receive "USART_MODE_TX_RX"
to benefit for the frame error and noise interrupts the usart mode should be
configured only for transmit "USART_MODE_TX" */
/* Configure Tx interrupt processing */
if (husart->FifoMode == USART_FIFOMODE_ENABLE)
{
/* Set the Tx ISR function pointer according to the data word length */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->TxISR = USART_TxISR_16BIT_FIFOEN;
}
else
{
husart->TxISR = USART_TxISR_8BIT_FIFOEN;
}
/* Process Unlocked */
__HAL_UNLOCK(husart);
/* Enable the TX FIFO threshold interrupt */
__HAL_USART_ENABLE_IT(husart, USART_IT_TXFT);
}
else
{
/* Set the Tx ISR function pointer according to the data word length */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->TxISR = USART_TxISR_16BIT;
}
else
{
husart->TxISR = USART_TxISR_8BIT;
}
/* Process Unlocked */
__HAL_UNLOCK(husart);
/* Enable the USART Transmit Data Register Empty Interrupt */
__HAL_USART_ENABLE_IT(husart, USART_IT_TXE);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in interrupt mode.
* @note To receive synchronous data, dummy data are simultaneously transmitted.
* @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the received data is handled as a set of u16. In this case, Size must indicate the number
* of u16 available through pRxData.
* @param husart USART handle.
* @param pRxData pointer to data buffer (u8 or u16 data elements).
* @param Size amount of data elements (u8 or u16) to be received.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size)
{
uint16_t nb_dummy_data;
if (husart->State == HAL_USART_STATE_READY)
{
if ((pRxData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(husart);
husart->pRxBuffPtr = pRxData;
husart->RxXferSize = Size;
husart->RxXferCount = Size;
husart->RxISR = NULL;
USART_MASK_COMPUTATION(husart);
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_RX;
/* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(husart->Instance->CR3, USART_CR3_EIE);
/* Configure Rx interrupt processing */
if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess))
{
/* Set the Rx ISR function pointer according to the data word length */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->RxISR = USART_RxISR_16BIT_FIFOEN;
}
else
{
husart->RxISR = USART_RxISR_8BIT_FIFOEN;
}
/* Process Unlocked */
__HAL_UNLOCK(husart);
/* Enable the USART Parity Error interrupt and RX FIFO Threshold interrupt */
if (husart->Init.Parity != USART_PARITY_NONE)
{
SET_BIT(husart->Instance->CR1, USART_CR1_PEIE);
}
SET_BIT(husart->Instance->CR3, USART_CR3_RXFTIE);
}
else
{
/* Set the Rx ISR function pointer according to the data word length */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->RxISR = USART_RxISR_16BIT;
}
else
{
husart->RxISR = USART_RxISR_8BIT;
}
/* Process Unlocked */
__HAL_UNLOCK(husart);
/* Enable the USART Parity Error and Data Register not empty Interrupts */
if (husart->Init.Parity != USART_PARITY_NONE)
{
SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE);
}
else
{
SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE);
}
}
if (husart->SlaveMode == USART_SLAVEMODE_DISABLE)
{
/* Send dummy data in order to generate the clock for the Slave to send the next data.
When FIFO mode is disabled only one data must be transferred.
When FIFO mode is enabled data must be transmitted until the RX FIFO reaches its threshold.
*/
if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess))
{
for (nb_dummy_data = husart->NbRxDataToProcess ; nb_dummy_data > 0U ; nb_dummy_data--)
{
husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF);
}
}
else
{
husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF);
}
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Full-Duplex Send and Receive an amount of data in interrupt mode.
* @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number
* of u16 available through pTxData and through pRxData.
* @param husart USART handle.
* @param pTxData pointer to TX data buffer (u8 or u16 data elements).
* @param pRxData pointer to RX data buffer (u8 or u16 data elements).
* @param Size amount of data elements (u8 or u16) to be sent (same amount to be received).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData,
uint16_t Size)
{
if (husart->State == HAL_USART_STATE_READY)
{
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(husart);
husart->pRxBuffPtr = pRxData;
husart->RxXferSize = Size;
husart->RxXferCount = Size;
husart->pTxBuffPtr = pTxData;
husart->TxXferSize = Size;
husart->TxXferCount = Size;
/* Computation of USART mask to apply to RDR register */
USART_MASK_COMPUTATION(husart);
husart->ErrorCode = HAL_USART_ERROR_NONE;
husart->State = HAL_USART_STATE_BUSY_TX_RX;
/* Configure TxRx interrupt processing */
if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess))
{
/* Set the Rx ISR function pointer according to the data word length */
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->TxISR = USART_TxISR_16BIT_FIFOEN;
husart->RxISR = USART_RxISR_16BIT_FIFOEN;
}
else
{
husart->TxISR = USART_TxISR_8BIT_FIFOEN;
husart->RxISR = USART_RxISR_8BIT_FIFOEN;
}
/* Process Locked */
__HAL_UNLOCK(husart);
/* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(husart->Instance->CR3, USART_CR3_EIE);
if (husart->Init.Parity != USART_PARITY_NONE)
{
/* Enable the USART Parity Error interrupt */
SET_BIT(husart->Instance->CR1, USART_CR1_PEIE);
}
/* Enable the TX and RX FIFO Threshold interrupts */
SET_BIT(husart->Instance->CR3, (USART_CR3_TXFTIE | USART_CR3_RXFTIE));
}
else
{
if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE))
{
husart->TxISR = USART_TxISR_16BIT;
husart->RxISR = USART_RxISR_16BIT;
}
else
{
husart->TxISR = USART_TxISR_8BIT;
husart->RxISR = USART_RxISR_8BIT;
}
/* Process Locked */
__HAL_UNLOCK(husart);
/* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(husart->Instance->CR3, USART_CR3_EIE);
/* Enable the USART Parity Error and USART Data Register not empty Interrupts */
if (husart->Init.Parity != USART_PARITY_NONE)
{
SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE);
}
else
{
SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE);
}
/* Enable the USART Transmit Data Register Empty Interrupt */
SET_BIT(husart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @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;
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;
/* Enable the USART transmit DMA channel */
tmp = (const uint32_t *)&pTxData;
status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size);
}
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;
/* 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;
/* Enable the USART receive DMA channel */
status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t *)tmp, Size);
}
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;
status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size);
}
}
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)
{
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;
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;
/* Enable the USART receive DMA channel */
tmp = (uint32_t *)&pRxData;
status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(const uint32_t *)tmp, Size);
/* Enable the USART transmit DMA channel */
if (status == HAL_OK)
{
tmp = (const uint32_t *)&pTxData;
status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size);
}
}
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)
{
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))
{
/* Disable the USART DMA Tx request */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
else if ((state == HAL_USART_STATE_BUSY_RX) ||
(state == HAL_USART_STATE_BUSY_TX_RX))
{
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT))
{
/* Disable the USART DMA Tx request */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE);
/* Disable the USART DMA Rx request */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
}
}
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)
{
/* Enable the USART DMA Tx request */
SET_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
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);
/* Enable the USART DMA Rx request before the DMA Tx request */
SET_BIT(husart->Instance->CR3, USART_CR3_DMAR);
/* Enable the USART DMA Tx request */
SET_BIT(husart->Instance->CR3, USART_CR3_DMAT);
}
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))
{
/* Disable the USART DMA Tx request if enabled */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
/* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */
if (husart->hdmatx != NULL)
{
/* Set the USART DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
husart->hdmatx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK)
{
if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
husart->ErrorCode = HAL_USART_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* Abort the USART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
/* Disable the USART DMA Rx request if enabled */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
/* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */
if (husart->hdmarx != NULL)
{
/* Set the USART DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
husart->hdmarx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK)
{
if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
husart->ErrorCode = HAL_USART_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* 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))
{
/* Disable DMA Tx at USART level */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
/* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */
if (husart->hdmatx != NULL)
{
/* USART Tx DMA Abort callback has already been initialised :
will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(husart->hdmatx) != HAL_OK)
{
husart->hdmatx->XferAbortCallback = NULL;
}
else
{
abortcplt = 0U;
}
}
}
/* Abort the USART DMA Rx channel if enabled */
if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR))
{
/* Disable the USART DMA Rx request if enabled */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
/* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */
if (husart->hdmarx != NULL)
{
/* USART Rx DMA Abort callback has already been initialised :
will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK)
{
husart->hdmarx->XferAbortCallback = NULL;
abortcplt = 1U;
}
else
{
abortcplt = 0U;
}
}
}
/* 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))
{
/* Disable the USART DMA Rx request if enabled */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR | USART_CR3_DMAR);
/* Abort the USART DMA Tx channel */
if (husart->hdmatx != NULL)
{
/* Set the USART Tx DMA Abort callback to NULL : no callback
executed at end of DMA abort procedure */
husart->hdmatx->XferAbortCallback = NULL;
/* Abort DMA TX */
(void)HAL_DMA_Abort_IT(husart->hdmatx);
}
/* Abort the USART DMA Rx channel */
if (husart->hdmarx != NULL)
{
/* Set the USART Rx DMA Abort callback :
will lead to call HAL_USART_ErrorCallback() at end of DMA abort procedure */
husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK)
{
/* Call Directly husart->hdmarx->XferAbortCallback function in case of error */
husart->hdmarx->XferAbortCallback(husart->hdmarx);
}
}
else
{
/* Call user error callback */
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Error Callback */
husart->ErrorCallback(husart);
#else
/* Call legacy weak Error Callback */
HAL_USART_ErrorCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
}
else
{
/* 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);
/* DMA Normal mode */
if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC))
{
husart->TxXferCount = 0U;
if (husart->State == HAL_USART_STATE_BUSY_TX)
{
/* Disable the DMA transfer for transmit request by resetting the DMAT bit
in the USART CR3 register */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
/* Enable the USART Transmit Complete Interrupt */
__HAL_USART_ENABLE_IT(husart, USART_IT_TC);
}
}
/* DMA Circular mode */
else
{
if (husart->State == HAL_USART_STATE_BUSY_TX)
{
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Tx Complete Callback */
husart->TxCpltCallback(husart);
#else
/* Call legacy weak Tx Complete Callback */
HAL_USART_TxCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
}
}
/**
* @brief DMA USART transmit process half complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Tx Half Complete Callback */
husart->TxHalfCpltCallback(husart);
#else
/* Call legacy weak Tx Half Complete Callback */
HAL_USART_TxHalfCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @brief DMA USART receive process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
/* DMA Normal mode */
if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC))
{
husart->RxXferCount = 0U;
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE);
/* Disable the DMA RX transfer for the receiver request by resetting the DMAR bit
in USART CR3 register */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR);
/* similarly, disable the DMA TX transfer that was started to provide the
clock to the slave device */
CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT);
if (husart->State == HAL_USART_STATE_BUSY_RX)
{
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Rx Complete Callback */
husart->RxCpltCallback(husart);
#else
/* Call legacy weak Rx Complete Callback */
HAL_USART_RxCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/* The USART state is HAL_USART_STATE_BUSY_TX_RX */
else
{
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Tx Rx Complete Callback */
husart->TxRxCpltCallback(husart);
#else
/* Call legacy weak Tx Rx Complete Callback */
HAL_USART_TxRxCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
husart->State = HAL_USART_STATE_READY;
}
/* DMA circular mode */
else
{
if (husart->State == HAL_USART_STATE_BUSY_RX)
{
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Rx Complete Callback */
husart->RxCpltCallback(husart);
#else
/* Call legacy weak Rx Complete Callback */
HAL_USART_RxCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/* The USART state is HAL_USART_STATE_BUSY_TX_RX */
else
{
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Tx Rx Complete Callback */
husart->TxRxCpltCallback(husart);
#else
/* Call legacy weak Tx Rx Complete Callback */
HAL_USART_TxRxCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
}
}
/**
* @brief DMA USART receive process half complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Rx Half Complete Callback */
husart->RxHalfCpltCallback(husart);
#else
/* Call legacy weak Rx Half Complete Callback */
HAL_USART_RxHalfCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @brief DMA USART communication error callback.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMAError(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
husart->RxXferCount = 0U;
husart->TxXferCount = 0U;
USART_EndTransfer(husart);
husart->ErrorCode |= HAL_USART_ERROR_DMA;
husart->State = HAL_USART_STATE_READY;
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Error Callback */
husart->ErrorCallback(husart);
#else
/* Call legacy weak Error Callback */
HAL_USART_ErrorCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @brief DMA USART communication abort callback, when initiated by HAL services on Error
* (To be called at end of DMA Abort procedure following error occurrence).
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
husart->RxXferCount = 0U;
husart->TxXferCount = 0U;
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Error Callback */
husart->ErrorCallback(husart);
#else
/* Call legacy weak Error Callback */
HAL_USART_ErrorCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @brief DMA USART Tx communication abort callback, when initiated by user
* (To be called at end of DMA Tx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Rx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
husart->hdmatx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if (husart->hdmarx != NULL)
{
if (husart->hdmarx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
husart->TxXferCount = 0U;
husart->RxXferCount = 0U;
/* Reset errorCode */
husart->ErrorCode = HAL_USART_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF);
/* Restore husart->State to Ready */
husart->State = HAL_USART_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Abort Complete Callback */
husart->AbortCpltCallback(husart);
#else
/* Call legacy weak Abort Complete Callback */
HAL_USART_AbortCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @brief DMA USART Rx communication abort callback, when initiated by user
* (To be called at end of DMA Rx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Tx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma)
{
USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent);
husart->hdmarx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if (husart->hdmatx != NULL)
{
if (husart->hdmatx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
husart->TxXferCount = 0U;
husart->RxXferCount = 0U;
/* Reset errorCode */
husart->ErrorCode = HAL_USART_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF);
/* Restore husart->State to Ready */
husart->State = HAL_USART_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_USART_REGISTER_CALLBACKS == 1)
/* Call registered Abort Complete Callback */
husart->AbortCpltCallback(husart);
#else
/* Call legacy weak Abort Complete Callback */
HAL_USART_AbortCpltCallback(husart);
#endif /* USE_HAL_USART_REGISTER_CALLBACKS */
}
/**
* @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 */
/**
* @}
*/
/**
* @}
*/
| 125,294 |
C
| 32.781343 | 173 | 0.615297 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_opamp_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_opamp_ex.c
* @author MCD Application Team
* @brief Extended OPAMP HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the operational amplifiers peripheral:
* + Extended Initialization and de-initialization functions
* + Extended Peripheral Control functions
*
@verbatim
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_OPAMP_MODULE_ENABLED
/** @defgroup OPAMPEx OPAMPEx
* @brief OPAMP Extended HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup OPAMPEx_Exported_Functions OPAMP Extended Exported Functions
* @{
*/
/** @defgroup OPAMPEx_Exported_Functions_Group1 Extended Input and Output operation functions
* @brief Extended Self calibration functions
*
@verbatim
===============================================================================
##### Extended IO operation functions #####
===============================================================================
[..]
(+) OPAMP Self calibration.
@endverbatim
* @{
*/
/**
* @brief Run the self calibration of up to 6 OPAMPs in parallel.
* @note Calibration is performed in the mode specified in OPAMP init
* structure (mode normal or high-speed).
* @param hopamp1 handle
* @param hopamp2 handle
* @param hopamp3 handle
* @param hopamp4 handle (1)
* @param hopamp5 handle (1)
* @param hopamp6 handle (1)
* (1) Parameter not present on STM32GBK1CB/STM32G431xx/STM32G441xx/STM32G471xx devices.
* @retval HAL status
* @note Updated offset trimming values (PMOS & NMOS), user trimming is enabled
* @note Calibration runs about 25 ms.
*/
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G484xx)
HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2,
OPAMP_HandleTypeDef *hopamp3, OPAMP_HandleTypeDef *hopamp4, OPAMP_HandleTypeDef *hopamp5, OPAMP_HandleTypeDef *hopamp6)
#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx)
HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2,
OPAMP_HandleTypeDef *hopamp3)
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2,
OPAMP_HandleTypeDef *hopamp3, OPAMP_HandleTypeDef *hopamp6)
#endif
{
uint32_t trimmingvaluen1;
uint32_t trimmingvaluep1;
uint32_t trimmingvaluen2;
uint32_t trimmingvaluep2;
uint32_t trimmingvaluen3;
uint32_t trimmingvaluep3;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
uint32_t trimmingvaluen4;
uint32_t trimmingvaluep4;
uint32_t trimmingvaluen5;
uint32_t trimmingvaluep5;
uint32_t trimmingvaluen6;
uint32_t trimmingvaluep6;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
uint32_t trimmingvaluen6;
uint32_t trimmingvaluep6;
#endif
uint32_t delta;
if ((hopamp1 == NULL) || (hopamp2 == NULL) || (hopamp3 == NULL)
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
|| (hopamp4 == NULL) || (hopamp5 == NULL) || (hopamp6 == NULL)
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
|| (hopamp6 == NULL)
#endif
)
{
return HAL_ERROR;
}
else if (hopamp1->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
else if (hopamp2->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
else if (hopamp3->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
else if (hopamp4->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
else if (hopamp5->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
else if (hopamp6->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
else if (hopamp6->State != HAL_OPAMP_STATE_READY)
{
return HAL_ERROR;
}
#endif
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp1->Instance));
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp2->Instance));
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp3->Instance));
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp4->Instance));
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp5->Instance));
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp6->Instance));
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp6->Instance));
#endif
/* Set Calibration mode */
/* Non-inverting input connected to calibration reference voltage. */
SET_BIT(hopamp1->Instance->CSR, OPAMP_CSR_FORCEVP);
SET_BIT(hopamp2->Instance->CSR, OPAMP_CSR_FORCEVP);
SET_BIT(hopamp3->Instance->CSR, OPAMP_CSR_FORCEVP);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
SET_BIT(hopamp4->Instance->CSR, OPAMP_CSR_FORCEVP);
SET_BIT(hopamp5->Instance->CSR, OPAMP_CSR_FORCEVP);
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_FORCEVP);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_FORCEVP);
#endif
/* user trimming values are used for offset calibration */
SET_BIT(hopamp1->Instance->CSR, OPAMP_CSR_USERTRIM);
SET_BIT(hopamp2->Instance->CSR, OPAMP_CSR_USERTRIM);
SET_BIT(hopamp3->Instance->CSR, OPAMP_CSR_USERTRIM);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
SET_BIT(hopamp4->Instance->CSR, OPAMP_CSR_USERTRIM);
SET_BIT(hopamp5->Instance->CSR, OPAMP_CSR_USERTRIM);
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_USERTRIM);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_USERTRIM);
#endif
/* Enable calibration */
SET_BIT(hopamp1->Instance->CSR, OPAMP_CSR_CALON);
SET_BIT(hopamp2->Instance->CSR, OPAMP_CSR_CALON);
SET_BIT(hopamp3->Instance->CSR, OPAMP_CSR_CALON);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
SET_BIT(hopamp4->Instance->CSR, OPAMP_CSR_CALON);
SET_BIT(hopamp5->Instance->CSR, OPAMP_CSR_CALON);
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_CALON);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_CALON);
#endif
/* 1st calibration - N */
/* Select 90% VREF */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
#endif
/* Enable the opamps */
SET_BIT(hopamp1->Instance->CSR, OPAMP_CSR_OPAMPxEN);
SET_BIT(hopamp2->Instance->CSR, OPAMP_CSR_OPAMPxEN);
SET_BIT(hopamp3->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
SET_BIT(hopamp4->Instance->CSR, OPAMP_CSR_OPAMPxEN);
SET_BIT(hopamp5->Instance->CSR, OPAMP_CSR_OPAMPxEN);
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
SET_BIT(hopamp6->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#endif
/* Init trimming counter */
/* Medium value */
trimmingvaluen1 = 16UL;
trimmingvaluen2 = 16UL;
trimmingvaluen3 = 16UL;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
trimmingvaluen4 = 16UL;
trimmingvaluen5 = 16UL;
trimmingvaluen6 = 16UL;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
trimmingvaluen6 = 16UL;
#endif
delta = 8UL;
while (delta != 0UL)
{
/* Set candidate trimming */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen1 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen2 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen3 << OPAMP_INPUT_INVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen4 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen5 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#endif
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp1->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen1 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen1 -= delta;
}
if ((hopamp2->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen2 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen2 -= delta;
}
if ((hopamp3->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen3 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen3 -= delta;
}
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
if ((hopamp4->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen4 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen4 -= delta;
}
if ((hopamp5->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen5 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen5 -= delta;
}
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen6 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen6 -= delta;
}
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen6 += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen6 -= delta;
}
#endif
delta >>= 1;
}
/* Still need to check if righ calibration is current value or un step below */
/* Indeed the first value that causes the OUTCAL bit to change from 1 to 0 */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen1 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen2 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen3 << OPAMP_INPUT_INVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen4 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen5 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#endif
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp1->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen1++;
/* Set right trimming */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen1 << OPAMP_INPUT_INVERTING);
}
if ((hopamp2->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen2++;
/* Set right trimming */
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen2 << OPAMP_INPUT_INVERTING);
}
if ((hopamp3->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen3++;
/* Set right trimming */
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen3 << OPAMP_INPUT_INVERTING);
}
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
if ((hopamp4->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen4++;
/* Set right trimming */
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen4 << OPAMP_INPUT_INVERTING);
}
if ((hopamp5->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen5++;
/* Set right trimming */
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen5 << OPAMP_INPUT_INVERTING);
}
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen6++;
/* Set right trimming */
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
}
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen6++;
/* Set right trimming */
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
}
#endif
/* 2nd calibration - P */
/* Select 10% VREF */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
#endif
/* Init trimming counter */
/* Medium value */
trimmingvaluep1 = 16UL;
trimmingvaluep2 = 16UL;
trimmingvaluep3 = 16UL;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
trimmingvaluep4 = 16UL;
trimmingvaluep5 = 16UL;
trimmingvaluep6 = 16UL;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
trimmingvaluep6 = 16UL;
#endif
delta = 8UL;
while (delta != 0UL)
{
/* Set candidate trimming */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep1 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep2 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep3 << OPAMP_INPUT_NONINVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep4 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep5 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#endif
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp1->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep1 += delta;
}
else
{
trimmingvaluep1 -= delta;
}
if ((hopamp2->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep2 += delta;
}
else
{
trimmingvaluep2 -= delta;
}
if ((hopamp3->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep3 += delta;
}
else
{
trimmingvaluep3 -= delta;
}
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
if ((hopamp4->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep4 += delta;
}
else
{
trimmingvaluep4 -= delta;
}
if ((hopamp5->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep5 += delta;
}
else
{
trimmingvaluep5 -= delta;
}
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep6 += delta;
}
else
{
trimmingvaluep6 -= delta;
}
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep6 += delta;
}
else
{
trimmingvaluep6 -= delta;
}
#endif
delta >>= 1;
}
/* Still need to check if righ calibration is current value or un step below */
/* Indeed the first value that causes the OUTCAL bit to change from 1 to 0 */
/* Set candidate trimming */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep1 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep2 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep3 << OPAMP_INPUT_NONINVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep4 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep5 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#endif
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp1->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep1++;
/* Set right trimming */
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep1 << OPAMP_INPUT_NONINVERTING);
}
if ((hopamp2->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep2++;
/* Set right trimming */
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep2 << OPAMP_INPUT_NONINVERTING);
}
if ((hopamp3->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep3++;
/* Set right trimming */
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep3 << OPAMP_INPUT_NONINVERTING);
}
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
if ((hopamp4->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep4++;
/* Set right trimming */
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep4 << OPAMP_INPUT_NONINVERTING);
}
if ((hopamp5->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep5++;
/* Set right trimming */
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep5 << OPAMP_INPUT_NONINVERTING);
}
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep6++;
/* Set right trimming */
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
}
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
if ((hopamp6->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* Trimming value is actually one value more */
trimmingvaluep6++;
/* Set right trimming */
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
}
#endif
/* Disable calibration */
CLEAR_BIT(hopamp1->Instance->CSR, OPAMP_CSR_CALON);
CLEAR_BIT(hopamp2->Instance->CSR, OPAMP_CSR_CALON);
CLEAR_BIT(hopamp3->Instance->CSR, OPAMP_CSR_CALON);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
CLEAR_BIT(hopamp4->Instance->CSR, OPAMP_CSR_CALON);
CLEAR_BIT(hopamp5->Instance->CSR, OPAMP_CSR_CALON);
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_CALON);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_CALON);
#endif
/* Disable the OPAMPs */
CLEAR_BIT(hopamp1->Instance->CSR, OPAMP_CSR_OPAMPxEN);
CLEAR_BIT(hopamp2->Instance->CSR, OPAMP_CSR_OPAMPxEN);
CLEAR_BIT(hopamp3->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
CLEAR_BIT(hopamp4->Instance->CSR, OPAMP_CSR_OPAMPxEN);
CLEAR_BIT(hopamp5->Instance->CSR, OPAMP_CSR_OPAMPxEN);
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_OPAMPxEN);
#endif
/* Set normal operating mode back */
CLEAR_BIT(hopamp1->Instance->CSR, OPAMP_CSR_FORCEVP);
CLEAR_BIT(hopamp2->Instance->CSR, OPAMP_CSR_FORCEVP);
CLEAR_BIT(hopamp3->Instance->CSR, OPAMP_CSR_FORCEVP);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
CLEAR_BIT(hopamp4->Instance->CSR, OPAMP_CSR_FORCEVP);
CLEAR_BIT(hopamp5->Instance->CSR, OPAMP_CSR_FORCEVP);
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_FORCEVP);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
CLEAR_BIT(hopamp6->Instance->CSR, OPAMP_CSR_FORCEVP);
#endif
/* Self calibration is successful */
/* Store calibration(user timing) results in init structure. */
/* Select user timing mode */
/* Write calibration result N */
hopamp1->Init.TrimmingValueN = trimmingvaluen1;
hopamp2->Init.TrimmingValueN = trimmingvaluen2;
hopamp3->Init.TrimmingValueN = trimmingvaluen3;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
hopamp4->Init.TrimmingValueN = trimmingvaluen4;
hopamp5->Init.TrimmingValueN = trimmingvaluen5;
hopamp6->Init.TrimmingValueN = trimmingvaluen6;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
hopamp6->Init.TrimmingValueN = trimmingvaluen6;
#endif
/* Write calibration result P */
hopamp1->Init.TrimmingValueP = trimmingvaluep1;
hopamp2->Init.TrimmingValueP = trimmingvaluep2;
hopamp3->Init.TrimmingValueP = trimmingvaluep3;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
hopamp4->Init.TrimmingValueP = trimmingvaluep4;
hopamp5->Init.TrimmingValueP = trimmingvaluep5;
hopamp6->Init.TrimmingValueP = trimmingvaluep6;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
hopamp6->Init.TrimmingValueP = trimmingvaluep6;
#endif
/* Select user timing mode */
/* And updated with calibrated settings */
hopamp1->Init.UserTrimming = OPAMP_TRIMMING_USER;
hopamp2->Init.UserTrimming = OPAMP_TRIMMING_USER;
hopamp3->Init.UserTrimming = OPAMP_TRIMMING_USER;
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
hopamp4->Init.UserTrimming = OPAMP_TRIMMING_USER;
hopamp5->Init.UserTrimming = OPAMP_TRIMMING_USER;
hopamp6->Init.UserTrimming = OPAMP_TRIMMING_USER;
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
hopamp6->Init.UserTrimming = OPAMP_TRIMMING_USER;
#endif
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen1 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen2 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen3 << OPAMP_INPUT_INVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen4 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen5 << OPAMP_INPUT_INVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen6 << OPAMP_INPUT_INVERTING);
#endif
MODIFY_REG(hopamp1->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep1 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp2->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep2 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp3->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep3 << OPAMP_INPUT_NONINVERTING);
#if defined(STM32G473xx) || defined(STM32G474xx) || defined(STM32G483xx) || defined(STM32G483xx)
MODIFY_REG(hopamp4->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep4 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp5->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep5 << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
MODIFY_REG(hopamp6->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep6 << OPAMP_INPUT_NONINVERTING);
#endif
}
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_OPAMP_MODULE_ENABLED */
/**
* @}
*/
| 29,875 |
C
| 38.941176 | 166 | 0.659113 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_cordic.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_cordic.c
* @author MCD Application Team
* @brief CORDIC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the CORDIC peripheral:
* + Initialization and de-initialization functions
* + Peripheral Control functions
* + Callback functions
* + IRQ handler management
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 CORDIC HAL driver can be used as follows:
(#) Initialize the CORDIC low level resources by implementing the HAL_CORDIC_MspInit():
(++) Enable the CORDIC interface clock using __HAL_RCC_CORDIC_CLK_ENABLE()
(++) In case of using interrupts (e.g. HAL_CORDIC_Calculate_IT())
(+++) Configure the CORDIC interrupt priority using HAL_NVIC_SetPriority()
(+++) Enable the CORDIC IRQ handler using HAL_NVIC_EnableIRQ()
(+++) In CORDIC IRQ handler, call HAL_CORDIC_IRQHandler()
(++) In case of using DMA to control data transfer (e.g. HAL_CORDIC_Calculate_DMA())
(+++) Enable the DMA2 interface clock using
__HAL_RCC_DMA2_CLK_ENABLE()
(+++) Configure and enable two DMA channels one for managing data transfer from
memory to peripheral (input channel) and another channel for managing data
transfer from peripheral to memory (output channel)
(+++) Associate the initialized DMA handle to the CORDIC DMA handle
using __HAL_LINKDMA()
(+++) Configure the priority and enable the NVIC for the transfer complete
interrupt on the two DMA channels.
Resort to HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ()
(#) Initialize the CORDIC HAL using HAL_CORDIC_Init(). This function
(++) resorts to HAL_CORDIC_MspInit() for low-level initialization,
(#) Configure CORDIC processing (calculation) using HAL_CORDIC_Configure().
This function configures:
(++) Processing functions: Cosine, Sine, Phase, Modulus, Arctangent,
Hyperbolic cosine, Hyperbolic sine, Hyperbolic arctangent,
Natural log, Square root
(++) Scaling factor: 1 to 2exp(-7)
(++) Width of input data: 32 bits input data size (Q1.31 format) or 16 bits
input data size (Q1.15 format)
(++) Width of output data: 32 bits output data size (Q1.31 format) or 16 bits
output data size (Q1.15 format)
(++) Number of 32-bit write expected for one calculation: One 32-bits write
or Two 32-bit write
(++) Number of 32-bit read expected after one calculation: One 32-bits read
or Two 32-bit read
(++) Precision: 1 to 15 cycles for calculation (the more cycles, the better precision)
(#) Four processing (calculation) functions are available:
(++) Polling mode: processing API is blocking function
i.e. it processes the data and wait till the processing is finished
API is HAL_CORDIC_Calculate
(++) Polling Zero-overhead mode: processing API is blocking function
i.e. it processes the data and wait till the processing is finished
A bit faster than standard polling mode, but blocking also AHB bus
API is HAL_CORDIC_CalculateZO
(++) Interrupt mode: processing API is not blocking functions
i.e. it processes the data under interrupt
API is HAL_CORDIC_Calculate_IT
(++) DMA mode: processing API is not blocking functions and the CPU is
not used for data transfer,
i.e. the data transfer is ensured by DMA
API is HAL_CORDIC_Calculate_DMA
(#) Call HAL_CORDIC_DeInit() to de-initialize the CORDIC peripheral. This function
(++) resorts to HAL_CORDIC_MspDeInit() for low-level de-initialization,
*** Callback registration ***
=============================================
The compilation define USE_HAL_CORDIC_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Function HAL_CORDIC_RegisterCallback() to register an interrupt callback.
Function HAL_CORDIC_RegisterCallback() allows to register following callbacks:
(+) ErrorCallback : Error Callback.
(+) CalculateCpltCallback : Calculate complete Callback.
(+) MspInitCallback : CORDIC MspInit.
(+) MspDeInitCallback : CORDIC MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
Use function HAL_CORDIC_UnRegisterCallback() to reset a callback to the default
weak function.
HAL_CORDIC_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) ErrorCallback : Error Callback.
(+) CalculateCpltCallback : Calculate complete Callback.
(+) MspInitCallback : CORDIC MspInit.
(+) MspDeInitCallback : CORDIC MspDeInit.
By default, after the HAL_CORDIC_Init() and when the state is HAL_CORDIC_STATE_RESET,
all callbacks are set to the corresponding weak functions:
examples HAL_CORDIC_ErrorCallback(), HAL_CORDIC_CalculateCpltCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak function in the HAL_CORDIC_Init()/ HAL_CORDIC_DeInit() only when
these callbacks are null (not registered beforehand).
if not, MspInit or MspDeInit are not null, the HAL_CORDIC_Init()/ HAL_CORDIC_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
Callbacks can be registered/unregistered in HAL_CORDIC_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_CORDIC_STATE_READY or HAL_CORDIC_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_CORDIC_RegisterCallback() before calling HAL_CORDIC_DeInit()
or HAL_CORDIC_Init() function.
When The compilation define USE_HAL_CORDIC_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 "stm32g4xx_hal.h"
#if defined(CORDIC)
#ifdef HAL_CORDIC_MODULE_ENABLED
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup CORDIC CORDIC
* @brief CORDIC HAL driver modules.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup CORDIC_Private_Functions CORDIC Private Functions
* @{
*/
static void CORDIC_WriteInDataIncrementPtr(CORDIC_HandleTypeDef *hcordic, int32_t **ppInBuff);
static void CORDIC_ReadOutDataIncrementPtr(CORDIC_HandleTypeDef *hcordic, int32_t **ppOutBuff);
static void CORDIC_DMAInCplt(DMA_HandleTypeDef *hdma);
static void CORDIC_DMAOutCplt(DMA_HandleTypeDef *hdma);
static void CORDIC_DMAError(DMA_HandleTypeDef *hdma);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup CORDIC_Exported_Functions CORDIC Exported Functions
* @{
*/
/** @defgroup CORDIC_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions.
*
@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Initialize the CORDIC peripheral and the associated handle
(+) DeInitialize the CORDIC peripheral
(+) Initialize the CORDIC MSP (MCU Specific Package)
(+) De-Initialize the CORDIC MSP
[..]
@endverbatim
* @{
*/
/**
* @brief Initialize the CORDIC peripheral and the associated handle.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_Init(CORDIC_HandleTypeDef *hcordic)
{
/* Check the CORDIC handle allocation */
if (hcordic == NULL)
{
/* Return error status */
return HAL_ERROR;
}
/* Check the instance */
assert_param(IS_CORDIC_ALL_INSTANCE(hcordic->Instance));
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
if (hcordic->State == HAL_CORDIC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcordic->Lock = HAL_UNLOCKED;
/* Reset callbacks to legacy functions */
hcordic->ErrorCallback = HAL_CORDIC_ErrorCallback; /* Legacy weak ErrorCallback */
hcordic->CalculateCpltCallback = HAL_CORDIC_CalculateCpltCallback; /* Legacy weak CalculateCpltCallback */
if (hcordic->MspInitCallback == NULL)
{
hcordic->MspInitCallback = HAL_CORDIC_MspInit; /* Legacy weak MspInit */
}
/* Initialize the low level hardware */
hcordic->MspInitCallback(hcordic);
}
#else
if (hcordic->State == HAL_CORDIC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcordic->Lock = HAL_UNLOCKED;
/* Initialize the low level hardware */
HAL_CORDIC_MspInit(hcordic);
}
#endif /* (USE_HAL_CORDIC_REGISTER_CALLBACKS) */
/* Set CORDIC error code to none */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Reset pInBuff and pOutBuff */
hcordic->pInBuff = NULL;
hcordic->pOutBuff = NULL;
/* Reset NbCalcToOrder and NbCalcToGet */
hcordic->NbCalcToOrder = 0U;
hcordic->NbCalcToGet = 0U;
/* Reset DMADirection */
hcordic->DMADirection = CORDIC_DMA_DIR_NONE;
/* Change CORDIC peripheral state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief DeInitialize the CORDIC peripheral.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_DeInit(CORDIC_HandleTypeDef *hcordic)
{
/* Check the CORDIC handle allocation */
if (hcordic == NULL)
{
/* Return error status */
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_CORDIC_ALL_INSTANCE(hcordic->Instance));
/* Change CORDIC peripheral state */
hcordic->State = HAL_CORDIC_STATE_BUSY;
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
if (hcordic->MspDeInitCallback == NULL)
{
hcordic->MspDeInitCallback = HAL_CORDIC_MspDeInit;
}
/* De-Initialize the low level hardware */
hcordic->MspDeInitCallback(hcordic);
#else
/* De-Initialize the low level hardware: CLOCK, NVIC, DMA */
HAL_CORDIC_MspDeInit(hcordic);
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
/* Set CORDIC error code to none */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Reset pInBuff and pOutBuff */
hcordic->pInBuff = NULL;
hcordic->pOutBuff = NULL;
/* Reset NbCalcToOrder and NbCalcToGet */
hcordic->NbCalcToOrder = 0U;
hcordic->NbCalcToGet = 0U;
/* Reset DMADirection */
hcordic->DMADirection = CORDIC_DMA_DIR_NONE;
/* Change CORDIC peripheral state */
hcordic->State = HAL_CORDIC_STATE_RESET;
/* Reset Lock */
hcordic->Lock = HAL_UNLOCKED;
/* Return function status */
return HAL_OK;
}
/**
* @brief Initialize the CORDIC MSP.
* @param hcordic CORDIC handle
* @retval None
*/
__weak void HAL_CORDIC_MspInit(CORDIC_HandleTypeDef *hcordic)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcordic);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_CORDIC_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the CORDIC MSP.
* @param hcordic CORDIC handle
* @retval None
*/
__weak void HAL_CORDIC_MspDeInit(CORDIC_HandleTypeDef *hcordic)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcordic);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_CORDIC_MspDeInit can be implemented in the user file
*/
}
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/**
* @brief Register a CORDIC CallBack.
* To be used instead of the weak predefined callback.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_CORDIC_ERROR_CB_ID error Callback ID
* @arg @ref HAL_CORDIC_CALCULATE_CPLT_CB_ID calculate complete Callback ID
* @arg @ref HAL_CORDIC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_CORDIC_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_RegisterCallback(CORDIC_HandleTypeDef *hcordic, HAL_CORDIC_CallbackIDTypeDef CallbackID,
void (* pCallback)(CORDIC_HandleTypeDef *_hcordic))
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
return HAL_ERROR;
}
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
switch (CallbackID)
{
case HAL_CORDIC_ERROR_CB_ID :
hcordic->ErrorCallback = pCallback;
break;
case HAL_CORDIC_CALCULATE_CPLT_CB_ID :
hcordic->CalculateCpltCallback = pCallback;
break;
case HAL_CORDIC_MSPINIT_CB_ID :
hcordic->MspInitCallback = pCallback;
break;
case HAL_CORDIC_MSPDEINIT_CB_ID :
hcordic->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hcordic->State == HAL_CORDIC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_CORDIC_MSPINIT_CB_ID :
hcordic->MspInitCallback = pCallback;
break;
case HAL_CORDIC_MSPDEINIT_CB_ID :
hcordic->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/**
* @brief Unregister a CORDIC CallBack.
* CORDIC callback is redirected to the weak predefined callback.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_CORDIC_ERROR_CB_ID error Callback ID
* @arg @ref HAL_CORDIC_CALCULATE_CPLT_CB_ID calculate complete Callback ID
* @arg @ref HAL_CORDIC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_CORDIC_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_UnRegisterCallback(CORDIC_HandleTypeDef *hcordic, HAL_CORDIC_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
switch (CallbackID)
{
case HAL_CORDIC_ERROR_CB_ID :
hcordic->ErrorCallback = HAL_CORDIC_ErrorCallback;
break;
case HAL_CORDIC_CALCULATE_CPLT_CB_ID :
hcordic->CalculateCpltCallback = HAL_CORDIC_CalculateCpltCallback;
break;
case HAL_CORDIC_MSPINIT_CB_ID :
hcordic->MspInitCallback = HAL_CORDIC_MspInit;
break;
case HAL_CORDIC_MSPDEINIT_CB_ID :
hcordic->MspDeInitCallback = HAL_CORDIC_MspDeInit;
break;
default :
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hcordic->State == HAL_CORDIC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_CORDIC_MSPINIT_CB_ID :
hcordic->MspInitCallback = HAL_CORDIC_MspInit;
break;
case HAL_CORDIC_MSPDEINIT_CB_ID :
hcordic->MspDeInitCallback = HAL_CORDIC_MspDeInit;
break;
default :
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup CORDIC_Exported_Functions_Group2 Peripheral Control functions
* @brief Control functions.
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Configure the CORDIC peripheral: function, precision, scaling factor,
number of input data and output data, size of input data and output data.
(+) Calculate output data of CORDIC processing on input date, using the
existing CORDIC configuration
[..] Four processing functions are available for calculation:
(+) Polling mode
(+) Polling mode, with Zero-Overhead register access
(+) Interrupt mode
(+) DMA mode
@endverbatim
* @{
*/
/**
* @brief Configure the CORDIC processing according to the specified
parameters in the CORDIC_ConfigTypeDef structure.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @param sConfig pointer to a CORDIC_ConfigTypeDef structure that
* contains the CORDIC configuration information.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_Configure(CORDIC_HandleTypeDef *hcordic, CORDIC_ConfigTypeDef *sConfig)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_CORDIC_FUNCTION(sConfig->Function));
assert_param(IS_CORDIC_PRECISION(sConfig->Precision));
assert_param(IS_CORDIC_SCALE(sConfig->Scale));
assert_param(IS_CORDIC_NBWRITE(sConfig->NbWrite));
assert_param(IS_CORDIC_NBREAD(sConfig->NbRead));
assert_param(IS_CORDIC_INSIZE(sConfig->InSize));
assert_param(IS_CORDIC_OUTSIZE(sConfig->OutSize));
/* Check handle state is ready */
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
/* Apply all configuration parameters in CORDIC control register */
MODIFY_REG(hcordic->Instance->CSR, \
(CORDIC_CSR_FUNC | CORDIC_CSR_PRECISION | CORDIC_CSR_SCALE | \
CORDIC_CSR_NARGS | CORDIC_CSR_NRES | CORDIC_CSR_ARGSIZE | CORDIC_CSR_RESSIZE), \
(sConfig->Function | sConfig->Precision | sConfig->Scale | \
sConfig->NbWrite | sConfig->NbRead | sConfig->InSize | sConfig->OutSize));
}
else
{
/* Set CORDIC error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_NOT_READY;
/* Return error status */
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Carry out data of CORDIC processing in polling mode,
* according to the existing CORDIC configuration.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param pInBuff Pointer to buffer containing input data for CORDIC processing.
* @param pOutBuff Pointer to buffer where output data of CORDIC processing will be stored.
* @param NbCalc Number of CORDIC calculation to process.
* @param Timeout Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_Calculate(CORDIC_HandleTypeDef *hcordic, int32_t *pInBuff, int32_t *pOutBuff,
uint32_t NbCalc, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t index;
int32_t *p_tmp_in_buff = pInBuff;
int32_t *p_tmp_out_buff = pOutBuff;
/* Check parameters setting */
if ((pInBuff == NULL) || (pOutBuff == NULL) || (NbCalc == 0U))
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
/* Check handle state is ready */
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
/* Reset CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Write of input data in Write Data register, and increment input buffer pointer */
CORDIC_WriteInDataIncrementPtr(hcordic, &p_tmp_in_buff);
/* Calculation is started.
Provide next set of input data, until number of calculation is achieved */
for (index = (NbCalc - 1U); index > 0U; index--)
{
/* Write of input data in Write Data register, and increment input buffer pointer */
CORDIC_WriteInDataIncrementPtr(hcordic, &p_tmp_in_buff);
/* Wait for RRDY flag to be raised */
do
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if ((HAL_GetTick() - tickstart) > Timeout)
{
/* Set CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_TIMEOUT;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Return function status */
return HAL_ERROR;
}
}
} while (HAL_IS_BIT_CLR(hcordic->Instance->CSR, CORDIC_CSR_RRDY));
/* Read output data from Read Data register, and increment output buffer pointer */
CORDIC_ReadOutDataIncrementPtr(hcordic, &p_tmp_out_buff);
}
/* Read output data from Read Data register, and increment output buffer pointer */
CORDIC_ReadOutDataIncrementPtr(hcordic, &p_tmp_out_buff);
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Return function status */
return HAL_OK;
}
else
{
/* Set CORDIC error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_NOT_READY;
/* Return function status */
return HAL_ERROR;
}
}
/**
* @brief Carry out data of CORDIC processing in Zero-Overhead mode (output data being read
* soon as input data are written), according to the existing CORDIC configuration.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param pInBuff Pointer to buffer containing input data for CORDIC processing.
* @param pOutBuff Pointer to buffer where output data of CORDIC processing will be stored.
* @param NbCalc Number of CORDIC calculation to process.
* @param Timeout Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_CalculateZO(CORDIC_HandleTypeDef *hcordic, int32_t *pInBuff, int32_t *pOutBuff,
uint32_t NbCalc, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t index;
int32_t *p_tmp_in_buff = pInBuff;
int32_t *p_tmp_out_buff = pOutBuff;
/* Check parameters setting */
if ((pInBuff == NULL) || (pOutBuff == NULL) || (NbCalc == 0U))
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
/* Check handle state is ready */
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
/* Reset CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Write of input data in Write Data register, and increment input buffer pointer */
CORDIC_WriteInDataIncrementPtr(hcordic, &p_tmp_in_buff);
/* Calculation is started.
Provide next set of input data, until number of calculation is achieved */
for (index = (NbCalc - 1U); index > 0U; index--)
{
/* Write of input data in Write Data register, and increment input buffer pointer */
CORDIC_WriteInDataIncrementPtr(hcordic, &p_tmp_in_buff);
/* Read output data from Read Data register, and increment output buffer pointer
The reading is performed in Zero-Overhead mode:
reading is ordered immediately without waiting result ready flag */
CORDIC_ReadOutDataIncrementPtr(hcordic, &p_tmp_out_buff);
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if ((HAL_GetTick() - tickstart) > Timeout)
{
/* Set CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_TIMEOUT;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Return function status */
return HAL_ERROR;
}
}
}
/* Read output data from Read Data register, and increment output buffer pointer
The reading is performed in Zero-Overhead mode:
reading is ordered immediately without waiting result ready flag */
CORDIC_ReadOutDataIncrementPtr(hcordic, &p_tmp_out_buff);
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Return function status */
return HAL_OK;
}
else
{
/* Set CORDIC error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_NOT_READY;
/* Return function status */
return HAL_ERROR;
}
}
/**
* @brief Carry out data of CORDIC processing in interrupt mode,
* according to the existing CORDIC configuration.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param pInBuff Pointer to buffer containing input data for CORDIC processing.
* @param pOutBuff Pointer to buffer where output data of CORDIC processing will be stored.
* @param NbCalc Number of CORDIC calculation to process.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_Calculate_IT(CORDIC_HandleTypeDef *hcordic, int32_t *pInBuff, int32_t *pOutBuff,
uint32_t NbCalc)
{
int32_t *tmp_pInBuff = pInBuff;
/* Check parameters setting */
if ((pInBuff == NULL) || (pOutBuff == NULL) || (NbCalc == 0U))
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
/* Check handle state is ready */
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
/* Reset CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_BUSY;
/* Store the buffers addresses and number of calculations in handle,
provisioning initial write of input data that will be done */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NARGS))
{
/* Two writes of input data are expected */
tmp_pInBuff++;
tmp_pInBuff++;
}
else
{
/* One write of input data is expected */
tmp_pInBuff++;
}
hcordic->pInBuff = tmp_pInBuff;
hcordic->pOutBuff = pOutBuff;
hcordic->NbCalcToOrder = NbCalc - 1U;
hcordic->NbCalcToGet = NbCalc;
/* Enable Result Ready Interrupt */
__HAL_CORDIC_ENABLE_IT(hcordic, CORDIC_IT_IEN);
/* Set back pointer to start of input data buffer */
tmp_pInBuff = pInBuff;
/* Initiate the processing by providing input data
in the Write Data register */
WRITE_REG(hcordic->Instance->WDATA, (uint32_t)*tmp_pInBuff);
/* Check if second write of input data is expected */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NARGS))
{
/* Increment pointer to input data */
tmp_pInBuff++;
/* Perform second write of input data */
WRITE_REG(hcordic->Instance->WDATA, (uint32_t)*tmp_pInBuff);
}
/* Return function status */
return HAL_OK;
}
else
{
/* Set CORDIC error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_NOT_READY;
/* Return function status */
return HAL_ERROR;
}
}
/**
* @brief Carry out input and/or output data of CORDIC processing in DMA mode,
* according to the existing CORDIC configuration.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param pInBuff Pointer to buffer containing input data for CORDIC processing.
* @param pOutBuff Pointer to buffer where output data of CORDIC processing will be stored.
* @param NbCalc Number of CORDIC calculation to process.
* @param DMADirection Direction of DMA transfers.
* This parameter can be one of the following values:
* @arg @ref CORDIC_DMA_Direction CORDIC DMA direction
* @note pInBuff or pOutBuff is unused in case of unique DMADirection transfer, and can
* be set to NULL value in this case.
* @note pInBuff and pOutBuff buffers must be 32-bit aligned to ensure a correct
* DMA transfer to and from the Peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CORDIC_Calculate_DMA(CORDIC_HandleTypeDef *hcordic, int32_t *pInBuff, int32_t *pOutBuff,
uint32_t NbCalc, uint32_t DMADirection)
{
uint32_t sizeinbuff;
uint32_t sizeoutbuff;
uint32_t inputaddr;
uint32_t outputaddr;
/* Check the parameters */
assert_param(IS_CORDIC_DMA_DIRECTION(DMADirection));
/* Check parameters setting */
if (NbCalc == 0U)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
/* Check if CORDIC DMA direction "Out" is requested */
if ((DMADirection == CORDIC_DMA_DIR_OUT) || (DMADirection == CORDIC_DMA_DIR_IN_OUT))
{
/* Check parameters setting */
if (pOutBuff == NULL)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
}
/* Check if CORDIC DMA direction "In" is requested */
if ((DMADirection == CORDIC_DMA_DIR_IN) || (DMADirection == CORDIC_DMA_DIR_IN_OUT))
{
/* Check parameters setting */
if (pInBuff == NULL)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_PARAM;
/* Return error status */
return HAL_ERROR;
}
}
if (hcordic->State == HAL_CORDIC_STATE_READY)
{
/* Reset CORDIC error code */
hcordic->ErrorCode = HAL_CORDIC_ERROR_NONE;
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_BUSY;
/* Get DMA direction */
hcordic->DMADirection = DMADirection;
/* Check if CORDIC DMA direction "Out" is requested */
if ((DMADirection == CORDIC_DMA_DIR_OUT) || (DMADirection == CORDIC_DMA_DIR_IN_OUT))
{
/* Set the CORDIC DMA transfer complete callback */
hcordic->hdmaOut->XferCpltCallback = CORDIC_DMAOutCplt;
/* Set the DMA error callback */
hcordic->hdmaOut->XferErrorCallback = CORDIC_DMAError;
/* Check number of output data at each calculation,
to retrieve the size of output data buffer */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NRES))
{
sizeoutbuff = 2U * NbCalc;
}
else
{
sizeoutbuff = NbCalc;
}
outputaddr = (uint32_t)pOutBuff;
/* Enable the DMA stream managing CORDIC output data read */
if (HAL_DMA_Start_IT(hcordic->hdmaOut, (uint32_t)&hcordic->Instance->RDATA, outputaddr, sizeoutbuff) != HAL_OK)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_DMA;
/* Return error status */
return HAL_ERROR;
}
/* Enable output data Read DMA requests */
SET_BIT(hcordic->Instance->CSR, CORDIC_DMA_REN);
}
/* Check if CORDIC DMA direction "In" is requested */
if ((DMADirection == CORDIC_DMA_DIR_IN) || (DMADirection == CORDIC_DMA_DIR_IN_OUT))
{
/* Set the CORDIC DMA transfer complete callback */
hcordic->hdmaIn->XferCpltCallback = CORDIC_DMAInCplt;
/* Set the DMA error callback */
hcordic->hdmaIn->XferErrorCallback = CORDIC_DMAError;
/* Check number of input data expected for each calculation,
to retrieve the size of input data buffer */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NARGS))
{
sizeinbuff = 2U * NbCalc;
}
else
{
sizeinbuff = NbCalc;
}
inputaddr = (uint32_t)pInBuff;
/* Enable the DMA stream managing CORDIC input data write */
if (HAL_DMA_Start_IT(hcordic->hdmaIn, inputaddr, (uint32_t)&hcordic->Instance->WDATA, sizeinbuff) != HAL_OK)
{
/* Update the error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_DMA;
/* Return error status */
return HAL_ERROR;
}
/* Enable input data Write DMA request */
SET_BIT(hcordic->Instance->CSR, CORDIC_DMA_WEN);
}
/* Return function status */
return HAL_OK;
}
else
{
/* Set CORDIC error code */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_NOT_READY;
/* Return function status */
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup CORDIC_Exported_Functions_Group3 Callback functions
* @brief Callback functions.
*
@verbatim
==============================================================================
##### Callback functions #####
==============================================================================
[..] This section provides Interruption and DMA callback functions:
(+) DMA or Interrupt calculate complete
(+) DMA or Interrupt error
@endverbatim
* @{
*/
/**
* @brief CORDIC error callback.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @retval None
*/
__weak void HAL_CORDIC_ErrorCallback(CORDIC_HandleTypeDef *hcordic)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcordic);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CORDIC_ErrorCallback can be implemented in the user file
*/
}
/**
* @brief CORDIC calculate complete callback.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @retval None
*/
__weak void HAL_CORDIC_CalculateCpltCallback(CORDIC_HandleTypeDef *hcordic)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcordic);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CORDIC_CalculateCpltCallback can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup CORDIC_Exported_Functions_Group4 IRQ handler management
* @brief IRQ handler.
*
@verbatim
==============================================================================
##### IRQ handler management #####
==============================================================================
[..] This section provides IRQ handler function.
@endverbatim
* @{
*/
/**
* @brief Handle CORDIC interrupt request.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @retval None
*/
void HAL_CORDIC_IRQHandler(CORDIC_HandleTypeDef *hcordic)
{
/* Check if calculation complete interrupt is enabled and if result ready
flag is raised */
if (__HAL_CORDIC_GET_IT_SOURCE(hcordic, CORDIC_IT_IEN) != 0U)
{
if (__HAL_CORDIC_GET_FLAG(hcordic, CORDIC_FLAG_RRDY) != 0U)
{
/* Decrement number of calculations to get */
hcordic->NbCalcToGet--;
/* Read output data from Read Data register, and increment output buffer pointer */
CORDIC_ReadOutDataIncrementPtr(hcordic, &(hcordic->pOutBuff));
/* Check if calculations are still to be ordered */
if (hcordic->NbCalcToOrder > 0U)
{
/* Decrement number of calculations to order */
hcordic->NbCalcToOrder--;
/* Continue the processing by providing another write of input data
in the Write Data register, and increment input buffer pointer */
CORDIC_WriteInDataIncrementPtr(hcordic, &(hcordic->pInBuff));
}
/* Check if all calculations results are got */
if (hcordic->NbCalcToGet == 0U)
{
/* Disable Result Ready Interrupt */
__HAL_CORDIC_DISABLE_IT(hcordic, CORDIC_IT_IEN);
/* Change the CORDIC state */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Call calculation complete callback */
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/*Call registered callback*/
hcordic->CalculateCpltCallback(hcordic);
#else
/*Call legacy weak (surcharged) callback*/
HAL_CORDIC_CalculateCpltCallback(hcordic);
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
}
}
}
}
/**
* @}
*/
/** @defgroup CORDIC_Exported_Functions_Group5 Peripheral State functions
* @brief Peripheral State functions.
*
@verbatim
==============================================================================
##### Peripheral State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Return the CORDIC handle state.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @retval HAL state
*/
HAL_CORDIC_StateTypeDef HAL_CORDIC_GetState(CORDIC_HandleTypeDef *hcordic)
{
/* Return CORDIC handle state */
return hcordic->State;
}
/**
* @brief Return the CORDIC peripheral error.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module
* @note The returned error is a bit-map combination of possible errors
* @retval Error bit-map
*/
uint32_t HAL_CORDIC_GetError(CORDIC_HandleTypeDef *hcordic)
{
/* Return CORDIC error code */
return hcordic->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup CORDIC_Private_Functions
* @{
*/
/**
* @brief Write input data for CORDIC processing, and increment input buffer pointer.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param ppInBuff Pointer to pointer to input buffer.
* @retval none
*/
static void CORDIC_WriteInDataIncrementPtr(CORDIC_HandleTypeDef *hcordic, int32_t **ppInBuff)
{
/* First write of input data in the Write Data register */
WRITE_REG(hcordic->Instance->WDATA, (uint32_t) **ppInBuff);
/* Increment input data pointer */
(*ppInBuff)++;
/* Check if second write of input data is expected */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NARGS))
{
/* Second write of input data in the Write Data register */
WRITE_REG(hcordic->Instance->WDATA, (uint32_t) **ppInBuff);
/* Increment input data pointer */
(*ppInBuff)++;
}
}
/**
* @brief Read output data of CORDIC processing, and increment output buffer pointer.
* @param hcordic pointer to a CORDIC_HandleTypeDef structure that contains
* the configuration information for CORDIC module.
* @param ppOutBuff Pointer to pointer to output buffer.
* @retval none
*/
static void CORDIC_ReadOutDataIncrementPtr(CORDIC_HandleTypeDef *hcordic, int32_t **ppOutBuff)
{
/* First read of output data from the Read Data register */
**ppOutBuff = (int32_t)READ_REG(hcordic->Instance->RDATA);
/* Increment output data pointer */
(*ppOutBuff)++;
/* Check if second read of output data is expected */
if (HAL_IS_BIT_SET(hcordic->Instance->CSR, CORDIC_CSR_NRES))
{
/* Second read of output data from the Read Data register */
**ppOutBuff = (int32_t)READ_REG(hcordic->Instance->RDATA);
/* Increment output data pointer */
(*ppOutBuff)++;
}
}
/**
* @brief DMA CORDIC Input Data process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void CORDIC_DMAInCplt(DMA_HandleTypeDef *hdma)
{
CORDIC_HandleTypeDef *hcordic = (CORDIC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable the DMA transfer for input request */
CLEAR_BIT(hcordic->Instance->CSR, CORDIC_DMA_WEN);
/* Check if DMA direction is CORDIC Input only (no DMA for CORDIC Output) */
if (hcordic->DMADirection == CORDIC_DMA_DIR_IN)
{
/* Change the CORDIC DMA direction to none */
hcordic->DMADirection = CORDIC_DMA_DIR_NONE;
/* Change the CORDIC state to ready */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Call calculation complete callback */
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/*Call registered callback*/
hcordic->CalculateCpltCallback(hcordic);
#else
/*Call legacy weak (surcharged) callback*/
HAL_CORDIC_CalculateCpltCallback(hcordic);
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
}
}
/**
* @brief DMA CORDIC Output Data process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void CORDIC_DMAOutCplt(DMA_HandleTypeDef *hdma)
{
CORDIC_HandleTypeDef *hcordic = (CORDIC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable the DMA transfer for output request */
CLEAR_BIT(hcordic->Instance->CSR, CORDIC_DMA_REN);
/* Change the CORDIC DMA direction to none */
hcordic->DMADirection = CORDIC_DMA_DIR_NONE;
/* Change the CORDIC state to ready */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Call calculation complete callback */
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/*Call registered callback*/
hcordic->CalculateCpltCallback(hcordic);
#else
/*Call legacy weak (surcharged) callback*/
HAL_CORDIC_CalculateCpltCallback(hcordic);
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
}
/**
* @brief DMA CORDIC communication error callback.
* @param hdma DMA handle.
* @retval None
*/
static void CORDIC_DMAError(DMA_HandleTypeDef *hdma)
{
CORDIC_HandleTypeDef *hcordic = (CORDIC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Set CORDIC handle state to error */
hcordic->State = HAL_CORDIC_STATE_READY;
/* Set CORDIC handle error code to DMA error */
hcordic->ErrorCode |= HAL_CORDIC_ERROR_DMA;
/* Call user callback */
#if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1
/*Call registered callback*/
hcordic->ErrorCallback(hcordic);
#else
/*Call legacy weak (surcharged) callback*/
HAL_CORDIC_ErrorCallback(hcordic);
#endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_CORDIC_MODULE_ENABLED */
#endif /* CORDIC */
| 45,120 |
C
| 32.324224 | 119 | 0.631516 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_fmc.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 --------------------------- */
#if defined(FMC_BANK1)
/* --- 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))
#endif /* FMC_BANK1 */
#if defined(FMC_BANK3)
/* --- 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))
#endif /* FMC_BANK3 */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup FMC_LL_Exported_Functions FMC Low Layer Exported Functions
* @{
*/
#if defined(FMC_BANK1)
/** @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;
}
/**
* @}
*/
/**
* @}
*/
#endif /* FMC_BANK1 */
#if defined(FMC_BANK3)
/** @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 /* FMC_BANK3 */
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_NOR_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 29,235 |
C
| 35.272953 | 115 | 0.574483 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_wwdg.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 170MHz (PCLK1) with zero prescaler:
max timeout before reset: approximately 24.09us
(++) Counter max (T[5;0] = 0x3F) at 170MHz (PCLK1) with prescaler
dividing by 128:
max timeout before reset: approximately 197.38ms
##### 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 */
/**
* @}
*/
/**
* @}
*/
| 15,309 |
C
| 35.365796 | 111 | 0.608466 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_pwr.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_pwr.c
* @author MCD Application Team
* @brief PWR LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_pwr.h"
#include "stm32g4xx_ll_bus.h"
/** @addtogroup STM32G4xx_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)
{
/* Force reset of PWR clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_PWR);
/* Release reset of PWR clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_PWR);
return SUCCESS;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(PWR) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 2,100 |
C
| 24.011904 | 80 | 0.429524 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_hrtim.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_hrtim.c
* @author MCD Application Team
* @brief TIM HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the High Resolution Timer (HRTIM) peripheral:
* + HRTIM Initialization
* + DLL Calibration Start
* + Timer Time Base Unit Configuration
* + Simple Time Base Start/Stop
* + Simple Time Base Start/Stop Interrupt
* + Simple Time Base Start/Stop DMA Request
* + Simple Output Compare/PWM Channel Configuration
* + Simple Output Compare/PWM Channel Start/Stop Interrupt
* + Simple Output Compare/PWM Channel Start/Stop DMA Request
* + Simple Input Capture Channel Configuration
* + Simple Input Capture Channel Start/Stop Interrupt
* + Simple Input Capture Channel Start/Stop DMA Request
* + Simple One Pulse Channel Configuration
* + Simple One Pulse Channel Start/Stop Interrupt
* + HRTIM External Synchronization Configuration
* + HRTIM Burst Mode Controller Configuration
* + HRTIM Burst Mode Controller Enabling
* + HRTIM External Events Conditioning Configuration
* + HRTIM Faults Conditioning Configuration
* + HRTIM Faults Enabling
* + HRTIM ADC trigger Configuration
* + Waveform Timer Configuration
* + Waveform Event Filtering Configuration
* + Waveform Dead Time Insertion Configuration
* + Waveform Chopper Mode Configuration
* + Waveform Compare Unit Configuration
* + Waveform Capture Unit Configuration
* + Waveform Output Configuration
* + Waveform Counter Start/Stop
* + Waveform Counter Start/Stop Interrupt
* + Waveform Counter Start/Stop DMA Request
* + Waveform Output Enabling
* + Waveform Output Level Set/Get
* + Waveform Output State Get
* + Waveform Burst DMA Operation Configuration
* + Waveform Burst DMA Operation Start
* + Waveform Timer Counter Software Reset
* + Waveform Capture Software Trigger
* + Waveform Burst Mode Controller Software Trigger
* + Waveform Timer Pre-loadable Registers Update Enabling
* + Waveform Timer Pre-loadable Registers Software Update
* + Waveform Timer Delayed Protection Status Get
* + Waveform Timer Burst Status Get
* + Waveform Timer Push-Pull Status Get
* + Peripheral State Get
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
==============================================================================
##### Simple mode v.s. waveform mode #####
==============================================================================
[..] The HRTIM HAL API is split into 2 categories:
(#)Simple functions: these functions allow for using a HRTIM timer as a
general purpose timer with high resolution capabilities.
HRTIM simple modes are managed through the set of functions named
HAL_HRTIM_Simple<Function>. These functions are similar in name and usage
to the one defined for the TIM peripheral. When a HRTIM timer operates in
simple mode, only a very limited set of HRTIM features are used.
Following simple modes are proposed:
(++)Output compare mode,
(++)PWM output mode,
(++)Input capture mode,
(++)One pulse mode.
(#)Waveform functions: These functions allow taking advantage of the HRTIM
flexibility to produce numerous types of control signal. When a HRTIM timer
operates in waveform mode, all the HRTIM features are accessible without
any restriction. HRTIM waveform modes are managed through the set of
functions named HAL_HRTIM_Waveform<Function>
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
(#)Initialize the HRTIM low level resources by implementing the
HAL_HRTIM_MspInit() function:
(##)Enable the HRTIM clock source using __HRTIMx_CLK_ENABLE()
(##)Connect HRTIM pins to MCU I/Os
(+++) Enable the clock for the HRTIM GPIOs using the following
function: __HAL_RCC_GPIOx_CLK_ENABLE()
(+++) Configure these GPIO pins in Alternate Function mode using
HAL_GPIO_Init()
(##)When using DMA to control data transfer (e.g HAL_HRTIM_SimpleBaseStart_DMA())
(+++)Enable the DMAx interface clock using __DMAx_CLK_ENABLE()
(+++)Initialize the DMA handle
(+++)Associate the initialized DMA handle to the appropriate DMA
handle of the HRTIM handle using __HAL_LINKDMA()
(+++)Initialize the DMA channel using HAL_DMA_Init()
(+++)Configure the priority and enable the NVIC for the transfer
complete interrupt on the DMA channel using HAL_NVIC_SetPriority()
and HAL_NVIC_EnableIRQ()
(##)In case of using interrupt mode (e.g HAL_HRTIM_SimpleBaseStart_IT())
(+++)Configure the priority and enable the NVIC for the concerned
HRTIM interrupt using HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ()
(#)Initialize the HRTIM HAL using HAL_HRTIM_Init(). The HRTIM configuration
structure (field of the HRTIM handle) specifies which global interrupt of
whole HRTIM must be enabled (Burst mode period, System fault, Faults).
It also contains the HRTIM external synchronization configuration. HRTIM
can act as a master (generating a synchronization signal) or as a slave
(waiting for a trigger to be synchronized).
(#)Start the high resolution unit using HAL_HRTIM_DLLCalibrationStart(). DLL
calibration is executed periodically and compensate for potential voltage
and temperature drifts. DLL calibration period is specified by the
CalibrationRate argument.
(#)HRTIM timers cannot be used until the high resolution unit is ready. This
can be checked using HAL_HRTIM_PollForDLLCalibration(): this function returns
HAL_OK if DLL calibration is completed or HAL_TIMEOUT if the DLL calibration
is still going on when timeout given as argument expires. DLL calibration
can also be started in interrupt mode using HAL_HRTIM_DLLCalibrationStart_IT().
In that case an interrupt is generated when the DLL calibration is completed.
Note that as DLL calibration is executed on a periodic basis an interrupt
will be generated at the end of every DLL calibration operation
(worst case: one interrupt every 14 micro seconds !).
(#) Configure HRTIM resources shared by all HRTIM timers
(##)Burst Mode Controller:
(+++)HAL_HRTIM_BurstModeConfig(): configures the HRTIM burst mode
controller: operating mode (continuous or one-shot mode), clock
(source, prescaler) , trigger(s), period, idle duration.
(##)External Events Conditioning:
(+++)HAL_HRTIM_EventConfig(): configures the conditioning of an
external event channel: source, polarity, edge-sensitivity.
External event can be used as triggers (timer reset, input
capture, burst mode, ADC triggers, delayed protection)
They can also be used to set or reset timer outputs. Up to
10 event channels are available.
(+++)HAL_HRTIM_EventPrescalerConfig(): configures the external
event sampling clock (used for digital filtering).
(##)Fault Conditioning:
(+++)HAL_HRTIM_FaultConfig(): configures the conditioning of a
fault channel: source, polarity, edge-sensitivity. Fault
channels are used to disable the outputs in case of an
abnormal operation. Up to 6 fault channels are available.
(+++)HAL_HRTIM_FaultPrescalerConfig(): configures the fault
sampling clock (used for digital filtering).
(+++)HAL_HRTIM_FaultModeCtl(): Enables or disables fault input(s)
circuitry. By default all fault inputs are disabled.
(##)ADC trigger:
(+++)HAL_HRTIM_ADCTriggerConfig(): configures the source triggering
the update of the ADC trigger register and the ADC trigger.
4 independent triggers are available to start both the regular
and the injected sequencers of the 2 ADCs
(#) Configure HRTIM timer time base using HAL_HRTIM_TimeBaseConfig(). This
function must be called whatever the HRTIM timer operating mode is
(simple v.s. waveform). It configures mainly:
(##)The HRTIM timer counter operating mode (continuous v.s. one shot)
(##)The HRTIM timer clock prescaler
(##)The HRTIM timer period
(##)The HRTIM timer repetition counter
*** If the HRTIM timer operates in simple mode ***
===================================================
[..]
(#) Start or Stop simple timers
(++)Simple time base: HAL_HRTIM_SimpleBaseStart(),HAL_HRTIM_SimpleBaseStop(),
HAL_HRTIM_SimpleBaseStart_IT(),HAL_HRTIM_SimpleBaseStop_IT(),
HAL_HRTIM_SimpleBaseStart_DMA(),HAL_HRTIM_SimpleBaseStop_DMA().
(++)Simple output compare: HAL_HRTIM_SimpleOCChannelConfig(),
HAL_HRTIM_SimpleOCStart(),HAL_HRTIM_SimpleOCStop(),
HAL_HRTIM_SimpleOCStart_IT(),HAL_HRTIM_SimpleOCStop_IT(),
HAL_HRTIM_SimpleOCStart_DMA(),HAL_HRTIM_SimpleOCStop_DMA(),
(++)Simple PWM output: HAL_HRTIM_SimplePWMChannelConfig(),
HAL_HRTIM_SimplePWMStart(),HAL_HRTIM_SimplePWMStop(),
HAL_HRTIM_SimplePWMStart_IT(),HAL_HRTIM_SimplePWMStop_IT(),
HAL_HRTIM_SimplePWMStart_DMA(),HAL_HRTIM_SimplePWMStop_DMA(),
(++)Simple input capture: HAL_HRTIM_SimpleCaptureChannelConfig(),
HAL_HRTIM_SimpleCaptureStart(),HAL_HRTIM_SimpleCaptureStop(),
HAL_HRTIM_SimpleCaptureStart_IT(),HAL_HRTIM_SimpleCaptureStop_IT(),
HAL_HRTIM_SimpleCaptureStart_DMA(),HAL_HRTIM_SimpleCaptureStop_DMA().
(++)Simple one pulse: HAL_HRTIM_SimpleOnePulseChannelConfig(),
HAL_HRTIM_SimpleOnePulseStart(),HAL_HRTIM_SimpleOnePulseStop(),
HAL_HRTIM_SimpleOnePulseStart_IT(),HAL_HRTIM_SimpleOnePulseStop_It().
*** If the HRTIM timer operates in waveform mode ***
====================================================
[..]
(#) Completes waveform timer configuration
(++)HAL_HRTIM_WaveformTimerConfig(): configuration of a HRTIM timer
operating in wave form mode mainly consists in:
(+++)Enabling the HRTIM timer interrupts and DMA requests.
(+++)Enabling the half mode for the HRTIM timer.
(+++)Defining how the HRTIM timer reacts to external synchronization input.
(+++)Enabling the push-pull mode for the HRTIM timer.
(+++)Enabling the fault channels for the HRTIM timer.
(+++)Enabling the dead-time insertion for the HRTIM timer.
(+++)Setting the delayed protection mode for the HRTIM timer (source and outputs
on which the delayed protection are applied).
(+++)Specifying the HRTIM timer update and reset triggers.
(+++)Specifying the HRTIM timer registers update policy (e.g. pre-load enabling).
(++)HAL_HRTIM_TimerEventFilteringConfig(): configures external
event blanking and windowing circuitry of a HRTIM timer:
(+++)Blanking: to mask external events during a defined time period a defined time period
(+++)Windowing, to enable external events only during a defined time period
(++)HAL_HRTIM_DeadTimeConfig(): configures the dead-time insertion
unit for a HRTIM timer. Allows to generate a couple of
complementary signals from a single reference waveform,
with programmable delays between active state.
(++)HAL_HRTIM_ChopperModeConfig(): configures the parameters of
the high-frequency carrier signal added on top of the timing
unit output. Chopper mode can be enabled or disabled for each
timer output separately (see HAL_HRTIM_WaveformOutputConfig()).
(++)HAL_HRTIM_BurstDMAConfig(): configures the burst DMA burst
controller. Allows having multiple HRTIM registers updated
with a single DMA request. The burst DMA operation is started
by calling HAL_HRTIM_BurstDMATransfer().
(++)HAL_HRTIM_WaveformCompareConfig():configures the compare unit
of a HRTIM timer. This operation consists in setting the
compare value and possibly specifying the auto delayed mode
for compare units 2 and 4 (allows to have compare events
generated relatively to capture events). Note that when auto
delayed mode is needed, the capture unit associated to the
compare unit must be configured separately.
(++)HAL_HRTIM_WaveformCaptureConfig(): configures the capture unit
of a HRTIM timer. This operation consists in specifying the
source(s) triggering the capture (timer register update event,
external event, timer output set/reset event, other HRTIM
timer related events).
(++)HAL_HRTIM_WaveformOutputConfig(): configuration of a HRTIM timer
output mainly consists in:
(+++)Setting the output polarity (active high or active low),
(+++)Defining the set/reset crossbar for the output,
(+++)Specifying the fault level (active or inactive) in IDLE and FAULT states.,
(#) Set waveform timer output(s) level
(++)HAL_HRTIM_WaveformSetOutputLevel(): forces the output to its
active or inactive level. For example, when deadtime insertion
is enabled it is necessary to force the output level by software
to have the outputs in a complementary state as soon as the RUN mode is entered.
(#) Enable or Disable waveform timer output(s)
(++)HAL_HRTIM_WaveformOutputStart(),HAL_HRTIM_WaveformOutputStop().
(#) Start or Stop waveform HRTIM timer(s).
(++)HAL_HRTIM_WaveformCountStart(),HAL_HRTIM_WaveformCountStop(),
(++)HAL_HRTIM_WaveformCountStart_IT(),HAL_HRTIM_WaveformCountStop_IT(),
(++)HAL_HRTIM_WaveformCountStart_DMA(),HAL_HRTIM_WaveformCountStop_DMA(),
(#) Burst mode controller enabling:
(++)HAL_HRTIM_BurstModeCtl(): activates or de-activates the
burst mode controller.
(#) Some HRTIM operations can be triggered by software:
(++)HAL_HRTIM_BurstModeSoftwareTrigger(): calling this function
trigs the burst operation.
(++)HAL_HRTIM_SoftwareCapture(): calling this function trigs the
capture of the HRTIM timer counter.
(++)HAL_HRTIM_SoftwareUpdate(): calling this function trigs the
update of the pre-loadable registers of the HRTIM timer
(++)HAL_HRTIM_SoftwareReset():calling this function resets the
HRTIM timer counter.
(#) Some functions can be used any time to retrieve HRTIM timer related
information
(++)HAL_HRTIM_GetCapturedValue(): returns actual value of the
capture register of the designated capture unit.
(++)HAL_HRTIM_WaveformGetOutputLevel(): returns actual level
(ACTIVE/INACTIVE) of the designated timer output.
(++)HAL_HRTIM_WaveformGetOutputState():returns actual state
(IDLE/RUN/FAULT) of the designated timer output.
(++)HAL_HRTIM_GetDelayedProtectionStatus():returns actual level
(ACTIVE/INACTIVE) of the designated output when the delayed
protection was triggered.
(++)HAL_HRTIM_GetBurstStatus(): returns the actual status
(ACTIVE/INACTIVE) of the burst mode controller.
(++)HAL_HRTIM_GetCurrentPushPullStatus(): when the push-pull mode
is enabled for the HRTIM timer (see HAL_HRTIM_WaveformTimerConfig()),
the push-pull status indicates on which output the signal is currently
active (e.g signal applied on output 1 and output 2 forced
inactive or vice versa).
(++)HAL_HRTIM_GetIdlePushPullStatus(): when the push-pull mode
is enabled for the HRTIM timer (see HAL_HRTIM_WaveformTimerConfig()),
the idle push-pull status indicates during which period the
delayed protection request occurred (e.g. protection occurred
when the output 1 was active and output 2 forced inactive or
vice versa).
(#) Some functions can be used any time to retrieve actual HRTIM status
(++)HAL_HRTIM_GetState(): returns actual HRTIM instance HAL state.
*** Callback registration ***
=============================
[..]
The compilation flag USE_HAL_HRTIM_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_HRTIM_RegisterCallback() or HAL_HRTIM_TIMxRegisterCallback()
to register an interrupt callback.
[..]
Function HAL_HRTIM_RegisterCallback() allows to register following callbacks:
(+) Fault1Callback : Fault 1 interrupt callback function
(+) Fault2Callback : Fault 2 interrupt callback function
(+) Fault3Callback : Fault 3 interrupt callback function
(+) Fault4Callback : Fault 4 interrupt callback function
(+) Fault5Callback : Fault 5 interrupt callback function
(+) Fault6Callback : Fault 6 interrupt callback function
(+) SystemFaultCallback : System fault interrupt callback function
(+) DLLCalibrationReadyCallback : DLL Ready interrupt callback function
(+) BurstModePeriodCallback : Burst mode period interrupt callback function
(+) SynchronizationEventCallback : Sync Input interrupt callback function
(+) ErrorCallback : DMA error callback function
(+) MspInitCallback : HRTIM MspInit callback function
(+) MspDeInitCallback : HRTIM MspInit callback function
[..]
Function HAL_HRTIM_TIMxRegisterCallback() allows to register following callbacks:
(+) RegistersUpdateCallback : Timer x Update interrupt callback function
(+) RepetitionEventCallback : Timer x Repetition interrupt callback function
(+) Compare1EventCallback : Timer x Compare 1 match interrupt callback function
(+) Compare2EventCallback : Timer x Compare 2 match interrupt callback function
(+) Compare3EventCallback : Timer x Compare 3 match interrupt callback function
(+) Compare4EventCallback : Timer x Compare 4 match interrupt callback function
(+) Capture1EventCallback : Timer x Capture 1 interrupts callback function
(+) Capture2EventCallback : Timer x Capture 2 interrupts callback function
(+) DelayedProtectionCallback : Timer x Delayed protection interrupt callback function
(+) CounterResetCallback : Timer x counter reset/roll-over interrupt callback function
(+) Output1SetCallback : Timer x output 1 set interrupt callback function
(+) Output1ResetCallback : Timer x output 1 reset interrupt callback function
(+) Output2SetCallback : Timer x output 2 set interrupt callback function
(+) Output2ResetCallback : Timer x output 2 reset interrupt callback function
(+) BurstDMATransferCallback : Timer x Burst DMA completed interrupt callback function
[..]
Both functions take as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_HRTIM_UnRegisterCallback or HAL_HRTIM_TIMxUnRegisterCallback
to reset a callback to the default weak function. Both functions take as parameters
the HAL peripheral handle and the Callback ID.
[..]
By default, after the HAL_HRTIM_Init() and when the state is HAL_HRTIM_STATE_RESET
all callbacks are set to the corresponding weak functions (e.g HAL_HRTIM_Fault1Callback)
Exception done for MspInit and MspDeInit functions that are reset to the legacy
weak functions in the HAL_HRTIM_Init()/ HAL_HRTIM_DeInit() only when these
callbacks are null (not registered beforehand). If MspInit or MspDeInit are
not null, the HAL_HRTIM_Init()/ HAL_HRTIM_DeInit() keep and use the user
MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in HAL_HRTIM_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in HAL_HRTIM_STATE_READY or HAL_HRTIM_STATE_RESET states, 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_HRTIM_RegisterCallback() before calling HAL_HRTIM_DeInit()
or HAL_HRTIM_Init() function.
[..]
When the compilation flag USE_HAL_HRTIM_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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_HRTIM_MODULE_ENABLED
#if defined(HRTIM1)
/** @defgroup HRTIM HRTIM
* @brief HRTIM HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup HRTIM_Private_Defines HRTIM Private Define
* @{
*/
#define HRTIM_FLTR_FLTxEN (HRTIM_FLTR_FLT1EN |\
HRTIM_FLTR_FLT2EN |\
HRTIM_FLTR_FLT3EN |\
HRTIM_FLTR_FLT4EN | \
HRTIM_FLTR_FLT5EN | \
HRTIM_FLTR_FLT6EN)
#define HRTIM_TIMCR_TIMUPDATETRIGGER (HRTIM_TIMUPDATETRIGGER_MASTER |\
HRTIM_TIMUPDATETRIGGER_TIMER_A |\
HRTIM_TIMUPDATETRIGGER_TIMER_B |\
HRTIM_TIMUPDATETRIGGER_TIMER_C |\
HRTIM_TIMUPDATETRIGGER_TIMER_D |\
HRTIM_TIMUPDATETRIGGER_TIMER_E |\
HRTIM_TIMUPDATETRIGGER_TIMER_F)
#define HRTIM_FLTINR1_FLTxLCK ((HRTIM_FAULTLOCK_READONLY) | \
(HRTIM_FAULTLOCK_READONLY << 8U) | \
(HRTIM_FAULTLOCK_READONLY << 16U) | \
(HRTIM_FAULTLOCK_READONLY << 24U))
#define HRTIM_FLTINR2_FLTxLCK ((HRTIM_FAULTLOCK_READONLY) | \
(HRTIM_FAULTLOCK_READONLY << 8U))
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup HRTIM_Private_Variables HRTIM Private Variables
* @{
*/
static uint32_t TimerIdxToTimerId[] =
{
HRTIM_TIMERID_TIMER_A,
HRTIM_TIMERID_TIMER_B,
HRTIM_TIMERID_TIMER_C,
HRTIM_TIMERID_TIMER_D,
HRTIM_TIMERID_TIMER_E,
HRTIM_TIMERID_TIMER_F,
HRTIM_TIMERID_MASTER,
};
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup HRTIM_Private_Functions HRTIM Private Functions
* @{
*/
static void HRTIM_MasterBase_Config(HRTIM_HandleTypeDef * hhrtim,
HRTIM_TimeBaseCfgTypeDef * pTimeBaseCfg);
static void HRTIM_TimingUnitBase_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimeBaseCfgTypeDef * pTimeBaseCfg);
static void HRTIM_MasterWaveform_Config(HRTIM_HandleTypeDef * hhrtim,
HRTIM_TimerCfgTypeDef * pTimerCfg);
static void HRTIM_TimingUnitWaveform_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCfgTypeDef * pTimerCfg);
static void HRTIM_TimingUnitWaveform_Control(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCtlTypeDef * pTimerCtl);
static void HRTIM_TimingUnitRollOver_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t pRollOverMode);
static void HRTIM_CaptureUnitConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit,
uint32_t Event);
static void HRTIM_OutputConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output,
HRTIM_OutputCfgTypeDef * pOutputCfg);
static void HRTIM_EventConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Event,
HRTIM_EventCfgTypeDef * pEventCfg);
static void HRTIM_TIM_ResetConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Event);
static uint32_t HRTIM_GetITFromOCMode(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel);
static uint32_t HRTIM_GetDMAFromOCMode(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel);
static DMA_HandleTypeDef * HRTIM_GetDMAHandleFromTimerIdx(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx);
static uint32_t GetTimerIdxFromDMAHandle(HRTIM_HandleTypeDef * hhrtim,
DMA_HandleTypeDef * hdma);
static void HRTIM_ForceRegistersUpdate(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx);
static void HRTIM_HRTIM_ISR(HRTIM_HandleTypeDef * hhrtim);
static void HRTIM_Master_ISR(HRTIM_HandleTypeDef * hhrtim);
static void HRTIM_Timer_ISR(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx);
static void HRTIM_DMAMasterCplt(DMA_HandleTypeDef *hdma);
static void HRTIM_DMATimerxCplt(DMA_HandleTypeDef *hdma);
static void HRTIM_DMAError(DMA_HandleTypeDef *hdma);
static void HRTIM_BurstDMACplt(DMA_HandleTypeDef *hdma);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup HRTIM_Exported_Functions HRTIM Exported Functions
* @{
*/
/** @defgroup HRTIM_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
@verbatim
===============================================================================
##### Initialization and Time Base Configuration functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize a HRTIM instance
(+) De-initialize a HRTIM instance
(+) Initialize the HRTIM MSP
(+) De-initialize the HRTIM MSP
(+) Start the high-resolution unit (start DLL calibration)
(+) Check that the high resolution unit is ready (DLL calibration done)
(+) Configure the time base unit of a HRTIM timer
@endverbatim
* @{
*/
/**
* @brief Initialize a HRTIM instance
* @param hhrtim pointer to HAL HRTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_Init(HRTIM_HandleTypeDef * hhrtim)
{
uint8_t timer_idx;
uint32_t hrtim_mcr;
/* Check the HRTIM handle allocation */
if(hhrtim == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_HRTIM_ALL_INSTANCE(hhrtim->Instance));
assert_param(IS_HRTIM_IT(hhrtim->Init.HRTIMInterruptResquests));
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
if (hhrtim->State == HAL_HRTIM_STATE_RESET)
{
/* Initialize callback function pointers to their default values */
hhrtim->Fault1Callback = HAL_HRTIM_Fault1Callback;
hhrtim->Fault2Callback = HAL_HRTIM_Fault2Callback;
hhrtim->Fault3Callback = HAL_HRTIM_Fault3Callback;
hhrtim->Fault4Callback = HAL_HRTIM_Fault4Callback;
hhrtim->Fault5Callback = HAL_HRTIM_Fault5Callback;
hhrtim->Fault6Callback = HAL_HRTIM_Fault6Callback;
hhrtim->SystemFaultCallback = HAL_HRTIM_SystemFaultCallback;
hhrtim->DLLCalibrationReadyCallback = HAL_HRTIM_DLLCalibrationReadyCallback;
hhrtim->BurstModePeriodCallback = HAL_HRTIM_BurstModePeriodCallback;
hhrtim->SynchronizationEventCallback = HAL_HRTIM_SynchronizationEventCallback;
hhrtim->ErrorCallback = HAL_HRTIM_ErrorCallback;
hhrtim->RegistersUpdateCallback = HAL_HRTIM_RegistersUpdateCallback;
hhrtim->RepetitionEventCallback = HAL_HRTIM_RepetitionEventCallback;
hhrtim->Compare1EventCallback = HAL_HRTIM_Compare1EventCallback;
hhrtim->Compare2EventCallback = HAL_HRTIM_Compare2EventCallback;
hhrtim->Compare3EventCallback = HAL_HRTIM_Compare3EventCallback;
hhrtim->Compare4EventCallback = HAL_HRTIM_Compare4EventCallback;
hhrtim->Capture1EventCallback = HAL_HRTIM_Capture1EventCallback;
hhrtim->Capture2EventCallback = HAL_HRTIM_Capture2EventCallback;
hhrtim->DelayedProtectionCallback = HAL_HRTIM_DelayedProtectionCallback;
hhrtim->CounterResetCallback = HAL_HRTIM_CounterResetCallback;
hhrtim->Output1SetCallback = HAL_HRTIM_Output1SetCallback;
hhrtim->Output1ResetCallback = HAL_HRTIM_Output1ResetCallback;
hhrtim->Output2SetCallback = HAL_HRTIM_Output2SetCallback;
hhrtim->Output2ResetCallback = HAL_HRTIM_Output2ResetCallback;
hhrtim->BurstDMATransferCallback = HAL_HRTIM_BurstDMATransferCallback;
if (hhrtim->MspInitCallback == NULL)
{
hhrtim->MspInitCallback = HAL_HRTIM_MspInit;
}
}
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
/* Set the HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Initialize the DMA handles */
hhrtim->hdmaMaster = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerA = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerB = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerC = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerD = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerE = (DMA_HandleTypeDef *)NULL;
hhrtim->hdmaTimerF = (DMA_HandleTypeDef *)NULL;
/* HRTIM output synchronization configuration (if required) */
if ((hhrtim->Init.SyncOptions & HRTIM_SYNCOPTION_MASTER) != (uint32_t)RESET)
{
/* Check parameters */
assert_param(IS_HRTIM_SYNCOUTPUTSOURCE(hhrtim->Init.SyncOutputSource));
assert_param(IS_HRTIM_SYNCOUTPUTPOLARITY(hhrtim->Init.SyncOutputPolarity));
/* The synchronization output initialization procedure must be done prior
to the configuration of the MCU outputs (done within HAL_HRTIM_MspInit)
*/
if (hhrtim->Instance == HRTIM1)
{
/* Enable the HRTIM peripheral clock */
__HAL_RCC_HRTIM1_CLK_ENABLE();
}
hrtim_mcr = hhrtim->Instance->sMasterRegs.MCR;
/* Set the event to be sent on the synchronization output */
hrtim_mcr &= ~(HRTIM_MCR_SYNC_SRC);
hrtim_mcr |= (hhrtim->Init.SyncOutputSource & HRTIM_MCR_SYNC_SRC);
/* Set the polarity of the synchronization output */
hrtim_mcr &= ~(HRTIM_MCR_SYNC_OUT);
hrtim_mcr |= (hhrtim->Init.SyncOutputPolarity & HRTIM_MCR_SYNC_OUT);
/* Update the HRTIM registers */
hhrtim->Instance->sMasterRegs.MCR = hrtim_mcr;
}
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->MspInitCallback(hhrtim);
#else
HAL_HRTIM_MspInit(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
/* HRTIM input synchronization configuration (if required) */
if ((hhrtim->Init.SyncOptions & HRTIM_SYNCOPTION_SLAVE) != (uint32_t)RESET)
{
/* Check parameters */
assert_param(IS_HRTIM_SYNCINPUTSOURCE(hhrtim->Init.SyncInputSource));
hrtim_mcr = hhrtim->Instance->sMasterRegs.MCR;
/* Set the synchronization input source */
hrtim_mcr &= ~(HRTIM_MCR_SYNC_IN);
hrtim_mcr |= (hhrtim->Init.SyncInputSource & HRTIM_MCR_SYNC_IN);
/* Update the HRTIM registers */
hhrtim->Instance->sMasterRegs.MCR = hrtim_mcr;
}
/* Initialize the HRTIM state*/
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Initialize the lock status of the HRTIM HAL API */
__HAL_UNLOCK(hhrtim);
/* Initialize timer related parameters */
for (timer_idx = HRTIM_TIMERINDEX_TIMER_A ;
timer_idx <= HRTIM_TIMERINDEX_MASTER ;
timer_idx++)
{
hhrtim->TimerParam[timer_idx].CaptureTrigger1 = HRTIM_CAPTURETRIGGER_NONE;
hhrtim->TimerParam[timer_idx].CaptureTrigger2 = HRTIM_CAPTURETRIGGER_NONE;
hhrtim->TimerParam[timer_idx].InterruptRequests = HRTIM_IT_NONE;
hhrtim->TimerParam[timer_idx].DMARequests = HRTIM_IT_NONE;
hhrtim->TimerParam[timer_idx].DMASrcAddress = 0U;
hhrtim->TimerParam[timer_idx].DMASize = 0U;
}
return HAL_OK;
}
/**
* @brief De-initialize a HRTIM instance
* @param hhrtim pointer to HAL HRTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_DeInit (HRTIM_HandleTypeDef * hhrtim)
{
/* Check the HRTIM handle allocation */
if(hhrtim == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_HRTIM_ALL_INSTANCE(hhrtim->Instance));
/* Set the HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* DeInit the low level hardware */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
if (hhrtim->MspDeInitCallback == NULL)
{
hhrtim->MspDeInitCallback = HAL_HRTIM_MspDeInit;
}
hhrtim->MspDeInitCallback(hhrtim);
#else
HAL_HRTIM_MspDeInit(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
hhrtim->State = HAL_HRTIM_STATE_READY;
return HAL_OK;
}
/**
* @brief MSP initialization for a HRTIM instance
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_MspInit(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_HRTIM_MspInit could be implemented in the user file
*/
}
/**
* @brief MSP de-initialization of a HRTIM instance
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_MspDeInit(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_HRTIM_MspDeInit could be implemented in the user file
*/
}
/**
* @brief Start the DLL calibration
* @param hhrtim pointer to HAL HRTIM handle
* @param CalibrationRate DLL calibration period
* This parameter can be one of the following values:
* @arg HRTIM_SINGLE_CALIBRATION: One shot DLL calibration
* @arg HRTIM_CALIBRATIONRATE_0: Periodic DLL calibration. T=6.168 ms
* @arg HRTIM_CALIBRATIONRATE_1: Periodic DLL calibration. T=0.771 ms
* @arg HRTIM_CALIBRATIONRATE_2: Periodic DLL calibration. T=0.096 ms
* @arg HRTIM_CALIBRATIONRATE_3: Periodic DLL calibration. T=0.012 ms
* @retval HAL status
* @note This function locks the HRTIM instance. HRTIM instance is unlocked
* within the HAL_HRTIM_PollForDLLCalibration function, just before
* exiting the function.
*/
HAL_StatusTypeDef HAL_HRTIM_DLLCalibrationStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t CalibrationRate)
{
/* Check the parameters */
assert_param(IS_HRTIM_CALIBRATIONRATE(CalibrationRate));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if (CalibrationRate == HRTIM_SINGLE_CALIBRATION)
{
/* One shot DLL calibration */
CLEAR_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALEN);
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CAL);
}
else
{
/* Periodic DLL calibration */
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALEN);
MODIFY_REG(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALRTE, CalibrationRate);
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CAL);
}
/* Set HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_READY;
return HAL_OK;
}
/**
* @brief Start the DLL calibration.
* DLL ready interrupt is enabled
* @param hhrtim pointer to HAL HRTIM handle
* @param CalibrationRate DLL calibration period
* This parameter can be one of the following values:
* @arg HRTIM_SINGLE_CALIBRATION: One shot DLL calibration
* @arg HRTIM_CALIBRATIONRATE_0: Periodic DLL calibration. T=6.168 ms
* @arg HRTIM_CALIBRATIONRATE_1: Periodic DLL calibration. T=0.771 ms
* @arg HRTIM_CALIBRATIONRATE_2: Periodic DLL calibration. T=0.096 ms
* @arg HRTIM_CALIBRATIONRATE_3: Periodic DLL calibration. T=0.012 ms
* @retval HAL status
* @note This function locks the HRTIM instance. HRTIM instance is unlocked
* within the IRQ processing function when processing the DLL ready
* interrupt.
* @note If this function is called for periodic calibration, the DLLRDY
* interrupt is generated every time the calibration completes which
* will significantly increases the overall interrupt rate.
*/
HAL_StatusTypeDef HAL_HRTIM_DLLCalibrationStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t CalibrationRate)
{
/* Check the parameters */
assert_param(IS_HRTIM_CALIBRATIONRATE(CalibrationRate));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable DLL Ready interrupt flag */
__HAL_HRTIM_ENABLE_IT(hhrtim, HRTIM_IT_DLLRDY);
if (CalibrationRate == HRTIM_SINGLE_CALIBRATION)
{
/* One shot DLL calibration */
CLEAR_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALEN);
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CAL);
}
else
{
/* Periodic DLL calibration */
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALEN);
MODIFY_REG(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CALRTE, CalibrationRate);
SET_BIT(hhrtim->Instance->sCommonRegs.DLLCR, HRTIM_DLLCR_CAL);
}
/* Set HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_READY;
return HAL_OK;
}
/**
* @brief Poll the DLL calibration ready flag and returns when the flag is
* set (DLL calibration completed) or upon timeout expiration.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timeout Timeout duration in millisecond
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_PollForDLLCalibration(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timeout)
{
uint32_t tickstart;
tickstart = HAL_GetTick();
/* Check End of conversion flag */
while(__HAL_HRTIM_GET_FLAG(hhrtim, HRTIM_IT_DLLRDY) == (uint32_t)RESET)
{
if (Timeout != HAL_MAX_DELAY)
{
if(((HAL_GetTick()-tickstart) > Timeout) || (Timeout == 0U))
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
return HAL_TIMEOUT;
}
}
}
/* Set HRTIM State */
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the time base unit of a timer
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pTimeBaseCfg pointer to the time base configuration structure
* @note This function must be called prior starting the timer
* @note The time-base unit initialization parameters specify:
* The timer counter operating mode (continuous, one shot),
* The timer clock prescaler,
* The timer period,
* The timer repetition counter.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_TimeBaseConfig(HRTIM_HandleTypeDef *hhrtim,
uint32_t TimerIdx,
HRTIM_TimeBaseCfgTypeDef * pTimeBaseCfg)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
assert_param(IS_HRTIM_PRESCALERRATIO(pTimeBaseCfg->PrescalerRatio));
assert_param(IS_HRTIM_MODE(pTimeBaseCfg->Mode));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Set the HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
/* Configure master timer time base unit */
HRTIM_MasterBase_Config(hhrtim, pTimeBaseCfg);
}
else
{
/* Configure timing unit time base unit */
HRTIM_TimingUnitBase_Config(hhrtim, TimerIdx, pTimeBaseCfg);
}
/* Set HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_READY;
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group2 Simple time base mode functions
* @brief Simple time base mode functions.
@verbatim
===============================================================================
##### Simple time base mode functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Start simple time base
(+) Stop simple time base
(+) Start simple time base and enable interrupt
(+) Stop simple time base and disable interrupt
(+) Start simple time base and enable DMA transfer
(+) Stop simple time base and disable DMA transfer
-@- When a HRTIM timer operates in simple time base mode, the timer
counter counts from 0 to the period value.
@endverbatim
* @{
*/
/**
* @brief Start the counter of a timer operating in simple time base mode.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the counter of a timer operating in simple time base mode.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the counter of a timer operating in simple time base mode
* (Timer repetition interrupt is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the repetition interrupt */
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
__HAL_HRTIM_MASTER_ENABLE_IT(hhrtim, HRTIM_MASTER_IT_MREP);
}
else
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_REP);
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the counter of a timer operating in simple time base mode
* (Timer repetition interrupt is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the repetition interrupt */
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
__HAL_HRTIM_MASTER_DISABLE_IT(hhrtim, HRTIM_MASTER_IT_MREP);
}
else
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_REP);
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the counter of a timer operating in simple time base mode
* (Timer repetition DMA request is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param SrcAddr DMA transfer source address
* @param DestAddr DMA transfer destination address
* @param Length The length of data items (data size) to be transferred
* from source to destination
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStart_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t SrcAddr,
uint32_t DestAddr,
uint32_t Length)
{
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
if(hhrtim->State == HAL_HRTIM_STATE_READY)
{
if((SrcAddr == 0U ) || (DestAddr == 0U ) || (Length == 0U))
{
return HAL_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_BUSY;
}
}
/* Process Locked */
__HAL_LOCK(hhrtim);
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA transfer completed callback */
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
hdma->XferCpltCallback = HRTIM_DMAMasterCplt;
}
else
{
hdma->XferCpltCallback = HRTIM_DMATimerxCplt;
}
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma, SrcAddr, DestAddr, Length) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Enable the timer repetition DMA request */
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
__HAL_HRTIM_MASTER_ENABLE_DMA(hhrtim, HRTIM_MASTER_DMA_MREP);
}
else
{
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_REP);
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the counter of a timer operating in simple time base mode
* (Timer repetition DMA request is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index.
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleBaseStop_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Process Locked */
__HAL_LOCK(hhrtim);
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Disable the DMA */
if (HAL_DMA_Abort(hhrtim->hdmaMaster) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
}
/* Disable the timer repetition DMA request */
__HAL_HRTIM_MASTER_DISABLE_DMA(hhrtim, HRTIM_MASTER_DMA_MREP);
}
else
{
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Disable the DMA */
if (HAL_DMA_Abort(hdma) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
}
/* Disable the timer repetition DMA request */
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_REP);
}
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
if (hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
else
{
return HAL_OK;
}
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group3 Simple output compare mode functions
* @brief Simple output compare functions
@verbatim
===============================================================================
##### Simple output compare functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure simple output channel
(+) Start simple output compare
(+) Stop simple output compare
(+) Start simple output compare and enable interrupt
(+) Stop simple output compare and disable interrupt
(+) Start simple output compare and enable DMA transfer
(+) Stop simple output compare and disable DMA transfer
-@- When a HRTIM timer operates in simple output compare mode
the output level is set to a programmable value when a match
is found between the compare register and the counter.
Compare unit 1 is automatically associated to output 1
Compare unit 2 is automatically associated to output 2
@endverbatim
* @{
*/
/**
* @brief Configure an output in simple output compare mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param pSimpleOCChannelCfg pointer to the simple output compare output configuration structure
* @note When the timer operates in simple output compare mode:
* Output 1 is implicitly controlled by the compare unit 1
* Output 2 is implicitly controlled by the compare unit 2
* Output Set/Reset crossbar is set according to the selected output compare mode:
* Toggle: SETxyR = RSTxyR = CMPy
* Active: SETxyR = CMPy, RSTxyR = 0
* Inactive: SETxy =0, RSTxy = CMPy
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCChannelConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel,
HRTIM_SimpleOCChannelCfgTypeDef* pSimpleOCChannelCfg)
{
uint32_t CompareUnit = (uint32_t)RESET;
HRTIM_OutputCfgTypeDef OutputCfg;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
assert_param(IS_HRTIM_BASICOCMODE(pSimpleOCChannelCfg->Mode));
assert_param(IS_HRTIM_OUTPUTPULSE(pSimpleOCChannelCfg->Pulse));
assert_param(IS_HRTIM_OUTPUTPOLARITY(pSimpleOCChannelCfg->Polarity));
assert_param(IS_HRTIM_OUTPUTIDLELEVEL(pSimpleOCChannelCfg->IdleLevel));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
/* Set HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure timer compare unit */
switch (OCChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
CompareUnit = HRTIM_COMPAREUNIT_1;
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pSimpleOCChannelCfg->Pulse;
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
CompareUnit = HRTIM_COMPAREUNIT_2;
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP2xR = pSimpleOCChannelCfg->Pulse;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Configure timer output */
OutputCfg.Polarity = (pSimpleOCChannelCfg->Polarity & HRTIM_OUTR_POL1);
OutputCfg.IdleLevel = (pSimpleOCChannelCfg->IdleLevel & HRTIM_OUTR_IDLES1);
OutputCfg.FaultLevel = HRTIM_OUTPUTFAULTLEVEL_NONE;
OutputCfg.IdleMode = HRTIM_OUTPUTIDLEMODE_NONE;
OutputCfg.ChopperModeEnable = HRTIM_OUTPUTCHOPPERMODE_DISABLED;
OutputCfg.BurstModeEntryDelayed = HRTIM_OUTPUTBURSTMODEENTRY_REGULAR;
switch (pSimpleOCChannelCfg->Mode)
{
case HRTIM_BASICOCMODE_TOGGLE:
{
if (CompareUnit == HRTIM_COMPAREUNIT_1)
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP1;
}
else
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP2;
}
OutputCfg.ResetSource = OutputCfg.SetSource;
break;
}
case HRTIM_BASICOCMODE_ACTIVE:
{
if (CompareUnit == HRTIM_COMPAREUNIT_1)
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP1;
}
else
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP2;
}
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_NONE;
break;
}
case HRTIM_BASICOCMODE_INACTIVE:
{
if (CompareUnit == HRTIM_COMPAREUNIT_1)
{
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_TIMCMP1;
}
else
{
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_TIMCMP2;
}
OutputCfg.SetSource = HRTIM_OUTPUTSET_NONE;
break;
}
default:
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_NONE;
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_NONE;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
HRTIM_OutputConfig(hhrtim,
TimerIdx,
OCChannel,
&OutputCfg);
/* Set HRTIM state */
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the output compare signal generation on the designed timer output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= OCChannel;
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the output compare signal generation on the designed timer output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= OCChannel;
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the output compare signal generation on the designed timer output
* (Interrupt is enabled (see note note below)).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @note Interrupt enabling depends on the chosen output compare mode
* Output toggle: compare match interrupt is enabled
* Output set active: output set interrupt is enabled
* Output set inactive: output reset interrupt is enabled
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
uint32_t interrupt;
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Get the interrupt to enable (depends on the output compare mode) */
interrupt = HRTIM_GetITFromOCMode(hhrtim, TimerIdx, OCChannel);
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= OCChannel;
/* Enable the timer interrupt (depends on the output compare mode) */
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, interrupt);
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the output compare signal generation on the designed timer output
* (Interrupt is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
uint32_t interrupt;
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= OCChannel;
/* Get the interrupt to disable (depends on the output compare mode) */
interrupt = HRTIM_GetITFromOCMode(hhrtim, TimerIdx, OCChannel);
/* Disable the timer interrupt */
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, interrupt);
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the output compare signal generation on the designed timer output
* (DMA request is enabled (see note below)).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param SrcAddr DMA transfer source address
* @param DestAddr DMA transfer destination address
* @param Length The length of data items (data size) to be transferred
* from source to destination
* @note DMA request enabling depends on the chosen output compare mode
* Output toggle: compare match DMA request is enabled
* Output set active: output set DMA request is enabled
* Output set inactive: output reset DMA request is enabled
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStart_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel,
uint32_t SrcAddr,
uint32_t DestAddr,
uint32_t Length)
{
DMA_HandleTypeDef * hdma;
uint32_t dma_request;
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
if(hhrtim->State == HAL_HRTIM_STATE_READY)
{
if((SrcAddr == 0U ) || (DestAddr == 0U ) || (Length == 0U))
{
return HAL_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_BUSY;
}
}
/* Process Locked */
__HAL_LOCK(hhrtim);
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= OCChannel;
/* Get the DMA request to enable */
dma_request = HRTIM_GetDMAFromOCMode(hhrtim, TimerIdx, OCChannel);
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Set the DMA transfer completed callback */
hdma->XferCpltCallback = HRTIM_DMATimerxCplt;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma, SrcAddr, DestAddr, Length) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Enable the timer DMA request */
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, dma_request);
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the output compare signal generation on the designed timer output
* (DMA request is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOCStop_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
uint32_t dma_request;
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OCChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= OCChannel;
/* Get the timer DMA handler */
/* Disable the DMA */
if (HAL_DMA_Abort(HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx)) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Get the DMA request to disable */
dma_request = HRTIM_GetDMAFromOCMode(hhrtim, TimerIdx, OCChannel);
/* Disable the timer DMA request */
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, dma_request);
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group4 Simple PWM output mode functions
* @brief Simple PWM output functions
@verbatim
===============================================================================
##### Simple PWM output functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure simple PWM output channel
(+) Start simple PWM output
(+) Stop simple PWM output
(+) Start simple PWM output and enable interrupt
(+) Stop simple PWM output and disable interrupt
(+) Start simple PWM output and enable DMA transfer
(+) Stop simple PWM output and disable DMA transfer
-@- When a HRTIM timer operates in simple PWM output mode
the output level is set to a programmable value when a match is
found between the compare register and the counter and reset when
the timer period is reached. Duty cycle is determined by the
comparison value.
Compare unit 1 is automatically associated to output 1
Compare unit 2 is automatically associated to output 2
@endverbatim
* @{
*/
/**
* @brief Configure an output in simple PWM mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param pSimplePWMChannelCfg pointer to the simple PWM output configuration structure
* @note When the timer operates in simple PWM output mode:
* Output 1 is implicitly controlled by the compare unit 1
* Output 2 is implicitly controlled by the compare unit 2
* Output Set/Reset crossbar is set as follows:
* Output 1: SETx1R = CMP1, RSTx1R = PER
* Output 2: SETx2R = CMP2, RST2R = PER
* @note When Simple PWM mode is used the registers preload mechanism is
* enabled (otherwise the behavior is not guaranteed).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMChannelConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel,
HRTIM_SimplePWMChannelCfgTypeDef* pSimplePWMChannelCfg)
{
HRTIM_OutputCfgTypeDef OutputCfg;
uint32_t hrtim_timcr;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
assert_param(IS_HRTIM_OUTPUTPOLARITY(pSimplePWMChannelCfg->Polarity));
assert_param(IS_HRTIM_OUTPUTPULSE(pSimplePWMChannelCfg->Pulse));
assert_param(IS_HRTIM_OUTPUTIDLELEVEL(pSimplePWMChannelCfg->IdleLevel));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure timer compare unit */
switch (PWMChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pSimplePWMChannelCfg->Pulse;
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP1;
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP2xR = pSimplePWMChannelCfg->Pulse;
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP2;
break;
}
default:
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_NONE;
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_NONE;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Configure timer output */
OutputCfg.Polarity = (pSimplePWMChannelCfg->Polarity & HRTIM_OUTR_POL1);
OutputCfg.IdleLevel = (pSimplePWMChannelCfg->IdleLevel& HRTIM_OUTR_IDLES1);
OutputCfg.FaultLevel = HRTIM_OUTPUTFAULTLEVEL_NONE;
OutputCfg.IdleMode = HRTIM_OUTPUTIDLEMODE_NONE;
OutputCfg.ChopperModeEnable = HRTIM_OUTPUTCHOPPERMODE_DISABLED;
OutputCfg.BurstModeEntryDelayed = HRTIM_OUTPUTBURSTMODEENTRY_REGULAR;
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_TIMPER;
HRTIM_OutputConfig(hhrtim,
TimerIdx,
PWMChannel,
&OutputCfg);
/* Enable the registers preload mechanism */
hrtim_timcr = hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR;
hrtim_timcr |= HRTIM_TIMCR_PREEN;
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR = hrtim_timcr;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the PWM output signal generation on the designed timer output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= PWMChannel;
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the PWM output signal generation on the designed timer output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= PWMChannel;
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the PWM output signal generation on the designed timer output
* (The compare interrupt is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= PWMChannel;
/* Enable the timer interrupt (depends on the PWM output) */
switch (PWMChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the PWM output signal generation on the designed timer output
* (The compare interrupt is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= PWMChannel;
/* Disable the timer interrupt (depends on the PWM output) */
switch (PWMChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the PWM output signal generation on the designed timer output
* (The compare DMA request is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param SrcAddr DMA transfer source address
* @param DestAddr DMA transfer destination address
* @param Length The length of data items (data size) to be transferred
* from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStart_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel,
uint32_t SrcAddr,
uint32_t DestAddr,
uint32_t Length)
{
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
if(hhrtim->State == HAL_HRTIM_STATE_READY)
{
if((SrcAddr == 0U ) || (DestAddr == 0U ) || (Length == 0U))
{
return HAL_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_BUSY;
}
}
/* Process Locked */
__HAL_LOCK(hhrtim);
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= PWMChannel;
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Set the DMA transfer completed callback */
hdma->XferCpltCallback = HRTIM_DMATimerxCplt;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma, SrcAddr, DestAddr, Length) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Enable the timer DMA request */
switch (PWMChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the PWM output signal generation on the designed timer output
* (The compare DMA request is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param PWMChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimplePWMStop_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t PWMChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, PWMChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= PWMChannel;
/* Get the timer DMA handler */
/* Disable the DMA */
if (HAL_DMA_Abort(HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx)) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Disable the timer DMA request */
switch (PWMChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group5 Simple input capture functions
* @brief Simple input capture functions
@verbatim
===============================================================================
##### Simple input capture functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure simple input capture channel
(+) Start simple input capture
(+) Stop simple input capture
(+) Start simple input capture and enable interrupt
(+) Stop simple input capture and disable interrupt
(+) Start simple input capture and enable DMA transfer
(+) Stop simple input capture and disable DMA transfer
-@- When a HRTIM timer operates in simple input capture mode
the Capture Register (HRTIM_CPT1/2xR) is used to latch the
value of the timer counter counter after a transition detected
on a given external event input.
@endverbatim
* @{
*/
/**
* @brief Configure a simple capture
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Capture unit
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @param pSimpleCaptureChannelCfg pointer to the simple capture configuration structure
* @note When the timer operates in simple capture mode the capture is triggered
* by the designated external event and GPIO input is implicitly used as event source.
* The cature can be triggered by a rising edge, a falling edge or both
* edges on event channel.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureChannelConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel,
HRTIM_SimpleCaptureChannelCfgTypeDef* pSimpleCaptureChannelCfg)
{
HRTIM_EventCfgTypeDef EventCfg;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
assert_param(IS_HRTIM_EVENT(pSimpleCaptureChannelCfg->Event));
assert_param(IS_HRTIM_EVENTPOLARITY(pSimpleCaptureChannelCfg->EventSensitivity,
pSimpleCaptureChannelCfg->EventPolarity));
assert_param(IS_HRTIM_EVENTSENSITIVITY(pSimpleCaptureChannelCfg->EventSensitivity));
assert_param(IS_HRTIM_EVENTFILTER(pSimpleCaptureChannelCfg->Event,
pSimpleCaptureChannelCfg->EventFilter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure external event channel */
EventCfg.FastMode = HRTIM_EVENTFASTMODE_DISABLE;
EventCfg.Filter = (pSimpleCaptureChannelCfg->EventFilter & HRTIM_EECR3_EE6F);
EventCfg.Polarity = (pSimpleCaptureChannelCfg->EventPolarity & HRTIM_EECR1_EE1POL);
EventCfg.Sensitivity = (pSimpleCaptureChannelCfg->EventSensitivity & HRTIM_EECR1_EE1SNS);
EventCfg.Source = HRTIM_EEV1SRC_GPIO; /* source 1 for External Event */
HRTIM_EventConfig(hhrtim,
pSimpleCaptureChannelCfg->Event,
&EventCfg);
/* Memorize capture trigger (will be configured when the capture is started */
HRTIM_CaptureUnitConfig(hhrtim,
TimerIdx,
CaptureChannel,
pSimpleCaptureChannelCfg->Event);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable a simple capture on the designed capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
* @note The external event triggering the capture is available for all timing
* units. It can be used directly and is active as soon as the timing
* unit counter is enabled.
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the capture unit trigger */
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger1;
break;
}
case HRTIM_CAPTUREUNIT_2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger2;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable a simple capture on the designed capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel)
{
uint32_t hrtim_cpt1cr;
uint32_t hrtim_cpt2cr;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the capture unit trigger */
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = HRTIM_CAPTURETRIGGER_NONE;
break;
}
case HRTIM_CAPTUREUNIT_2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = HRTIM_CAPTURETRIGGER_NONE;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hrtim_cpt1cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR;
hrtim_cpt2cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR;
/* Disable the timer counter */
if ((hrtim_cpt1cr == HRTIM_CAPTURETRIGGER_NONE) &&
(hrtim_cpt2cr == HRTIM_CAPTURETRIGGER_NONE))
{
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable a simple capture on the designed capture unit
* (Capture interrupt is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the capture unit trigger */
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger1;
/* Enable the capture unit 1 interrupt */
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT1);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger2;
/* Enable the capture unit 2 interrupt */
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable a simple capture on the designed capture unit
* (Capture interrupt is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel)
{
uint32_t hrtim_cpt1cr;
uint32_t hrtim_cpt2cr;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the capture unit trigger */
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = HRTIM_CAPTURETRIGGER_NONE;
/* Disable the capture unit 1 interrupt */
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT1);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = HRTIM_CAPTURETRIGGER_NONE;
/* Disable the capture unit 2 interrupt */
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hrtim_cpt1cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR;
hrtim_cpt2cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR;
/* Disable the timer counter */
if ((hrtim_cpt1cr == HRTIM_CAPTURETRIGGER_NONE) &&
(hrtim_cpt2cr == HRTIM_CAPTURETRIGGER_NONE))
{
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable a simple capture on the designed capture unit
* (Capture DMA request is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @param SrcAddr DMA transfer source address
* @param DestAddr DMA transfer destination address
* @param Length The length of data items (data size) to be transferred
* from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStart_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel,
uint32_t SrcAddr,
uint32_t DestAddr,
uint32_t Length)
{
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Set the DMA transfer completed callback */
hdma->XferCpltCallback = HRTIM_DMATimerxCplt;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma, SrcAddr, DestAddr, Length) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
/* Set the capture unit trigger */
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger1;
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CPT1);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
/* Set the capture unit trigger */
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = hhrtim->TimerParam[TimerIdx].CaptureTrigger2;
/* Enable the timer DMA request */
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CPT2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable a simple capture on the designed capture unit
* (Capture DMA request is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleCaptureStop_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureChannel)
{
uint32_t hrtim_cpt1cr;
uint32_t hrtim_cpt2cr;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Get the timer DMA handler */
/* Disable the DMA */
if (HAL_DMA_Abort(HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx)) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
switch (CaptureChannel)
{
case HRTIM_CAPTUREUNIT_1:
{
/* Reset the capture unit trigger */
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR = HRTIM_CAPTURETRIGGER_NONE;
/* Disable the capture unit 1 DMA request */
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CPT1);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
/* Reset the capture unit trigger */
hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR = HRTIM_CAPTURETRIGGER_NONE;
/* Disable the capture unit 2 DMA request */
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim, TimerIdx, HRTIM_TIM_DMA_CPT2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hrtim_cpt1cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR;
hrtim_cpt2cr = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR;
/* Disable the timer counter */
if ((hrtim_cpt1cr == HRTIM_CAPTURETRIGGER_NONE) &&
(hrtim_cpt2cr == HRTIM_CAPTURETRIGGER_NONE))
{
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group6 Simple one pulse functions
* @brief Simple one pulse functions
@verbatim
===============================================================================
##### Simple one pulse functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure one pulse channel
(+) Start one pulse generation
(+) Stop one pulse generation
(+) Start one pulse generation and enable interrupt
(+) Stop one pulse generation and disable interrupt
-@- When a HRTIM timer operates in simple one pulse mode
the timer counter is started in response to transition detected
on a given external event input to generate a pulse with a
programmable length after a programmable delay.
@endverbatim
* @{
*/
/**
* @brief Configure an output simple one pulse mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OnePulseChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param pSimpleOnePulseChannelCfg pointer to the simple one pulse output configuration structure
* @note When the timer operates in simple one pulse mode:
* the timer counter is implicitly started by the reset event,
* the reset of the timer counter is triggered by the designated external event
* GPIO input is implicitly used as event source,
* Output 1 is implicitly controlled by the compare unit 1,
* Output 2 is implicitly controlled by the compare unit 2.
* Output Set/Reset crossbar is set as follows:
* Output 1: SETx1R = CMP1, RSTx1R = PER
* Output 2: SETx2R = CMP2, RST2R = PER
* @retval HAL status
* @note If HAL_HRTIM_SimpleOnePulseChannelConfig is called for both timer
* outputs, the reset event related configuration data provided in the
* second call will override the reset event related configuration data
* provided in the first call.
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOnePulseChannelConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OnePulseChannel,
HRTIM_SimpleOnePulseChannelCfgTypeDef* pSimpleOnePulseChannelCfg)
{
HRTIM_OutputCfgTypeDef OutputCfg;
HRTIM_EventCfgTypeDef EventCfg;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OnePulseChannel));
assert_param(IS_HRTIM_OUTPUTPULSE(pSimpleOnePulseChannelCfg->Pulse));
assert_param(IS_HRTIM_OUTPUTPOLARITY(pSimpleOnePulseChannelCfg->OutputPolarity));
assert_param(IS_HRTIM_OUTPUTIDLELEVEL(pSimpleOnePulseChannelCfg->OutputIdleLevel));
assert_param(IS_HRTIM_EVENT(pSimpleOnePulseChannelCfg->Event));
assert_param(IS_HRTIM_EVENTPOLARITY(pSimpleOnePulseChannelCfg->EventSensitivity,
pSimpleOnePulseChannelCfg->EventPolarity));
assert_param(IS_HRTIM_EVENTSENSITIVITY(pSimpleOnePulseChannelCfg->EventSensitivity));
assert_param(IS_HRTIM_EVENTFILTER(pSimpleOnePulseChannelCfg->Event,
pSimpleOnePulseChannelCfg->EventFilter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure timer compare unit */
switch (OnePulseChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pSimpleOnePulseChannelCfg->Pulse;
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP1;
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP2xR = pSimpleOnePulseChannelCfg->Pulse;
OutputCfg.SetSource = HRTIM_OUTPUTSET_TIMCMP2;
break;
}
default:
{
OutputCfg.SetSource = HRTIM_OUTPUTSET_NONE;
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_NONE;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Configure timer output */
OutputCfg.Polarity = (pSimpleOnePulseChannelCfg->OutputPolarity & HRTIM_OUTR_POL1);
OutputCfg.IdleLevel = (pSimpleOnePulseChannelCfg->OutputIdleLevel & HRTIM_OUTR_IDLES1);
OutputCfg.FaultLevel = HRTIM_OUTPUTFAULTLEVEL_NONE;
OutputCfg.IdleMode = HRTIM_OUTPUTIDLEMODE_NONE;
OutputCfg.ChopperModeEnable = HRTIM_OUTPUTCHOPPERMODE_DISABLED;
OutputCfg.BurstModeEntryDelayed = HRTIM_OUTPUTBURSTMODEENTRY_REGULAR;
OutputCfg.ResetSource = HRTIM_OUTPUTRESET_TIMPER;
HRTIM_OutputConfig(hhrtim,
TimerIdx,
OnePulseChannel,
&OutputCfg);
/* Configure external event channel */
EventCfg.FastMode = HRTIM_EVENTFASTMODE_DISABLE;
EventCfg.Filter = (pSimpleOnePulseChannelCfg->EventFilter & HRTIM_EECR3_EE6F);
EventCfg.Polarity = (pSimpleOnePulseChannelCfg->EventPolarity & HRTIM_OUTR_POL1);
EventCfg.Sensitivity = (pSimpleOnePulseChannelCfg->EventSensitivity &HRTIM_EECR1_EE1SNS);
EventCfg.Source = HRTIM_EEV1SRC_GPIO; /* source 1 for External Event */
HRTIM_EventConfig(hhrtim,
pSimpleOnePulseChannelCfg->Event,
&EventCfg);
/* Configure the timer reset register */
HRTIM_TIM_ResetConfig(hhrtim,
TimerIdx,
pSimpleOnePulseChannelCfg->Event);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable the simple one pulse signal generation on the designed output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OnePulseChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOnePulseStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OnePulseChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OnePulseChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= OnePulseChannel;
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable the simple one pulse signal generation on the designed output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OnePulseChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOnePulseStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OnePulseChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OnePulseChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= OnePulseChannel;
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable the simple one pulse signal generation on the designed output
* (The compare interrupt is enabled (pulse start)).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer E
* @param OnePulseChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOnePulseStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OnePulseChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OnePulseChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the timer output */
hhrtim->Instance->sCommonRegs.OENR |= OnePulseChannel;
/* Enable the timer interrupt (depends on the OnePulse output) */
switch (OnePulseChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable the simple one pulse signal generation on the designed output
* (The compare interrupt is disabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param OnePulseChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_SimpleOnePulseStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OnePulseChannel)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, OnePulseChannel));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable the timer output */
hhrtim->Instance->sCommonRegs.ODISR |= OnePulseChannel;
/* Disable the timer interrupt (depends on the OnePulse output) */
switch (OnePulseChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP1);
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP2);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, TimerIdxToTimerId[TimerIdx]);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group7 Configuration functions
* @brief HRTIM configuration functions
@verbatim
===============================================================================
##### HRTIM configuration functions #####
===============================================================================
[..] This section provides functions allowing to configure the HRTIM
resources shared by all the HRTIM timers operating in waveform mode:
(+) Configure the burst mode controller
(+) Configure an external event conditioning
(+) Configure the external events sampling clock
(+) Configure a fault conditioning
(+) Enable or disable fault inputs
(+) Configure the faults sampling clock
(+) Configure an ADC trigger
@endverbatim
* @{
*/
/**
* @brief Configure the burst mode feature of the HRTIM
* @param hhrtim pointer to HAL HRTIM handle
* @param pBurstModeCfg pointer to the burst mode configuration structure
* @retval HAL status
* @note This function must be called before starting the burst mode
* controller
*/
HAL_StatusTypeDef HAL_HRTIM_BurstModeConfig(HRTIM_HandleTypeDef * hhrtim,
HRTIM_BurstModeCfgTypeDef* pBurstModeCfg)
{
uint32_t hrtim_bmcr;
/* Check parameters */
assert_param(IS_HRTIM_BURSTMODE(pBurstModeCfg->Mode));
assert_param(IS_HRTIM_BURSTMODECLOCKSOURCE(pBurstModeCfg->ClockSource));
assert_param(IS_HRTIM_HRTIM_BURSTMODEPRESCALER(pBurstModeCfg->Prescaler));
assert_param(IS_HRTIM_BURSTMODEPRELOAD(pBurstModeCfg->PreloadEnable));
assert_param(IS_HRTIM_BURSTMODETRIGGER(pBurstModeCfg->Trigger));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
hrtim_bmcr = hhrtim->Instance->sCommonRegs.BMCR;
/* Set the burst mode operating mode */
hrtim_bmcr &= ~(HRTIM_BMCR_BMOM);
hrtim_bmcr |= (pBurstModeCfg->Mode & HRTIM_BMCR_BMOM);
/* Set the burst mode clock source */
hrtim_bmcr &= ~(HRTIM_BMCR_BMCLK);
hrtim_bmcr |= (pBurstModeCfg->ClockSource & HRTIM_BMCR_BMCLK);
/* Set the burst mode prescaler */
hrtim_bmcr &= ~(HRTIM_BMCR_BMPRSC);
hrtim_bmcr |= pBurstModeCfg->Prescaler;
/* Enable/disable burst mode registers preload */
hrtim_bmcr &= ~(HRTIM_BMCR_BMPREN);
hrtim_bmcr |= (pBurstModeCfg->PreloadEnable & HRTIM_BMCR_BMPREN);
/* Set the burst mode trigger */
hhrtim->Instance->sCommonRegs.BMTRGR = pBurstModeCfg->Trigger;
/* Set the burst mode compare value */
hhrtim->Instance->sCommonRegs.BMCMPR = pBurstModeCfg->IdleDuration;
/* Set the burst mode period */
hhrtim->Instance->sCommonRegs.BMPER = pBurstModeCfg->Period;
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.BMCR = hrtim_bmcr;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the conditioning of an external event
* @param hhrtim pointer to HAL HRTIM handle
* @param Event external event to configure
* This parameter can be one of the following values:
* @arg HRTIM_EVENT_NONE: no external Event
* @arg HRTIM_EVENT_1: External event 1
* @arg HRTIM_EVENT_2: External event 2
* @arg HRTIM_EVENT_3: External event 3
* @arg HRTIM_EVENT_4: External event 4
* @arg HRTIM_EVENT_5: External event 5
* @arg HRTIM_EVENT_6: External event 6
* @arg HRTIM_EVENT_7: External event 7
* @arg HRTIM_EVENT_8: External event 8
* @arg HRTIM_EVENT_9: External event 9
* @arg HRTIM_EVENT_10: External event 10
* @param pEventCfg pointer to the event conditioning configuration structure
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_EventConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Event,
HRTIM_EventCfgTypeDef* pEventCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_EVENT(Event));
assert_param(IS_HRTIM_EVENTSRC(Event, pEventCfg->Source));
assert_param(IS_HRTIM_EVENTPOLARITY(pEventCfg->Sensitivity, pEventCfg->Polarity));
assert_param(IS_HRTIM_EVENTSENSITIVITY(pEventCfg->Sensitivity));
assert_param(IS_HRTIM_EVENTFASTMODE(Event, pEventCfg->FastMode));
assert_param(IS_HRTIM_EVENTFILTER(Event, pEventCfg->Filter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure the event channel */
HRTIM_EventConfig(hhrtim, Event, pEventCfg);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the external event conditioning block prescaler
* @param hhrtim pointer to HAL HRTIM handle
* @param Prescaler Prescaler value
* This parameter can be one of the following values:
* @arg HRTIM_EVENTPRESCALER_DIV1: fEEVS=fHRTIM
* @arg HRTIM_EVENTPRESCALER_DIV2: fEEVS=fHRTIM / 2
* @arg HRTIM_EVENTPRESCALER_DIV4: fEEVS=fHRTIM / 4
* @arg HRTIM_EVENTPRESCALER_DIV8: fEEVS=fHRTIM / 8
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_EventPrescalerConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Prescaler)
{
/* Check parameters */
assert_param(IS_HRTIM_EVENTPRESCALER(Prescaler));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the external event prescaler */
MODIFY_REG(hhrtim->Instance->sCommonRegs.EECR3, HRTIM_EECR3_EEVSD, (Prescaler & HRTIM_EECR3_EEVSD));
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the conditioning of fault input
* @param hhrtim pointer to HAL HRTIM handle
* @param Fault fault input to configure
* This parameter can be one of the following values:
* @arg HRTIM_FAULT_1: Fault input 1
* @arg HRTIM_FAULT_2: Fault input 2
* @arg HRTIM_FAULT_3: Fault input 3
* @arg HRTIM_FAULT_4: Fault input 4
* @arg HRTIM_FAULT_5: Fault input 5
* @arg HRTIM_FAULT_6: Fault input 6
* @param pFaultCfg pointer to the fault conditioning configuration structure
* @note This function must be called before starting the timer and before
* enabling faults inputs
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_FaultConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Fault,
HRTIM_FaultCfgTypeDef* pFaultCfg)
{
uint32_t hrtim_fltinr1;
uint32_t hrtim_fltinr2;
uint32_t source0,source1;
/* Check parameters */
assert_param(IS_HRTIM_FAULT(Fault));
assert_param(IS_HRTIM_FAULTSOURCE(pFaultCfg->Source));
assert_param(IS_HRTIM_FAULTPOLARITY(pFaultCfg->Polarity));
assert_param(IS_HRTIM_FAULTFILTER(pFaultCfg->Filter));
assert_param(IS_HRTIM_FAULTLOCK(pFaultCfg->Lock));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure fault channel */
hrtim_fltinr1 = hhrtim->Instance->sCommonRegs.FLTINR1;
hrtim_fltinr2 = hhrtim->Instance->sCommonRegs.FLTINR2;
source0 = (pFaultCfg->Source & 1U);
source1 = ((pFaultCfg->Source & 2U) >> 1);
switch (Fault)
{
case HRTIM_FAULT_1:
{
hrtim_fltinr1 &= ~(HRTIM_FLTINR1_FLT1P | HRTIM_FLTINR1_FLT1SRC_0 | HRTIM_FLTINR1_FLT1F | HRTIM_FLTINR1_FLT1LCK);
hrtim_fltinr1 |= (pFaultCfg->Polarity & HRTIM_FLTINR1_FLT1P);
hrtim_fltinr1 |= (source0 << HRTIM_FLTINR1_FLT1SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT1SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT1SRC_1_Pos);
hrtim_fltinr1 |= (pFaultCfg->Filter & HRTIM_FLTINR1_FLT1F);
hrtim_fltinr1 |= (pFaultCfg->Lock & HRTIM_FLTINR1_FLT1LCK);
break;
}
case HRTIM_FAULT_2:
{
hrtim_fltinr1 &= ~(HRTIM_FLTINR1_FLT2P | HRTIM_FLTINR1_FLT2SRC_0 | HRTIM_FLTINR1_FLT2F | HRTIM_FLTINR1_FLT2LCK);
hrtim_fltinr1 |= ((pFaultCfg->Polarity << 8U) & HRTIM_FLTINR1_FLT2P);
hrtim_fltinr1 |= (source0 << HRTIM_FLTINR1_FLT2SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT2SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT2SRC_1_Pos);
hrtim_fltinr1 |= ((pFaultCfg->Filter << 8U) & HRTIM_FLTINR1_FLT2F);
hrtim_fltinr1 |= ((pFaultCfg->Lock << 8U) & HRTIM_FLTINR1_FLT2LCK);
break;
}
case HRTIM_FAULT_3:
{
hrtim_fltinr1 &= ~(HRTIM_FLTINR1_FLT3P | HRTIM_FLTINR1_FLT3SRC_0 | HRTIM_FLTINR1_FLT3F | HRTIM_FLTINR1_FLT3LCK);
hrtim_fltinr1 |= ((pFaultCfg->Polarity << 16U) & HRTIM_FLTINR1_FLT3P);
hrtim_fltinr1 |= (source0 << HRTIM_FLTINR1_FLT3SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT3SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT3SRC_1_Pos);
hrtim_fltinr1 |= ((pFaultCfg->Filter << 16U) & HRTIM_FLTINR1_FLT3F);
hrtim_fltinr1 |= ((pFaultCfg->Lock << 16U) & HRTIM_FLTINR1_FLT3LCK);
break;
}
case HRTIM_FAULT_4:
{
hrtim_fltinr1 &= ~(HRTIM_FLTINR1_FLT4P | HRTIM_FLTINR1_FLT4SRC_0 | HRTIM_FLTINR1_FLT4F | HRTIM_FLTINR1_FLT4LCK);
hrtim_fltinr1 |= ((pFaultCfg->Polarity << 24U) & HRTIM_FLTINR1_FLT4P);
hrtim_fltinr1 |= (source0 << HRTIM_FLTINR1_FLT4SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT4SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT4SRC_1_Pos);
hrtim_fltinr1 |= ((pFaultCfg->Filter << 24U) & HRTIM_FLTINR1_FLT4F);
hrtim_fltinr1 |= ((pFaultCfg->Lock << 24U) & HRTIM_FLTINR1_FLT4LCK);
break;
}
case HRTIM_FAULT_5:
{
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT5P | HRTIM_FLTINR2_FLT5SRC_0 | HRTIM_FLTINR2_FLT5F | HRTIM_FLTINR2_FLT5LCK);
hrtim_fltinr2 |= (pFaultCfg->Polarity & HRTIM_FLTINR2_FLT5P);
hrtim_fltinr2 |= (source0 << HRTIM_FLTINR2_FLT5SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT5SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT5SRC_1_Pos);
hrtim_fltinr2 |= (pFaultCfg->Filter & HRTIM_FLTINR2_FLT5F);
hrtim_fltinr2 |= (pFaultCfg->Lock & HRTIM_FLTINR2_FLT5LCK);
break;
}
case HRTIM_FAULT_6:
{
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT6P | HRTIM_FLTINR2_FLT6SRC_0 | HRTIM_FLTINR2_FLT6F | HRTIM_FLTINR2_FLT6LCK);
hrtim_fltinr2 |= ((pFaultCfg->Polarity << 8U) & HRTIM_FLTINR2_FLT6P);
hrtim_fltinr2 |= (source0 << HRTIM_FLTINR2_FLT6SRC_0_Pos);
hrtim_fltinr2 &= ~(HRTIM_FLTINR2_FLT6SRC_1);
hrtim_fltinr2 |= (source1 << HRTIM_FLTINR2_FLT6SRC_1_Pos);
hrtim_fltinr2 |= ((pFaultCfg->Filter << 8U) & HRTIM_FLTINR2_FLT6F);
hrtim_fltinr2 |= ((pFaultCfg->Lock << 8U) & HRTIM_FLTINR2_FLT6LCK);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Update the HRTIM registers except LOCK bit */
hhrtim->Instance->sCommonRegs.FLTINR1 = (hrtim_fltinr1 & (~(HRTIM_FLTINR1_FLTxLCK)));
hhrtim->Instance->sCommonRegs.FLTINR2 = (hrtim_fltinr2 & (~(HRTIM_FLTINR2_FLTxLCK)));
/* Update the HRTIM registers LOCK bit */
SET_BIT(hhrtim->Instance->sCommonRegs.FLTINR1,(hrtim_fltinr1 & HRTIM_FLTINR1_FLTxLCK));
SET_BIT(hhrtim->Instance->sCommonRegs.FLTINR2,(hrtim_fltinr2 & HRTIM_FLTINR2_FLTxLCK));
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the fault conditioning block prescaler
* @param hhrtim pointer to HAL HRTIM handle
* @param Prescaler Prescaler value
* This parameter can be one of the following values:
* @arg HRTIM_FAULTPRESCALER_DIV1: fFLTS=fHRTIM
* @arg HRTIM_FAULTPRESCALER_DIV2: fFLTS=fHRTIM / 2
* @arg HRTIM_FAULTPRESCALER_DIV4: fFLTS=fHRTIM / 4
* @arg HRTIM_FAULTPRESCALER_DIV8: fFLTS=fHRTIM / 8
* @retval HAL status
* @note This function must be called before starting the timer and before
* enabling faults inputs
*/
HAL_StatusTypeDef HAL_HRTIM_FaultPrescalerConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Prescaler)
{
/* Check parameters */
assert_param(IS_HRTIM_FAULTPRESCALER(Prescaler));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the external event prescaler */
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR2, HRTIM_FLTINR2_FLTSD, (Prescaler & HRTIM_FLTINR2_FLTSD));
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure and Enable the blanking source of a Fault input
* @param hhrtim pointer to HAL HRTIM handle
* @param Fault fault input to configure
* This parameter can be one of the following values:
* @arg HRTIM_FAULT_1: Fault input 1
* @arg HRTIM_FAULT_2: Fault input 2
* @arg HRTIM_FAULT_3: Fault input 3
* @arg HRTIM_FAULT_4: Fault input 4
* @arg HRTIM_FAULT_5: Fault input 5
* @arg HRTIM_FAULT_6: Fault input 6
* @param pFaultBlkCfg: pointer to the fault conditioning configuration structure
* @note This function automatically enables the Blanking on Fault
* @note This function must be called when fault is not enabled
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_FaultBlankingConfigAndEnable(HRTIM_HandleTypeDef * hhrtim,
uint32_t Fault,
HRTIM_FaultBlankingCfgTypeDef* pFaultBlkCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_FAULT(Fault));
assert_param(IS_HRTIM_FAULTBLANKNGMODE(pFaultBlkCfg->BlankingSource));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
switch (Fault)
{
case HRTIM_FAULT_1:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT1BLKS | HRTIM_FLTINR3_FLT1BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR3_FLT1BLKS_Pos) |
HRTIM_FLTINR3_FLT1BLKE));
break;
}
case HRTIM_FAULT_2:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT2BLKS | HRTIM_FLTINR3_FLT2BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR3_FLT2BLKS_Pos) |
HRTIM_FLTINR3_FLT2BLKE));
break;
}
case HRTIM_FAULT_3:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT3BLKS | HRTIM_FLTINR3_FLT3BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR3_FLT3BLKS_Pos) |
HRTIM_FLTINR3_FLT3BLKE));
break;
}
case HRTIM_FAULT_4:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT4BLKS | HRTIM_FLTINR3_FLT4BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR3_FLT4BLKS_Pos) |
HRTIM_FLTINR3_FLT4BLKE));
break;
}
case HRTIM_FAULT_5:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4,
(HRTIM_FLTINR4_FLT5BLKS | HRTIM_FLTINR4_FLT5BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR4_FLT5BLKS_Pos) |
HRTIM_FLTINR4_FLT5BLKE));
break;
}
case HRTIM_FAULT_6:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4,
(HRTIM_FLTINR4_FLT6BLKS | HRTIM_FLTINR4_FLT6BLKE),
((pFaultBlkCfg->BlankingSource << HRTIM_FLTINR4_FLT6BLKS_Pos) |
HRTIM_FLTINR4_FLT6BLKE));
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the Fault Counter (Threshold and Reset Mode)
* @param hhrtim pointer to HAL HRTIM handle
* @param Fault fault input to configure
* This parameter can be one of the following values:
* @arg HRTIM_FAULT_1: Fault input 1
* @arg HRTIM_FAULT_2: Fault input 2
* @arg HRTIM_FAULT_3: Fault input 3
* @arg HRTIM_FAULT_4: Fault input 4
* @arg HRTIM_FAULT_5: Fault input 5
* @arg HRTIM_FAULT_6: Fault input 6
* @param pFaultBlkCfg: pointer to the fault conditioning configuration structure
* @retval HAL status
* @note A fault is considered valid when the number of
* events is equal to the (FLTxCNT[3:0]+1) value
*
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_FaultCounterConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Fault,
HRTIM_FaultBlankingCfgTypeDef* pFaultBlkCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_FAULT(Fault));
assert_param(IS_HRTIM_FAULTCOUNTER(pFaultBlkCfg->Threshold));
assert_param(IS_HRTIM_FAULTCOUNTERRST(pFaultBlkCfg->ResetMode));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
switch (Fault)
{
case HRTIM_FAULT_1:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT1RSTM | HRTIM_FLTINR3_FLT1CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR3_FLT1CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR3_FLT1RSTM_Pos));
break;
}
case HRTIM_FAULT_2:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT2RSTM | HRTIM_FLTINR3_FLT2CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR3_FLT2CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR3_FLT2RSTM_Pos));
break;
}
case HRTIM_FAULT_3:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT3RSTM | HRTIM_FLTINR3_FLT3CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR3_FLT3CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR3_FLT3RSTM_Pos));
break;
}
case HRTIM_FAULT_4:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3,
(HRTIM_FLTINR3_FLT4RSTM | HRTIM_FLTINR3_FLT4CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR3_FLT4CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR3_FLT4RSTM_Pos));
break;
}
case HRTIM_FAULT_5:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4,
(HRTIM_FLTINR4_FLT5RSTM | HRTIM_FLTINR4_FLT5CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR4_FLT5CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR4_FLT5RSTM_Pos));
break;
}
case HRTIM_FAULT_6:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4,
(HRTIM_FLTINR4_FLT6RSTM | HRTIM_FLTINR4_FLT6CNT),
(pFaultBlkCfg->Threshold << HRTIM_FLTINR4_FLT6CNT_Pos) |
(pFaultBlkCfg->ResetMode << HRTIM_FLTINR4_FLT6RSTM_Pos));
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Reset the fault Counter Reset
* @param hhrtim pointer to HAL HRTIM handle
* @param Fault fault input to reset
* This parameter can be one of the following values:
* @arg HRTIM_FAULT_1: Fault input 1
* @arg HRTIM_FAULT_2: Fault input 2
* @arg HRTIM_FAULT_3: Fault input 3
* @arg HRTIM_FAULT_4: Fault input 4
* @arg HRTIM_FAULT_5: Fault input 5
* @arg HRTIM_FAULT_6: Fault input 6
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_FaultCounterReset(HRTIM_HandleTypeDef * hhrtim,
uint32_t Fault)
{
/* Check parameters */
assert_param(IS_HRTIM_FAULT(Fault));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
switch (Fault)
{
case HRTIM_FAULT_1:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3, HRTIM_FLTINR3_FLT1CRES, HRTIM_FLTINR3_FLT1CRES) ;
break;
}
case HRTIM_FAULT_2:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3, HRTIM_FLTINR3_FLT2CRES, HRTIM_FLTINR3_FLT2CRES) ;
break;
}
case HRTIM_FAULT_3:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3, HRTIM_FLTINR3_FLT3CRES, HRTIM_FLTINR3_FLT3CRES) ;
break;
}
case HRTIM_FAULT_4:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR3, HRTIM_FLTINR3_FLT4CRES, HRTIM_FLTINR3_FLT4CRES) ;
break;
}
case HRTIM_FAULT_5:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4, HRTIM_FLTINR4_FLT5CRES, HRTIM_FLTINR4_FLT5CRES) ;
break;
}
case HRTIM_FAULT_6:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR4, HRTIM_FLTINR4_FLT6CRES, HRTIM_FLTINR4_FLT6CRES) ;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable or disables the HRTIMx Fault mode.
* @param hhrtim pointer to HAL HRTIM handle
* @param Faults fault input(s) to enable or disable
* This parameter can be any combination of the following values:
* @arg HRTIM_FAULT_1: Fault input 1
* @arg HRTIM_FAULT_2: Fault input 2
* @arg HRTIM_FAULT_3: Fault input 3
* @arg HRTIM_FAULT_4: Fault input 4
* @arg HRTIM_FAULT_5: Fault input 5
* @arg HRTIM_FAULT_6: Fault input 6
* @param Enable Fault(s) enabling
* This parameter can be one of the following values:
* @arg HRTIM_FAULTMODECTL_ENABLED: Fault(s) enabled
* @arg HRTIM_FAULTMODECTL_DISABLED: Fault(s) disabled
* @retval None
*/
void HAL_HRTIM_FaultModeCtl(HRTIM_HandleTypeDef * hhrtim,
uint32_t Faults,
uint32_t Enable)
{
/* Check parameters */
assert_param(IS_HRTIM_FAULT(Faults));
assert_param(IS_HRTIM_FAULTMODECTL(Enable));
if ((Faults & HRTIM_FAULT_1) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR1, HRTIM_FLTINR1_FLT1E, (Enable & HRTIM_FLTINR1_FLT1E));
}
if ((Faults & HRTIM_FAULT_2) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR1, HRTIM_FLTINR1_FLT2E, ((Enable << 8U) & HRTIM_FLTINR1_FLT2E));
}
if ((Faults & HRTIM_FAULT_3) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR1, HRTIM_FLTINR1_FLT3E, ((Enable << 16U) & HRTIM_FLTINR1_FLT3E));
}
if ((Faults & HRTIM_FAULT_4) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR1, HRTIM_FLTINR1_FLT4E, ((Enable << 24U) & HRTIM_FLTINR1_FLT4E));
}
if ((Faults & HRTIM_FAULT_5) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR2, HRTIM_FLTINR2_FLT5E, ((Enable) & HRTIM_FLTINR2_FLT5E));
}
if ((Faults & HRTIM_FAULT_6) != (uint32_t)RESET)
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.FLTINR2, HRTIM_FLTINR2_FLT6E, ((Enable << 8U) & HRTIM_FLTINR2_FLT6E));
}
}
/**
* @brief Configure both the ADC trigger register update source and the ADC
* trigger source.
* @param hhrtim pointer to HAL HRTIM handle
* @param ADCTrigger ADC trigger to configure
* This parameter can be one of the following values:
* @arg HRTIM_ADCTRIGGER_1: ADC trigger 1
* @arg HRTIM_ADCTRIGGER_2: ADC trigger 2
* @arg HRTIM_ADCTRIGGER_3: ADC trigger 3
* @arg HRTIM_ADCTRIGGER_4: ADC trigger 4
* @arg HRTIM_ADCTRIGGER_5: ADC trigger 5
* @arg HRTIM_ADCTRIGGER_6: ADC trigger 6
* @arg HRTIM_ADCTRIGGER_7: ADC trigger 7
* @arg HRTIM_ADCTRIGGER_8: ADC trigger 8
* @arg HRTIM_ADCTRIGGER_9: ADC trigger 9
* @arg HRTIM_ADCTRIGGER_10: ADC trigger 10
* @param pADCTriggerCfg pointer to the ADC trigger configuration structure
* for Trigger nb (1..4): pADCTriggerCfg->Trigger parameter
* can be a combination of the following values
* @arg HRTIM_ADCTRIGGEREVENT13_...
* @arg HRTIM_ADCTRIGGEREVENT24_...
* for Trigger nb (5..10): pADCTriggerCfg->Trigger parameter
* can be one of the following values
* @arg HRTIM_ADCTRIGGEREVENT579_...
* @arg HRTIM_ADCTRIGGEREVENT6810_...
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_ADCTriggerConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t ADCTrigger,
HRTIM_ADCTriggerCfgTypeDef* pADCTriggerCfg)
{
uint32_t hrtim_cr1;
uint32_t hrtim_adcur;
/* Check parameters */
assert_param(IS_HRTIM_ADCTRIGGER(ADCTrigger));
assert_param(IS_HRTIM_ADCTRIGGERUPDATE(pADCTriggerCfg->UpdateSource));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the ADC trigger update source */
hrtim_cr1 = hhrtim->Instance->sCommonRegs.CR1;
hrtim_adcur = hhrtim->Instance->sCommonRegs.ADCUR;
switch (ADCTrigger)
{
case HRTIM_ADCTRIGGER_1:
{
hrtim_cr1 &= ~(HRTIM_CR1_ADC1USRC);
hrtim_cr1 |= (pADCTriggerCfg->UpdateSource & HRTIM_CR1_ADC1USRC);
/* Set the ADC trigger 1 source */
hhrtim->Instance->sCommonRegs.ADC1R = pADCTriggerCfg->Trigger;
break;
}
case HRTIM_ADCTRIGGER_2:
{
hrtim_cr1 &= ~(HRTIM_CR1_ADC2USRC);
hrtim_cr1 |= ((pADCTriggerCfg->UpdateSource << 3U) & HRTIM_CR1_ADC2USRC);
/* Set the ADC trigger 2 source */
hhrtim->Instance->sCommonRegs.ADC2R = pADCTriggerCfg->Trigger;
break;
}
case HRTIM_ADCTRIGGER_3:
{
hrtim_cr1 &= ~(HRTIM_CR1_ADC3USRC);
hrtim_cr1 |= ((pADCTriggerCfg->UpdateSource << 6U) & HRTIM_CR1_ADC3USRC);
/* Set the ADC trigger 3 source */
hhrtim->Instance->sCommonRegs.ADC3R = pADCTriggerCfg->Trigger;
break;
}
case HRTIM_ADCTRIGGER_4:
{
hrtim_cr1 &= ~(HRTIM_CR1_ADC4USRC);
hrtim_cr1 |= ((pADCTriggerCfg->UpdateSource << 9U) & HRTIM_CR1_ADC4USRC);
/* Set the ADC trigger 4 source */
hhrtim->Instance->sCommonRegs.ADC4R = pADCTriggerCfg->Trigger;
break;
}
case HRTIM_ADCTRIGGER_5:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD5USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource >> 16U) & HRTIM_ADCUR_AD5USRC);
/* Set the ADC trigger 5 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD5TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD5TRG_Pos) & HRTIM_ADCER_AD5TRG);
break;
}
case HRTIM_ADCTRIGGER_6:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD6USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource >> 12U) & HRTIM_ADCUR_AD6USRC);
/* Set the ADC trigger 6 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD6TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD6TRG_Pos) & HRTIM_ADCER_AD6TRG);
break;
}
case HRTIM_ADCTRIGGER_7:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD7USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource >> 8U) & HRTIM_ADCUR_AD7USRC);
/* Set the ADC trigger 7 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD7TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD7TRG_Pos) & HRTIM_ADCER_AD7TRG);
break;
}
case HRTIM_ADCTRIGGER_8:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD8USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource >> 4U) & HRTIM_ADCUR_AD8USRC);
/* Set the ADC trigger 8 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD8TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD8TRG_Pos) & HRTIM_ADCER_AD8TRG);
break;
}
case HRTIM_ADCTRIGGER_9:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD9USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource) & HRTIM_ADCUR_AD9USRC);
/* Set the ADC trigger 9 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD9TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD9TRG_Pos) & HRTIM_ADCER_AD9TRG);
break;
}
case HRTIM_ADCTRIGGER_10:
{
hrtim_adcur &= ~(HRTIM_ADCUR_AD10USRC);
hrtim_adcur |= ((pADCTriggerCfg->UpdateSource << 4U) & HRTIM_ADCUR_AD10USRC);
/* Set the ADC trigger 10 source */
hhrtim->Instance->sCommonRegs.ADCER &= ~(HRTIM_ADCER_AD10TRG);
hhrtim->Instance->sCommonRegs.ADCER |= ((pADCTriggerCfg->Trigger << HRTIM_ADCER_AD10TRG_Pos) & HRTIM_ADCER_AD10TRG);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
/* Update the HRTIM registers */
if (ADCTrigger < HRTIM_ADCTRIGGER_5)
{
hhrtim->Instance->sCommonRegs.CR1 = hrtim_cr1;
}
else
{
hhrtim->Instance->sCommonRegs.ADCUR = hrtim_adcur;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the ADC trigger postscaler register of the ADC
* trigger source.
* @param hhrtim pointer to HAL HRTIM handle
* @param ADCTrigger ADC trigger to configure
* This parameter can be one of the following values:
* @arg HRTIM_ADCTRIGGER_1: ADC trigger 1
* @arg HRTIM_ADCTRIGGER_2: ADC trigger 2
* @arg HRTIM_ADCTRIGGER_3: ADC trigger 3
* @arg HRTIM_ADCTRIGGER_4: ADC trigger 4
* @arg HRTIM_ADCTRIGGER_5: ADC trigger 5
* @arg HRTIM_ADCTRIGGER_6: ADC trigger 6
* @arg HRTIM_ADCTRIGGER_7: ADC trigger 7
* @arg HRTIM_ADCTRIGGER_8: ADC trigger 8
* @arg HRTIM_ADCTRIGGER_9: ADC trigger 9
* @arg HRTIM_ADCTRIGGER_10: ADC trigger 10
* @param Postscaler value 0..1F
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_ADCPostScalerConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t ADCTrigger,
uint32_t Postscaler)
{
/* Check parameters */
assert_param(IS_HRTIM_ADCTRIGGER(ADCTrigger));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
switch (ADCTrigger)
{
case HRTIM_ADCTRIGGER_1:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS1, HRTIM_ADCPS1_AD1PSC, (Postscaler & HRTIM_ADCPS1_AD1PSC));
break;
}
case HRTIM_ADCTRIGGER_2:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS1, HRTIM_ADCPS1_AD2PSC, ((Postscaler << HRTIM_ADCPS1_AD2PSC_Pos) & HRTIM_ADCPS1_AD2PSC));
break;
}
case HRTIM_ADCTRIGGER_3:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS1, HRTIM_ADCPS1_AD3PSC, ((Postscaler << HRTIM_ADCPS1_AD3PSC_Pos) & HRTIM_ADCPS1_AD3PSC));
break;
}
case HRTIM_ADCTRIGGER_4:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS1, HRTIM_ADCPS1_AD4PSC, ((Postscaler << HRTIM_ADCPS1_AD4PSC_Pos) & HRTIM_ADCPS1_AD4PSC));
break;
}
case HRTIM_ADCTRIGGER_5:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS1, HRTIM_ADCPS1_AD5PSC, ((Postscaler << HRTIM_ADCPS1_AD5PSC_Pos) & HRTIM_ADCPS1_AD5PSC));
break;
}
case HRTIM_ADCTRIGGER_6:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS2, HRTIM_ADCPS2_AD6PSC, ((Postscaler << HRTIM_ADCPS2_AD6PSC_Pos) & HRTIM_ADCPS2_AD6PSC));
break;
}
case HRTIM_ADCTRIGGER_7:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS2, HRTIM_ADCPS2_AD7PSC, ((Postscaler << HRTIM_ADCPS2_AD7PSC_Pos) & HRTIM_ADCPS2_AD7PSC));
break;
}
case HRTIM_ADCTRIGGER_8:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS2, HRTIM_ADCPS2_AD8PSC, ((Postscaler << HRTIM_ADCPS2_AD8PSC_Pos) & HRTIM_ADCPS2_AD8PSC));
break;
}
case HRTIM_ADCTRIGGER_9:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS2, HRTIM_ADCPS2_AD9PSC, ((Postscaler << HRTIM_ADCPS2_AD9PSC_Pos) & HRTIM_ADCPS2_AD9PSC));
break;
}
case HRTIM_ADCTRIGGER_10:
{
MODIFY_REG(hhrtim->Instance->sCommonRegs.ADCPS2, HRTIM_ADCPS2_AD10PSC, ((Postscaler << HRTIM_ADCPS2_AD10PSC_Pos) & HRTIM_ADCPS2_AD10PSC));
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the ADC Roll-Over mode of the ADC
* trigger source.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param RollOverCfg This parameter can be a combination of all the following values:
* @arg HRTIM_TIM_FEROM_BOTH or HRTIM_TIM_FEROM_CREST or HRTIM_TIM_FEROM_VALLEY
* @arg HRTIM_TIM_BMROM_BOTH or HRTIM_TIM_BMROM_CREST or HRTIM_TIM_BMROM_VALLEY
* @arg HRTIM_TIM_ADROM_BOTH or HRTIM_TIM_ADROM_CREST or HRTIM_TIM_ADROM_VALLEY
* @arg HRTIM_TIM_OUTROM_BOTH or HRTIM_TIM_OUTROM_CREST or HRTIM_TIM_OUTROM_VALLEY
* @arg HRTIM_TIM_ROM_BOTH or HRTIM_TIM_ROM_CREST or HRTIM_TIM_ROM_VALLEY
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_RollOverModeConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t RollOverCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_ROLLOVERMODE(RollOverCfg));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
HRTIM_TimingUnitRollOver_Config(hhrtim,TimerIdx,RollOverCfg);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group8 Timer waveform configuration and functions
* @brief HRTIM timer configuration and control functions
@verbatim
===============================================================================
##### HRTIM timer configuration and control functions #####
===============================================================================
[..] This section provides functions used to configure and control a
HRTIM timer operating in waveform mode:
(+) Configure HRTIM timer general behavior
(+) Configure HRTIM timer event filtering
(+) Configure HRTIM timer deadtime insertion
(+) Configure HRTIM timer chopper mode
(+) Configure HRTIM timer burst DMA
(+) Configure HRTIM timer compare unit
(+) Configure HRTIM timer capture unit
(+) Configure HRTIM timer output
(+) Set HRTIM timer output level
(+) Enable HRTIM timer output
(+) Disable HRTIM timer output
(+) Start HRTIM timer
(+) Stop HRTIM timer
(+) Start HRTIM timer and enable interrupt
(+) Stop HRTIM timer and disable interrupt
(+) Start HRTIM timer and enable DMA transfer
(+) Stop HRTIM timer and disable DMA transfer
(+) Enable or disable the burst mode controller
(+) Start the burst mode controller (by software)
(+) Trigger a Capture (by software)
(+) Update the HRTIM timer preloadable registers (by software)
(+) Reset the HRTIM timer counter (by software)
(+) Start a burst DMA transfer
(+) Enable timer register update
(+) Disable timer register update
@endverbatim
* @{
*/
/**
* @brief Configure the general behavior of a timer operating in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pTimerCfg pointer to the timer configuration structure
* @note When the timer operates in waveform mode, all the features supported by
* the HRTIM are available without any limitation.
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformTimerConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCfgTypeDef * pTimerCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Relevant for all HRTIM timers, including the master */
assert_param(IS_HRTIM_HALFMODE(pTimerCfg->HalfModeEnable));
assert_param(IS_HRTIM_INTERLEAVEDMODE(pTimerCfg->InterleavedMode));
assert_param(IS_HRTIM_SYNCSTART(pTimerCfg->StartOnSync));
assert_param(IS_HRTIM_SYNCRESET(pTimerCfg->ResetOnSync));
assert_param(IS_HRTIM_DACSYNC(pTimerCfg->DACSynchro));
assert_param(IS_HRTIM_PRELOAD(pTimerCfg->PreloadEnable));
assert_param(IS_HRTIM_TIMERBURSTMODE(pTimerCfg->BurstMode));
assert_param(IS_HRTIM_UPDATEONREPETITION(pTimerCfg->RepetitionUpdate));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
/* Check parameters */
assert_param(IS_HRTIM_UPDATEGATING_MASTER(pTimerCfg->UpdateGating));
assert_param(IS_HRTIM_MASTER_IT(pTimerCfg->InterruptRequests));
assert_param(IS_HRTIM_MASTER_DMA(pTimerCfg->DMARequests));
/* Configure master timer */
HRTIM_MasterWaveform_Config(hhrtim, pTimerCfg);
}
else
{
/* Check parameters */
assert_param(IS_HRTIM_UPDATEGATING_TIM(pTimerCfg->UpdateGating));
assert_param(IS_HRTIM_TIM_IT(pTimerCfg->InterruptRequests));
assert_param(IS_HRTIM_TIM_DMA(pTimerCfg->DMARequests));
assert_param(IS_HRTIM_TIMPUSHPULLMODE(pTimerCfg->PushPull));
assert_param(IS_HRTIM_TIMFAULTENABLE(pTimerCfg->FaultEnable));
assert_param(IS_HRTIM_TIMFAULTLOCK(pTimerCfg->FaultLock));
assert_param(IS_HRTIM_TIMDEADTIMEINSERTION(pTimerCfg->PushPull,
pTimerCfg->DeadTimeInsertion));
assert_param(IS_HRTIM_TIMDELAYEDPROTECTION(pTimerCfg->PushPull,
pTimerCfg->DelayedProtectionMode));
assert_param(IS_HRTIM_OUTPUTBALANCEDIDLE(pTimerCfg->BalancedIdleAutomaticResume));
assert_param(IS_HRTIM_TIMUPDATETRIGGER(pTimerCfg->UpdateTrigger));
assert_param(IS_HRTIM_TIMRESETTRIGGER(pTimerCfg->ResetTrigger));
assert_param(IS_HRTIM_TIMUPDATEONRESET(pTimerCfg->ResetUpdate));
assert_param(IS_HRTIM_TIMSYNCUPDATE(pTimerCfg->ReSyncUpdate));
/* Configure timing unit */
HRTIM_TimingUnitWaveform_Config(hhrtim, TimerIdx, pTimerCfg);
}
/* Update timer parameters */
hhrtim->TimerParam[TimerIdx].InterruptRequests = pTimerCfg->InterruptRequests;
hhrtim->TimerParam[TimerIdx].DMARequests = pTimerCfg->DMARequests;
hhrtim->TimerParam[TimerIdx].DMASrcAddress = pTimerCfg->DMASrcAddress;
hhrtim->TimerParam[TimerIdx].DMADstAddress = pTimerCfg->DMADstAddress;
hhrtim->TimerParam[TimerIdx].DMASize = pTimerCfg->DMASize;
/* Force a software update */
HRTIM_ForceRegistersUpdate(hhrtim, TimerIdx);
/* Configure slave timer update re-synchronization */
if ((TimerIdx != HRTIM_TIMERINDEX_MASTER)
&& (pTimerCfg->UpdateGating == HRTIM_UPDATEGATING_INDEPENDENT))
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR,
HRTIM_TIMCR_RSYNCU_Msk,
pTimerCfg->ReSyncUpdate << HRTIM_TIMCR_RSYNCU_Pos);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the general behavior of a timer operating in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pTimerCtl pointer to the timer configuration structure
* @note When the timer operates in waveform mode, all the features supported by
* the HRTIM are available without any limitation.
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformTimerControl(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCtlTypeDef * pTimerCtl)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
/* Relevant for all A..F HRTIM timers */
assert_param(IS_HRTIM_TIMERUPDOWNMODE(pTimerCtl->UpDownMode));
assert_param(IS_HRTIM_TIMERTRGHLFMODE(pTimerCtl->TrigHalf));
assert_param(IS_HRTIM_TIMERGTCMP3(pTimerCtl->GreaterCMP3));
assert_param(IS_HRTIM_TIMERGTCMP1(pTimerCtl->GreaterCMP1));
assert_param(IS_HRTIM_DUALDAC_RESET(pTimerCtl->DualChannelDacReset));
assert_param(IS_HRTIM_DUALDAC_STEP(pTimerCtl->DualChannelDacStep));
assert_param(IS_HRTIM_DUALDAC_ENABLE(pTimerCtl->DualChannelDacEnable));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure timing unit */
HRTIM_TimingUnitWaveform_Control(hhrtim, TimerIdx, pTimerCtl);
/* Force a software update */
HRTIM_ForceRegistersUpdate(hhrtim, TimerIdx);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the Dual Channel Dac behavior of a timer operating in waveform mode
* @param hhrtim: pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pTimerCtl pointer to the timer DualChannel Dac configuration structure
* @note When the timer operates in waveform mode, all the features supported by
* the HRTIM are available without any limitation.
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_TimerDualChannelDacConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCtlTypeDef * pTimerCtl)
{
assert_param(IS_HRTIM_DUALDAC_RESET(pTimerCtl->DualChannelDacReset));
assert_param(IS_HRTIM_DUALDAC_STEP(pTimerCtl->DualChannelDacStep));
assert_param(IS_HRTIM_DUALDAC_ENABLE(pTimerCtl->DualChannelDacEnable));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* clear DCDS,DCDR,DCDE bits */
CLEAR_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2,
(HRTIM_TIMER_DCDE_ENABLED |
HRTIM_TIMER_DCDS_OUT1RST |
HRTIM_TIMER_DCDR_OUT1SET) );
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2 ,
(HRTIM_TIMER_DCDE_ENABLED |
HRTIM_TIMER_DCDS_OUT1RST |
HRTIM_TIMER_DCDR_OUT1SET),
(pTimerCtl->DualChannelDacReset |
pTimerCtl->DualChannelDacStep |
pTimerCtl->DualChannelDacEnable));
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the event filtering capabilities of a timer (blanking, windowing)
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Event external event for which timer event filtering must be configured
* This parameter can be one of the following values:
* @arg HRTIM_EVENT_1: External event 1
* @arg HRTIM_EVENT_2: External event 2
* @arg HRTIM_EVENT_3: External event 3
* @arg HRTIM_EVENT_4: External event 4
* @arg HRTIM_EVENT_5: External event 5
* @arg HRTIM_EVENT_6: External event 6
* @arg HRTIM_EVENT_7: External event 7
* @arg HRTIM_EVENT_8: External event 8
* @arg HRTIM_EVENT_9: External event 9
* @arg HRTIM_EVENT_10: External event 10
* @param pTimerEventFilteringCfg pointer to the timer event filtering configuration structure
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_TimerEventFilteringConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Event,
HRTIM_TimerEventFilteringCfgTypeDef* pTimerEventFilteringCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_EVENT(Event));
assert_param(IS_HRTIM_TIMEVENTFILTER(TimerIdx,pTimerEventFilteringCfg->Filter));
assert_param(IS_HRTIM_TIMEVENTLATCH(pTimerEventFilteringCfg->Latch));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure timer event filtering capabilities */
switch (Event)
{
case HRTIM_EVENT_NONE:
{
CLEAR_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1);
CLEAR_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2);
break;
}
case HRTIM_EVENT_1:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1, (HRTIM_EEFR1_EE1FLTR | HRTIM_EEFR1_EE1LTCH), (pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch));
break;
}
case HRTIM_EVENT_2:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1, (HRTIM_EEFR1_EE2FLTR | HRTIM_EEFR1_EE2LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 6U) );
break;
}
case HRTIM_EVENT_3:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1, (HRTIM_EEFR1_EE3FLTR | HRTIM_EEFR1_EE3LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 12U) );
break;
}
case HRTIM_EVENT_4:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1, (HRTIM_EEFR1_EE4FLTR | HRTIM_EEFR1_EE4LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 18U) );
break;
}
case HRTIM_EVENT_5:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR1, (HRTIM_EEFR1_EE5FLTR | HRTIM_EEFR1_EE5LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 24U) );
break;
}
case HRTIM_EVENT_6:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2, (HRTIM_EEFR2_EE6FLTR | HRTIM_EEFR2_EE6LTCH), (pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) );
break;
}
case HRTIM_EVENT_7:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2, (HRTIM_EEFR2_EE7FLTR | HRTIM_EEFR2_EE7LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 6U) );
break;
}
case HRTIM_EVENT_8:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2, (HRTIM_EEFR2_EE8FLTR | HRTIM_EEFR2_EE8LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 12U) );
break;
}
case HRTIM_EVENT_9:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2, (HRTIM_EEFR2_EE9FLTR | HRTIM_EEFR2_EE9LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 18U) );
break;
}
case HRTIM_EVENT_10:
{
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR2, (HRTIM_EEFR2_EE10FLTR | HRTIM_EEFR2_EE10LTCH), ((pTimerEventFilteringCfg->Filter | pTimerEventFilteringCfg->Latch) << 24U) );
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the external Event Counter A or B of a timer (source, threshold, reset mode)
* but does not enable : call HAL_HRTIM_ExternalEventCounterEnable afterwards
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param EventCounter external event Counter A or B for which timer event must be configured
* This parameter can be one of the following values:
* @arg HRTIM_EVENTCOUNTER_A
* @arg HRTIM_EVENTCOUNTER_B
* @param pTimerExternalEventCfg: pointer to the timer external event configuration structure
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_ExtEventCounterConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t EventCounter,
HRTIM_ExternalEventCfgTypeDef* pTimerExternalEventCfg)
{
uint32_t hrtim_eefr3;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_TIMEEVENT(EventCounter));
assert_param(IS_HRTIM_TIMEEVENT_RESETMODE(pTimerExternalEventCfg->ResetMode));
assert_param(IS_HRTIM_TIMEEVENT_COUNTER(pTimerExternalEventCfg->Counter));
assert_param(IS_HRTIM_EVENT(pTimerExternalEventCfg->Source));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if ((EventCounter & HRTIM_EVENTCOUNTER_A) != 0U)
{
if (pTimerExternalEventCfg->Source == HRTIM_EVENT_NONE)
{ /* reset External EventCounter A */
WRITE_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, 0xFFFF0000U);
}
else
{
/* Set timer External EventCounter A configuration */
hrtim_eefr3 = (pTimerExternalEventCfg->ResetMode) << HRTIM_EEFR3_EEVARSTM_Pos;
hrtim_eefr3 |= ((pTimerExternalEventCfg->Source - 1U)) << HRTIM_EEFR3_EEVASEL_Pos;
hrtim_eefr3 |= (pTimerExternalEventCfg->Counter) << HRTIM_EEFR3_EEVACNT_Pos;
/* do not enable, use HAL_HRTIM_TimerExternalEventEnable function */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, (HRTIM_EEFR3_EEVARSTM | HRTIM_EEFR3_EEVASEL | HRTIM_EEFR3_EEVACNT) , hrtim_eefr3 );
}
}
if ((EventCounter & HRTIM_EVENTCOUNTER_B) != 0U)
{
if (pTimerExternalEventCfg->Source == HRTIM_EVENT_NONE)
{ /* reset External EventCounter B */
WRITE_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, 0x0000FFFFU);
}
else
{
/* Set timer External EventCounter B configuration */
hrtim_eefr3 = (pTimerExternalEventCfg->ResetMode) << HRTIM_EEFR3_EEVBRSTM_Pos;
hrtim_eefr3 |= ((pTimerExternalEventCfg->Source - 1U)) << HRTIM_EEFR3_EEVBSEL_Pos;
hrtim_eefr3 |= (pTimerExternalEventCfg->Counter) << HRTIM_EEFR3_EEVBCNT_Pos;
/* do not enable, use HAL_HRTIM_TimerExternalEventEnable function */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, (HRTIM_EEFR3_EEVBRSTM | HRTIM_EEFR3_EEVBSEL | HRTIM_EEFR3_EEVBCNT) , hrtim_eefr3 );
}
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable the external event Counter A or B of a timer
* @param hhrtim: pointer to HAL HRTIM handle
* @param TimerIdx: Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param EventCounter external Event Counter A or B for which timer event must be configured
* This parameter can be a one of the following values:
* @arg HRTIM_EVENTCOUNTER_A
* @arg HRTIM_EVENTCOUNTER_B
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_ExtEventCounterEnable(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t EventCounter)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_TIMEEVENT(EventCounter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if ((EventCounter & HRTIM_EVENTCOUNTER_A) != 0U)
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, HRTIM_EEFR3_EEVACE);
}
if ((EventCounter & HRTIM_EVENTCOUNTER_B) != 0U)
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, HRTIM_EEFR3_EEVBCE);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable the external event Counter A or B of a timer
* @param hhrtim: pointer to HAL HRTIM handle
* @param TimerIdx: Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param EventCounter external event Counter A or B for which timer event must be configured
* This parameter can be a one of the following values:
* @arg HRTIM_EVENTCOUNTER_A
* @arg HRTIM_EVENTCOUNTER_B
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_ExtEventCounterDisable(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t EventCounter)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_TIMEEVENT(EventCounter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if ((EventCounter & HRTIM_EVENTCOUNTER_A) != 0U)
{
CLEAR_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, HRTIM_EEFR3_EEVACE);
}
if ((EventCounter & HRTIM_EVENTCOUNTER_B) != 0U)
{
CLEAR_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, HRTIM_EEFR3_EEVBCE);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Reset the external event Counter A or B of a timer
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param EventCounter external event Counter A or B for which timer event must be configured
* This parameter can be one of the following values:
* @arg HRTIM_EVENTCOUNTER_A
* @arg HRTIM_EVENTCOUNTER_B
* @note This function must be called before starting the timer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_ExtEventCounterReset(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t EventCounter)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_TIMEEVENT(EventCounter));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if ((EventCounter & HRTIM_EVENTCOUNTER_A) != 0U)
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3, HRTIM_EEFR3_EEVACRES);
}
if ((EventCounter & HRTIM_EVENTCOUNTER_B) != 0U)
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].EEFxR3,HRTIM_EEFR3_EEVBCRES);
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the dead-time insertion feature for a timer
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pDeadTimeCfg pointer to the deadtime insertion configuration structure
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_DeadTimeConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_DeadTimeCfgTypeDef* pDeadTimeCfg)
{
uint32_t hrtim_dtr;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_TIMDEADTIME_PRESCALERRATIO(pDeadTimeCfg->Prescaler));
assert_param(IS_HRTIM_TIMDEADTIME_RISINGSIGN(pDeadTimeCfg->RisingSign));
assert_param(IS_HRTIM_TIMDEADTIME_RISINGLOCK(pDeadTimeCfg->RisingLock));
assert_param(IS_HRTIM_TIMDEADTIME_RISINGSIGNLOCK(pDeadTimeCfg->RisingSignLock));
assert_param(IS_HRTIM_TIMDEADTIME_FALLINGSIGN(pDeadTimeCfg->FallingSign));
assert_param(IS_HRTIM_TIMDEADTIME_FALLINGLOCK(pDeadTimeCfg->FallingLock));
assert_param(IS_HRTIM_TIMDEADTIME_FALLINGSIGNLOCK(pDeadTimeCfg->FallingSignLock));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set timer deadtime configuration */
hrtim_dtr = (pDeadTimeCfg->Prescaler & HRTIM_DTR_DTPRSC);
hrtim_dtr |= (pDeadTimeCfg->RisingValue & HRTIM_DTR_DTR);
hrtim_dtr |= (pDeadTimeCfg->RisingSign & HRTIM_DTR_SDTR);
hrtim_dtr |= (pDeadTimeCfg->RisingSignLock & HRTIM_DTR_DTRSLK);
hrtim_dtr |= (pDeadTimeCfg->RisingLock & HRTIM_DTR_DTRLK);
hrtim_dtr |= ((pDeadTimeCfg->FallingValue << 16U) & HRTIM_DTR_DTF);
hrtim_dtr |= (pDeadTimeCfg->FallingSign & HRTIM_DTR_SDTF);
hrtim_dtr |= (pDeadTimeCfg->FallingSignLock & HRTIM_DTR_DTFSLK);
hrtim_dtr |= (pDeadTimeCfg->FallingLock & HRTIM_DTR_DTFLK);
/* Update the HRTIM registers */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].DTxR, (
HRTIM_DTR_DTR | HRTIM_DTR_SDTR | HRTIM_DTR_DTPRSC |
HRTIM_DTR_DTRSLK | HRTIM_DTR_DTRLK | HRTIM_DTR_DTF |
HRTIM_DTR_SDTF | HRTIM_DTR_DTFSLK | HRTIM_DTR_DTFLK), hrtim_dtr);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the chopper mode feature for a timer
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param pChopperModeCfg pointer to the chopper mode configuration structure
* @retval HAL status
* @note This function must be called before configuring the timer output(s)
*/
HAL_StatusTypeDef HAL_HRTIM_ChopperModeConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_ChopperModeCfgTypeDef* pChopperModeCfg)
{
uint32_t hrtim_chpr;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CHOPPER_PRESCALERRATIO(pChopperModeCfg->CarrierFreq));
assert_param(IS_HRTIM_CHOPPER_DUTYCYCLE(pChopperModeCfg->DutyCycle));
assert_param(IS_HRTIM_CHOPPER_PULSEWIDTH(pChopperModeCfg->StartPulse));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set timer choppe mode configuration */
hrtim_chpr = (pChopperModeCfg->CarrierFreq & HRTIM_CHPR_CARFRQ);
hrtim_chpr |= (pChopperModeCfg->DutyCycle & HRTIM_CHPR_CARDTY);
hrtim_chpr |= (pChopperModeCfg->StartPulse & HRTIM_CHPR_STRPW);
/* Update the HRTIM registers */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].CHPxR, (HRTIM_CHPR_CARFRQ | HRTIM_CHPR_CARDTY |
HRTIM_CHPR_STRPW) ,
hrtim_chpr);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the burst DMA controller for a timer
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param RegistersToUpdate registers to be written by DMA
* This parameter can be any combination of the following values:
* @arg HRTIM_BURSTDMA_CR: HRTIM_MCR or HRTIM_TIMxCR
* @arg HRTIM_BURSTDMA_ICR: HRTIM_MICR or HRTIM_TIMxICR
* @arg HRTIM_BURSTDMA_DIER: HRTIM_MDIER or HRTIM_TIMxDIER
* @arg HRTIM_BURSTDMA_CNT: HRTIM_MCNT or HRTIM_TIMxCNT
* @arg HRTIM_BURSTDMA_PER: HRTIM_MPER or HRTIM_TIMxPER
* @arg HRTIM_BURSTDMA_REP: HRTIM_MREP or HRTIM_TIMxREP
* @arg HRTIM_BURSTDMA_CMP1: HRTIM_MCMP1 or HRTIM_TIMxCMP1
* @arg HRTIM_BURSTDMA_CMP2: HRTIM_MCMP2 or HRTIM_TIMxCMP2
* @arg HRTIM_BURSTDMA_CMP3: HRTIM_MCMP3 or HRTIM_TIMxCMP3
* @arg HRTIM_BURSTDMA_CMP4: HRTIM_MCMP4 or HRTIM_TIMxCMP4
* @arg HRTIM_BURSTDMA_DTR: HRTIM_TIMxDTR
* @arg HRTIM_BURSTDMA_SET1R: HRTIM_TIMxSET1R
* @arg HRTIM_BURSTDMA_RST1R: HRTIM_TIMxRST1R
* @arg HRTIM_BURSTDMA_SET2R: HRTIM_TIMxSET2R
* @arg HRTIM_BURSTDMA_RST2R: HRTIM_TIMxRST2R
* @arg HRTIM_BURSTDMA_EEFR1: HRTIM_TIMxEEFR1
* @arg HRTIM_BURSTDMA_EEFR2: HRTIM_TIMxEEFR2
* @arg HRTIM_BURSTDMA_RSTR: HRTIM_TIMxRSTR
* @arg HRTIM_BURSTDMA_CHPR: HRTIM_TIMxCHPR
* @arg HRTIM_BURSTDMA_OUTR: HRTIM_TIMxOUTR
* @arg HRTIM_BURSTDMA_FLTR: HRTIM_TIMxFLTR
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_BurstDMAConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t RegistersToUpdate)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMER_BURSTDMA(TimerIdx, RegistersToUpdate));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Set the burst DMA timer update register */
switch (TimerIdx)
{
case HRTIM_TIMERINDEX_TIMER_A:
{
hhrtim->Instance->sCommonRegs.BDTAUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_TIMER_B:
{
hhrtim->Instance->sCommonRegs.BDTBUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_TIMER_C:
{
hhrtim->Instance->sCommonRegs.BDTCUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_TIMER_D:
{
hhrtim->Instance->sCommonRegs.BDTDUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_TIMER_E:
{
hhrtim->Instance->sCommonRegs.BDTEUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_TIMER_F:
{
hhrtim->Instance->sCommonRegs.BDTFUPR = RegistersToUpdate;
break;
}
case HRTIM_TIMERINDEX_MASTER:
{
hhrtim->Instance->sCommonRegs.BDMUPR = RegistersToUpdate;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the compare unit of a timer operating in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CompareUnit Compare unit to configure
* This parameter can be one of the following values:
* @arg HRTIM_COMPAREUNIT_1: Compare unit 1
* @arg HRTIM_COMPAREUNIT_2: Compare unit 2
* @arg HRTIM_COMPAREUNIT_3: Compare unit 3
* @arg HRTIM_COMPAREUNIT_4: Compare unit 4
* @param pCompareCfg pointer to the compare unit configuration structure
* @note When auto delayed mode is required for compare unit 2 or compare unit 4,
* application has to configure separately the capture unit. Capture unit
* to configure in that case depends on the compare unit auto delayed mode
* is applied to (see below):
* Auto delayed on output compare 2: capture unit 1 must be configured
* Auto delayed on output compare 4: capture unit 2 must be configured
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCompareConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CompareUnit,
HRTIM_CompareCfgTypeDef* pCompareCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure the compare unit */
if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
switch (CompareUnit)
{
case HRTIM_COMPAREUNIT_1:
{
hhrtim->Instance->sMasterRegs.MCMP1R = pCompareCfg->CompareValue;
break;
}
case HRTIM_COMPAREUNIT_2:
{
hhrtim->Instance->sMasterRegs.MCMP2R = pCompareCfg->CompareValue;
break;
}
case HRTIM_COMPAREUNIT_3:
{
hhrtim->Instance->sMasterRegs.MCMP3R = pCompareCfg->CompareValue;
break;
}
case HRTIM_COMPAREUNIT_4:
{
hhrtim->Instance->sMasterRegs.MCMP4R = pCompareCfg->CompareValue;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
}
else
{
switch (CompareUnit)
{
case HRTIM_COMPAREUNIT_1:
{
/* Set the compare value */
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pCompareCfg->CompareValue;
break;
}
case HRTIM_COMPAREUNIT_2:
{
/* Check parameters */
assert_param(IS_HRTIM_COMPAREUNIT_AUTODELAYEDMODE(CompareUnit, pCompareCfg->AutoDelayedMode));
/* Set the compare value */
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP2xR = pCompareCfg->CompareValue;
if (pCompareCfg->AutoDelayedMode != HRTIM_AUTODELAYEDMODE_REGULAR)
{
/* Configure auto-delayed mode */
/* DELCMP2 bitfield must be reset when reprogrammed from one value */
/* to the other to reinitialize properly the auto-delayed mechanism */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR &= ~HRTIM_TIMCR_DELCMP2;
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR |= pCompareCfg->AutoDelayedMode;
/* Set the compare value for timeout compare unit (if any) */
if (pCompareCfg->AutoDelayedMode == HRTIM_AUTODELAYEDMODE_AUTODELAYED_TIMEOUTCMP1)
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pCompareCfg->AutoDelayedTimeout;
}
else if (pCompareCfg->AutoDelayedMode == HRTIM_AUTODELAYEDMODE_AUTODELAYED_TIMEOUTCMP3)
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP3xR = pCompareCfg->AutoDelayedTimeout;
}
else
{
/* nothing to do */
}
}
else
{
/* Clear HRTIM_TIMxCR.DELCMP2 bitfield */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR, HRTIM_TIMCR_DELCMP2, 0U);
}
break;
}
case HRTIM_COMPAREUNIT_3:
{
/* Set the compare value */
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP3xR = pCompareCfg->CompareValue;
break;
}
case HRTIM_COMPAREUNIT_4:
{
/* Check parameters */
assert_param(IS_HRTIM_COMPAREUNIT_AUTODELAYEDMODE(CompareUnit, pCompareCfg->AutoDelayedMode));
/* Set the compare value */
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP4xR = pCompareCfg->CompareValue;
if (pCompareCfg->AutoDelayedMode != HRTIM_AUTODELAYEDMODE_REGULAR)
{
/* Configure auto-delayed mode */
/* DELCMP4 bitfield must be reset when reprogrammed from one value */
/* to the other to reinitialize properly the auto-delayed mechanism */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR &= ~HRTIM_TIMCR_DELCMP4;
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR |= (pCompareCfg->AutoDelayedMode << 2U);
/* Set the compare value for timeout compare unit (if any) */
if (pCompareCfg->AutoDelayedMode == HRTIM_AUTODELAYEDMODE_AUTODELAYED_TIMEOUTCMP1)
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP1xR = pCompareCfg->AutoDelayedTimeout;
}
else if (pCompareCfg->AutoDelayedMode == HRTIM_AUTODELAYEDMODE_AUTODELAYED_TIMEOUTCMP3)
{
hhrtim->Instance->sTimerxRegs[TimerIdx].CMP3xR = pCompareCfg->AutoDelayedTimeout;
}
else
{
/* nothing to do */
}
}
else
{
/* Clear HRTIM_TIMxCR.DELCMP4 bitfield */
MODIFY_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR, HRTIM_TIMCR_DELCMP4, 0U);
}
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the capture unit of a timer operating in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureUnit Capture unit to configure
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @param pCaptureCfg pointer to the compare unit configuration structure
* @retval HAL status
* @note This function must be called before starting the timer
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCaptureConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit,
HRTIM_CaptureCfgTypeDef* pCaptureCfg)
{
uint32_t Trigger;
uint32_t TimerF_Trigger = (uint32_t)(pCaptureCfg->Trigger >> 32);
/* Check parameters */
assert_param(IS_HRTIM_TIMER_CAPTURETRIGGER(TimerIdx, (uint32_t)(pCaptureCfg->Trigger)));
assert_param(IS_HRTIM_TIMER_CAPTUREFTRIGGER(TimerIdx, TimerF_Trigger));
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* TimerF_Trigger is valid for setting other Timers than Timer F */
if (TimerIdx == HRTIM_TIMERINDEX_TIMER_A)
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0xFFFF0FFFU) | ( (TimerF_Trigger ) << HRTIM_CPT1CR_TA1SET_Pos ); }
else if (TimerIdx == HRTIM_TIMERINDEX_TIMER_B)
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0xFFF0FFFFU) | ( (TimerF_Trigger ) << HRTIM_CPT1CR_TB1SET_Pos ); }
else if (TimerIdx == HRTIM_TIMERINDEX_TIMER_C)
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0xFF0FFFFFU) | ( (TimerF_Trigger ) << HRTIM_CPT1CR_TC1SET_Pos ); }
else if (TimerIdx == HRTIM_TIMERINDEX_TIMER_D)
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0xF0FFFFFFU) | ( (TimerF_Trigger ) << HRTIM_CPT1CR_TD1SET_Pos ); }
else if (TimerIdx == HRTIM_TIMERINDEX_TIMER_E)
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0x0FFFFFFFU) | ( (TimerF_Trigger ) << HRTIM_CPT1CR_TE1SET_Pos ); }
else
{ Trigger = ((uint32_t)(pCaptureCfg->Trigger) & 0xFFFFFFFFU); }
/* for setting source capture on Timer F, use Trigger only (all bits are valid then) */
/* Configure the capture unit */
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
{
WRITE_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR, Trigger);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
WRITE_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR, Trigger);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Configure the output of a timer operating in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Output Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param pOutputCfg pointer to the timer output configuration structure
* @retval HAL status
* @note This function must be called before configuring the timer and after
* configuring the deadtime insertion feature (if required).
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformOutputConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output,
HRTIM_OutputCfgTypeDef * pOutputCfg)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, Output));
assert_param(IS_HRTIM_OUTPUTPOLARITY(pOutputCfg->Polarity));
assert_param(IS_HRTIM_OUTPUTIDLELEVEL(pOutputCfg->IdleLevel));
assert_param(IS_HRTIM_OUTPUTIDLEMODE(pOutputCfg->IdleMode));
assert_param(IS_HRTIM_OUTPUTFAULTLEVEL(pOutputCfg->FaultLevel));
assert_param(IS_HRTIM_OUTPUTCHOPPERMODE(pOutputCfg->ChopperModeEnable));
assert_param(IS_HRTIM_OUTPUTBURSTMODEENTRY(pOutputCfg->BurstModeEntryDelayed));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Configure the timer output */
HRTIM_OutputConfig(hhrtim,
TimerIdx,
Output,
pOutputCfg);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Force the timer output to its active or inactive state
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Output Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @param OutputLevel indicates whether the output is forced to its active or inactive level
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUTLEVEL_ACTIVE: output is forced to its active level
* @arg HRTIM_OUTPUTLEVEL_INACTIVE: output is forced to its inactive level
* @retval HAL status
* @note The 'software set/reset trigger' bit in the output set/reset registers
* is automatically reset by hardware
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformSetOutputLevel(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output,
uint32_t OutputLevel)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, Output));
assert_param(IS_HRTIM_OUTPUTLEVEL(OutputLevel));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer output level */
switch (Output)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
if (OutputLevel == HRTIM_OUTPUTLEVEL_ACTIVE)
{
/* Force output to its active state */
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].SETx1R,HRTIM_SET1R_SST);
}
else
{
/* Force output to its inactive state */
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx1R, HRTIM_RST1R_SRT);
}
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
if (OutputLevel == HRTIM_OUTPUTLEVEL_ACTIVE)
{
/* Force output to its active state */
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].SETx2R, HRTIM_SET2R_SST);
}
else
{
/* Force output to its inactive state */
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx2R, HRTIM_RST2R_SRT);
}
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable the generation of the waveform signal on the designated output(s)
* Outputs can be combined (ORed) to allow for simultaneous output enabling.
* @param hhrtim pointer to HAL HRTIM handle
* @param OutputsToStart Timer output(s) to enable
* This parameter can be any combination of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformOutputStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t OutputsToStart)
{
/* Check the parameters */
assert_param(IS_HRTIM_OUTPUT(OutputsToStart));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the HRTIM outputs */
hhrtim->Instance->sCommonRegs.OENR |= (OutputsToStart);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable the generation of the waveform signal on the designated output(s)
* Outputs can be combined (ORed) to allow for simultaneous output disabling.
* @param hhrtim pointer to HAL HRTIM handle
* @param OutputsToStop Timer output(s) to disable
* This parameter can be any combination of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformOutputStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t OutputsToStop)
{
/* Check the parameters */
assert_param(IS_HRTIM_OUTPUT(OutputsToStop));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable the HRTIM outputs */
hhrtim->Instance->sCommonRegs.ODISR |= (OutputsToStop);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter start.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to start
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStart(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable timer(s) counter */
hhrtim->Instance->sMasterRegs.MCR |= (Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter stop.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to stop
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @retval HAL status
* @note The counter of a timer is stopped only if all timer outputs are disabled
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStop(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable timer(s) counter */
hhrtim->Instance->sMasterRegs.MCR &= ~(Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter start.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to start
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @note HRTIM interrupts (e.g. faults interrupts) and interrupts related
* to the timers to start are enabled within this function.
* Interrupts to enable are selected through HAL_HRTIM_WaveformTimerConfig
* function.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStart_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
uint8_t timer_idx;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable HRTIM interrupts (if required) */
__HAL_HRTIM_ENABLE_IT(hhrtim, hhrtim->Init.HRTIMInterruptResquests);
/* Enable master timer related interrupts (if required) */
if ((Timers & HRTIM_TIMERID_MASTER) != 0U)
{
__HAL_HRTIM_MASTER_ENABLE_IT(hhrtim,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].InterruptRequests);
}
/* Enable timing unit related interrupts (if required) */
for (timer_idx = HRTIM_TIMERINDEX_TIMER_A ;
timer_idx < HRTIM_TIMERINDEX_MASTER ;
timer_idx++)
{
if ((Timers & TimerIdxToTimerId[timer_idx]) != 0U)
{
__HAL_HRTIM_TIMER_ENABLE_IT(hhrtim,
timer_idx,
hhrtim->TimerParam[timer_idx].InterruptRequests);
}
}
/* Enable timer(s) counter */
hhrtim->Instance->sMasterRegs.MCR |= (Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;}
/**
* @brief Stop the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter stop.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to stop
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @retval HAL status
* @note The counter of a timer is stopped only if all timer outputs are disabled
* @note All enabled timer related interrupts are disabled.
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStop_IT(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* ++ WA */
__IO uint32_t delai = (uint32_t)(0x17FU);
/* -- WA */
uint8_t timer_idx;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Disable HRTIM interrupts (if required) */
__HAL_HRTIM_DISABLE_IT(hhrtim, hhrtim->Init.HRTIMInterruptResquests);
/* Disable master timer related interrupts (if required) */
if ((Timers & HRTIM_TIMERID_MASTER) != 0U)
{
/* Interrupts enable flag must be cleared one by one */
__HAL_HRTIM_MASTER_DISABLE_IT(hhrtim, hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].InterruptRequests);
}
/* Disable timing unit related interrupts (if required) */
for (timer_idx = HRTIM_TIMERINDEX_TIMER_A ;
timer_idx < HRTIM_TIMERINDEX_MASTER ;
timer_idx++)
{
if ((Timers & TimerIdxToTimerId[timer_idx]) != 0U)
{
__HAL_HRTIM_TIMER_DISABLE_IT(hhrtim, timer_idx, hhrtim->TimerParam[timer_idx].InterruptRequests);
}
}
/* ++ WA */
do { delai--; } while (delai != 0U);
/* -- WA */
/* Disable timer(s) counter */
hhrtim->Instance->sMasterRegs.MCR &= ~(Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter start.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to start
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @retval HAL status
* @note This function enables the dma request(s) mentioned in the timer
* configuration data structure for every timers to start.
* @note The source memory address, the destination memory address and the
* size of each DMA transfer are specified at timer configuration time
* (see HAL_HRTIM_WaveformTimerConfig)
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStart_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
uint8_t timer_idx;
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Process Locked */
__HAL_LOCK(hhrtim);
if (((Timers & HRTIM_TIMERID_MASTER) != (uint32_t)RESET) &&
(hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMARequests != 0U))
{
/* Set the DMA error callback */
hhrtim->hdmaMaster->XferErrorCallback = HRTIM_DMAError ;
/* Set the DMA transfer completed callback */
hhrtim->hdmaMaster->XferCpltCallback = HRTIM_DMAMasterCplt;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hhrtim->hdmaMaster,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMASrcAddress,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMADstAddress,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMASize) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Enable the timer DMA request */
__HAL_HRTIM_MASTER_ENABLE_DMA(hhrtim,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMARequests);
}
for (timer_idx = HRTIM_TIMERINDEX_TIMER_A ;
timer_idx < HRTIM_TIMERINDEX_MASTER ;
timer_idx++)
{
if (((Timers & TimerIdxToTimerId[timer_idx]) != (uint32_t)RESET) &&
(hhrtim->TimerParam[timer_idx].DMARequests != 0U))
{
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, timer_idx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Set the DMA transfer completed callback */
hdma->XferCpltCallback = HRTIM_DMATimerxCplt;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma,
hhrtim->TimerParam[timer_idx].DMASrcAddress,
hhrtim->TimerParam[timer_idx].DMADstAddress,
hhrtim->TimerParam[timer_idx].DMASize) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Enable the timer DMA request */
__HAL_HRTIM_TIMER_ENABLE_DMA(hhrtim,
timer_idx,
hhrtim->TimerParam[timer_idx].DMARequests);
}
}
/* Enable the timer counter */
__HAL_HRTIM_ENABLE(hhrtim, Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Stop the counter of the designated timer(s) operating in waveform mode
* Timers can be combined (ORed) to allow for simultaneous counter stop.
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer counter(s) to stop
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERID_MASTER
* @arg HRTIM_TIMERID_TIMER_A
* @arg HRTIM_TIMERID_TIMER_B
* @arg HRTIM_TIMERID_TIMER_C
* @arg HRTIM_TIMERID_TIMER_D
* @arg HRTIM_TIMERID_TIMER_E
* @arg HRTIM_TIMERID_TIMER_F
* @retval HAL status
* @note The counter of a timer is stopped only if all timer outputs are disabled
* @note All enabled timer related DMA requests are disabled.
*/
HAL_StatusTypeDef HAL_HRTIM_WaveformCountStop_DMA(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
uint8_t timer_idx;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERID(Timers));
hhrtim->State = HAL_HRTIM_STATE_BUSY;
if (((Timers & HRTIM_TIMERID_MASTER) != 0U) &&
(hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMARequests != 0U))
{
/* Disable the DMA */
if (HAL_DMA_Abort(hhrtim->hdmaMaster) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Disable the DMA request(s) */
__HAL_HRTIM_MASTER_DISABLE_DMA(hhrtim,
hhrtim->TimerParam[HRTIM_TIMERINDEX_MASTER].DMARequests);
}
}
for (timer_idx = HRTIM_TIMERINDEX_TIMER_A ;
timer_idx < HRTIM_TIMERINDEX_MASTER ;
timer_idx++)
{
if (((Timers & TimerIdxToTimerId[timer_idx]) != 0U) &&
(hhrtim->TimerParam[timer_idx].DMARequests != 0U))
{
/* Get the timer DMA handler */
/* Disable the DMA */
if (HAL_DMA_Abort(HRTIM_GetDMAHandleFromTimerIdx(hhrtim, timer_idx)) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Disable the DMA request(s) */
__HAL_HRTIM_TIMER_DISABLE_DMA(hhrtim,
timer_idx,
hhrtim->TimerParam[timer_idx].DMARequests);
}
}
}
/* Disable the timer counter */
__HAL_HRTIM_DISABLE(hhrtim, Timers);
if (hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
else
{
return HAL_OK;
}
}
/**
* @brief Enable or disables the HRTIM burst mode controller.
* @param hhrtim pointer to HAL HRTIM handle
* @param Enable Burst mode controller enabling
* This parameter can be one of the following values:
* @arg HRTIM_BURSTMODECTL_ENABLED: Burst mode enabled
* @arg HRTIM_BURSTMODECTL_DISABLED: Burst mode disabled
* @retval HAL status
* @note This function must be called after starting the timer(s)
*/
HAL_StatusTypeDef HAL_HRTIM_BurstModeCtl(HRTIM_HandleTypeDef * hhrtim,
uint32_t Enable)
{
/* Check parameters */
assert_param(IS_HRTIM_BURSTMODECTL(Enable));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable/Disable the burst mode controller */
MODIFY_REG(hhrtim->Instance->sCommonRegs.BMCR, HRTIM_BMCR_BME, Enable);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Trig the burst mode operation.
* @param hhrtim pointer to HAL HRTIM handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_BurstModeSoftwareTrigger(HRTIM_HandleTypeDef *hhrtim)
{
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Software trigger of the burst mode controller */
SET_BIT(hhrtim->Instance->sCommonRegs.BMTRGR, HRTIM_BMTRGR_SW);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Trig a software capture on the designed capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureUnit Capture unit to trig
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval HAL status
* @note The 'software capture' bit in the capure configuration register is
* automatically reset by hardware
*/
HAL_StatusTypeDef HAL_HRTIM_SoftwareCapture(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureUnit));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force a software capture on concerned capture unit */
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xCR, HRTIM_CPT1CR_SWCPT);
break;
}
case HRTIM_CAPTUREUNIT_2:
{
SET_BIT(hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xCR, HRTIM_CPT2CR_SWCPT);
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Trig the update of the registers of one or several timers
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers timers concerned with the software register update
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERUPDATE_MASTER
* @arg HRTIM_TIMERUPDATE_A
* @arg HRTIM_TIMERUPDATE_B
* @arg HRTIM_TIMERUPDATE_C
* @arg HRTIM_TIMERUPDATE_D
* @arg HRTIM_TIMERUPDATE_E
* @arg HRTIM_TIMERUPDATE_F
* @retval HAL status
* @note The 'software update' bits in the HRTIM control register 2 register are
* automatically reset by hardware
*/
HAL_StatusTypeDef HAL_HRTIM_SoftwareUpdate(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERUPDATE(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR2 |= Timers;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Swap the Timer outputs
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers timers concerned with the software register update
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERSWAP_A
* @arg HRTIM_TIMERSWAP_B
* @arg HRTIM_TIMERSWAP_C
* @arg HRTIM_TIMERSWAP_D
* @arg HRTIM_TIMERSWAP_E
* @arg HRTIM_TIMERSWAP_F
* @retval HAL status
* @note The function is not significant when the Push-pull mode is enabled (PSHPLL = 1)
*/
HAL_StatusTypeDef HAL_HRTIM_SwapTimerOutput(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERSWAP(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR2 |= Timers;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Trig the reset of one or several timers
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers timers concerned with the software counter reset
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERRESET_MASTER
* @arg HRTIM_TIMERRESET_TIMER_A
* @arg HRTIM_TIMERRESET_TIMER_B
* @arg HRTIM_TIMERRESET_TIMER_C
* @arg HRTIM_TIMERRESET_TIMER_D
* @arg HRTIM_TIMERRESET_TIMER_E
* @arg HRTIM_TIMERRESET_TIMER_F
* @retval HAL status
* @note The 'software reset' bits in the HRTIM control register 2 are
* automatically reset by hardware
*/
HAL_StatusTypeDef HAL_HRTIM_SoftwareReset(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERRESET(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer(s) registers reset */
hhrtim->Instance->sCommonRegs.CR2 = Timers;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Swap the output of one or several timers
* @param hhrtim: pointer to HAL HRTIM handle
* @param Timers: timers concerned with the software register update
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERSWAP_A
* @arg HRTIM_TIMERSWAP_B
* @arg HRTIM_TIMERSWAP_C
* @arg HRTIM_TIMERSWAP_D
* @arg HRTIM_TIMERSWAP_E
* @arg HRTIM_TIMERSWAP_F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_OutputSwapEnable(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERSWAP(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR2 |= Timers;
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Un-swap the output of one or several timers
* @param hhrtim: pointer to HAL HRTIM handle
* @param Timers: timers concerned with the software register update
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERSWAP_A
* @arg HRTIM_TIMERSWAP_B
* @arg HRTIM_TIMERSWAP_C
* @arg HRTIM_TIMERSWAP_D
* @arg HRTIM_TIMERSWAP_E
* @arg HRTIM_TIMERSWAP_F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_OutputSwapDisable(HRTIM_HandleTypeDef * hhrtim,
uint32_t Timers)
{
/* Check parameters */
assert_param(IS_HRTIM_TIMERSWAP(Timers));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Force timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR2 &= ~(Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Start a burst DMA operation to update HRTIM control registers content
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param BurstBufferAddress address of the buffer the HRTIM control registers
* content will be updated from.
* @param BurstBufferLength size (in WORDS) of the burst buffer.
* @retval HAL status
* @note The TimerIdx parameter determines the dma channel to be used by the
* DMA burst controller (see below)
* HRTIM_TIMERINDEX_MASTER: DMA channel 2 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_A: DMA channel 3 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_B: DMA channel 4 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_C: DMA channel 5 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_D: DMA channel 6 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_E: DMA channel 7 is used by the DMA burst controller
* HRTIM_TIMERINDEX_TIMER_F: DMA channel 8 is used by the DMA burst controller
*/
HAL_StatusTypeDef HAL_HRTIM_BurstDMATransfer(HRTIM_HandleTypeDef *hhrtim,
uint32_t TimerIdx,
uint32_t BurstBufferAddress,
uint32_t BurstBufferLength)
{
DMA_HandleTypeDef * hdma;
/* Check the parameters */
assert_param(IS_HRTIM_TIMERINDEX(TimerIdx));
if(hhrtim->State == HAL_HRTIM_STATE_BUSY)
{
return HAL_BUSY;
}
if(hhrtim->State == HAL_HRTIM_STATE_READY)
{
if((BurstBufferAddress == 0U ) || (BurstBufferLength == 0U))
{
return HAL_ERROR;
}
else
{
hhrtim->State = HAL_HRTIM_STATE_BUSY;
}
}
/* Process Locked */
__HAL_LOCK(hhrtim);
/* Get the timer DMA handler */
hdma = HRTIM_GetDMAHandleFromTimerIdx(hhrtim, TimerIdx);
if (hdma == NULL)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
/* Set the DMA transfer completed callback */
hdma->XferCpltCallback = HRTIM_BurstDMACplt;
/* Set the DMA error callback */
hdma->XferErrorCallback = HRTIM_DMAError ;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hdma,
BurstBufferAddress,
(uint32_t)&(hhrtim->Instance->sCommonRegs.BDMADR),
BurstBufferLength) != HAL_OK)
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_ERROR;
}
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Enable the transfer from preload to active registers for one
* or several timing units (including master timer).
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer(s) concerned by the register preload enabling command
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERUPDATE_MASTER
* @arg HRTIM_TIMERUPDATE_A
* @arg HRTIM_TIMERUPDATE_B
* @arg HRTIM_TIMERUPDATE_C
* @arg HRTIM_TIMERUPDATE_D
* @arg HRTIM_TIMERUPDATE_E
* @arg HRTIM_TIMERUPDATE_E
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_UpdateEnable(HRTIM_HandleTypeDef *hhrtim,
uint32_t Timers)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERUPDATE(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR1 &= ~(Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @brief Disable the transfer from preload to active registers for one
* or several timing units (including master timer).
* @param hhrtim pointer to HAL HRTIM handle
* @param Timers Timer(s) concerned by the register preload disabling command
* This parameter can be any combination of the following values:
* @arg HRTIM_TIMERUPDATE_MASTER
* @arg HRTIM_TIMERUPDATE_A
* @arg HRTIM_TIMERUPDATE_B
* @arg HRTIM_TIMERUPDATE_C
* @arg HRTIM_TIMERUPDATE_D
* @arg HRTIM_TIMERUPDATE_E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_UpdateDisable(HRTIM_HandleTypeDef *hhrtim,
uint32_t Timers)
{
/* Check the parameters */
assert_param(IS_HRTIM_TIMERUPDATE(Timers));
/* Process Locked */
__HAL_LOCK(hhrtim);
hhrtim->State = HAL_HRTIM_STATE_BUSY;
/* Enable timer(s) registers update */
hhrtim->Instance->sCommonRegs.CR1 |= (Timers);
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group9 Peripheral state functions
* @brief Peripheral State functions
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..] This section provides functions used to get HRTIM or HRTIM timer
specific information:
(+) Get HRTIM HAL state
(+) Get captured value
(+) Get HRTIM timer output level
(+) Get HRTIM timer output state
(+) Get delayed protection status
(+) Get burst status
(+) Get current push-pull status
(+) Get idle push-pull status
@endverbatim
* @{
*/
/**
* @brief Return the HRTIM HAL state
* @param hhrtim pointer to HAL HRTIM handle
* @retval HAL state
*/
HAL_HRTIM_StateTypeDef HAL_HRTIM_GetState(HRTIM_HandleTypeDef* hhrtim)
{
/* Return HRTIM state */
return hhrtim->State;
}
/**
* @brief Return actual value of the capture register of the designated capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureUnit Capture unit to trig
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval Captured value
*/
uint32_t HAL_HRTIM_GetCapturedValue(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit)
{
uint32_t captured_value;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureUnit));
/* Read captured value */
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
{
captured_value = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xR & 0x0000FFFFU;
break;
}
case HRTIM_CAPTUREUNIT_2:
{
captured_value = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xR & 0x0000FFFFU;
break;
}
default:
{
captured_value = 0xFFFFFFFFUL;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
return captured_value;
}
/**
* @brief Return actual value and direction of the capture register of the designated capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureUnit Capture unit to trig
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval captured value and direction structure
*/
HRTIM_CaptureValueTypeDef HAL_HRTIM_GetCaptured(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit)
{
uint32_t tmp;
HRTIM_CaptureValueTypeDef captured;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureUnit));
/* Read captured value */
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
tmp = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xR;
captured.Value = tmp & HRTIM_CPT1R_CPT1R & 0x0000FFFFU;
captured.Dir = (((tmp & HRTIM_CPT1R_DIR) == HRTIM_CPT1R_DIR)?1U:0U);
break;
case HRTIM_CAPTUREUNIT_2:
tmp = hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xR;
captured.Value = tmp & HRTIM_CPT2R_CPT2R & 0x0000FFFFU;
captured.Dir = (((tmp & HRTIM_CPT2R_DIR ) == HRTIM_CPT2R_DIR)?1U:0U);
break;
default:
captured.Value = 0xFFFFFFFFUL;
captured.Dir = 0xFFFFFFFFUL;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
return captured;
}
/**
* @brief Return actual direction of the capture register of the designated capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param CaptureUnit Capture unit to trig
* This parameter can be one of the following values:
* @arg HRTIM_CAPTUREUNIT_1: Capture unit 1
* @arg HRTIM_CAPTUREUNIT_2: Capture unit 2
* @retval captured direction
* @arg This parameter is one HRTIM_Timer_UpDown_Mode :
* @arg HRTIM_TIMERUPDOWNMODE_UP
* @arg HRTIM_TIMERUPDOWNMODE_UPDOWN
*/
uint32_t HAL_HRTIM_GetCapturedDir(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit)
{
uint32_t tmp;
/* Check parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
assert_param(IS_HRTIM_CAPTUREUNIT(CaptureUnit));
/* Read captured value */
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
tmp = ((hhrtim->Instance->sTimerxRegs[TimerIdx].CPT1xR & HRTIM_CPT1R_DIR ) >> HRTIM_CPT1R_DIR_Pos);
break;
case HRTIM_CAPTUREUNIT_2:
tmp = ((hhrtim->Instance->sTimerxRegs[TimerIdx].CPT2xR & HRTIM_CPT2R_DIR ) >> HRTIM_CPT2R_DIR_Pos);
break;
default:
tmp = 0xFFFFFFFFU;
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
return tmp;
}
/**
* @brief Return actual level (active or inactive) of the designated output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Output Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval Output level
* @note Returned output level is taken before the output stage (chopper,
* polarity).
*/
uint32_t HAL_HRTIM_WaveformGetOutputLevel(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output)
{
uint32_t output_level = (uint32_t)RESET;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, Output));
/* Read the output level */
switch (Output)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
if ((hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_O1CPY) != (uint32_t)RESET)
{
output_level = HRTIM_OUTPUTLEVEL_ACTIVE;
}
else
{
output_level = HRTIM_OUTPUTLEVEL_INACTIVE;
}
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
if ((hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_O2CPY) != (uint32_t)RESET)
{
output_level = HRTIM_OUTPUTLEVEL_ACTIVE;
}
else
{
output_level = HRTIM_OUTPUTLEVEL_INACTIVE;
}
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return (uint32_t)HAL_ERROR;
}
return output_level;
}
/**
* @brief Return actual state (RUN, IDLE, FAULT) of the designated output
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Output Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval Output state
*/
uint32_t HAL_HRTIM_WaveformGetOutputState(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output)
{
uint32_t output_bit = (uint32_t)RESET;
uint32_t output_state;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, Output));
/* Prevent unused argument(s) compilation warning */
UNUSED(TimerIdx);
/* Set output state according to output control status and output disable status */
switch (Output)
{
case HRTIM_OUTPUT_TA1:
{
output_bit = HRTIM_OENR_TA1OEN;
break;
}
case HRTIM_OUTPUT_TA2:
{
output_bit = HRTIM_OENR_TA2OEN;
break;
}
case HRTIM_OUTPUT_TB1:
{
output_bit = HRTIM_OENR_TB1OEN;
break;
}
case HRTIM_OUTPUT_TB2:
{
output_bit = HRTIM_OENR_TB2OEN;
break;
}
case HRTIM_OUTPUT_TC1:
{
output_bit = HRTIM_OENR_TC1OEN;
break;
}
case HRTIM_OUTPUT_TC2:
{
output_bit = HRTIM_OENR_TC2OEN;
break;
}
case HRTIM_OUTPUT_TD1:
{
output_bit = HRTIM_OENR_TD1OEN;
break;
}
case HRTIM_OUTPUT_TD2:
{
output_bit = HRTIM_OENR_TD2OEN;
break;
}
case HRTIM_OUTPUT_TE1:
{
output_bit = HRTIM_OENR_TE1OEN;
break;
}
case HRTIM_OUTPUT_TE2:
{
output_bit = HRTIM_OENR_TE2OEN;
break;
}
case HRTIM_OUTPUT_TF1:
{
output_bit = HRTIM_OENR_TF1OEN;
break;
}
case HRTIM_OUTPUT_TF2:
{
output_bit = HRTIM_OENR_TF2OEN;
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return (uint32_t)HAL_ERROR;
}
if ((hhrtim->Instance->sCommonRegs.OENR & output_bit) != (uint32_t)RESET)
{
/* Output is enabled: output in RUN state (whatever output disable status is)*/
output_state = HRTIM_OUTPUTSTATE_RUN;
}
else
{
if ((hhrtim->Instance->sCommonRegs.ODSR & output_bit) != (uint32_t)RESET)
{
/* Output is disabled: output in FAULT state */
output_state = HRTIM_OUTPUTSTATE_FAULT;
}
else
{
/* Output is disabled: output in IDLE state */
output_state = HRTIM_OUTPUTSTATE_IDLE;
}
}
return(output_state);
}
/**
* @brief Return the level (active or inactive) of the designated output
* when the delayed protection was triggered.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @param Output Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval Delayed protection status
*/
uint32_t HAL_HRTIM_GetDelayedProtectionStatus(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output)
{
uint32_t delayed_protection_status = (uint32_t)RESET;
/* Check parameters */
assert_param(IS_HRTIM_TIMER_OUTPUT(TimerIdx, Output));
/* Read the delayed protection status */
switch (Output)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
if ((hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_O1STAT) != (uint32_t)RESET)
{
/* Output 1 was active when the delayed idle protection was triggered */
delayed_protection_status = HRTIM_OUTPUTLEVEL_ACTIVE;
}
else
{
/* Output 1 was inactive when the delayed idle protection was triggered */
delayed_protection_status = HRTIM_OUTPUTLEVEL_INACTIVE;
}
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
if ((hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_O2STAT) != (uint32_t)RESET)
{
/* Output 2 was active when the delayed idle protection was triggered */
delayed_protection_status = HRTIM_OUTPUTLEVEL_ACTIVE;
}
else
{
/* Output 2 was inactive when the delayed idle protection was triggered */
delayed_protection_status = HRTIM_OUTPUTLEVEL_INACTIVE;
}
break;
}
default:
{
hhrtim->State = HAL_HRTIM_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hhrtim);
break;
}
}
if(hhrtim->State == HAL_HRTIM_STATE_ERROR)
{
return (uint32_t)HAL_ERROR;
}
return delayed_protection_status;
}
/**
* @brief Return the actual status (active or inactive) of the burst mode controller
* @param hhrtim pointer to HAL HRTIM handle
* @retval Burst mode controller status
*/
uint32_t HAL_HRTIM_GetBurstStatus(HRTIM_HandleTypeDef * hhrtim)
{
uint32_t burst_mode_status;
/* Read burst mode status */
burst_mode_status = (hhrtim->Instance->sCommonRegs.BMCR & HRTIM_BMCR_BMSTAT);
return burst_mode_status;
}
/**
* @brief Indicate on which output the signal is currently active (when the
* push pull mode is enabled).
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval Burst mode controller status
*/
uint32_t HAL_HRTIM_GetCurrentPushPullStatus(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
uint32_t current_pushpull_status;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
/* Read current push pull status */
current_pushpull_status = (hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_CPPSTAT);
return current_pushpull_status;
}
/**
* @brief Indicate on which output the signal was applied, in push-pull mode,
balanced fault mode or delayed idle mode, when the protection was triggered.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval Idle Push Pull Status
*/
uint32_t HAL_HRTIM_GetIdlePushPullStatus(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
uint32_t idle_pushpull_status;
/* Check the parameters */
assert_param(IS_HRTIM_TIMING_UNIT(TimerIdx));
/* Read current push pull status */
idle_pushpull_status = (hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR & HRTIM_TIMISR_IPPSTAT);
return idle_pushpull_status;
}
/**
* @}
*/
/** @defgroup HRTIM_Exported_Functions_Group10 Interrupts handling
* @brief Functions called when HRTIM generates an interrupt
* 7 interrupts can be generated by the master timer:
* - Master timer registers update
* - Synchronization event received
* - Master timer repetition event
* - Master Compare 1 to 4 event
* 14 interrupts can be generated by each timing unit:
* - Delayed protection triggered
* - Counter reset or roll-over event
* - Output 1 and output 2 reset (transition active to inactive)
* - Output 1 and output 2 set (transition inactive to active)
* - Capture 1 and 2 events
* - Timing unit registers update
* - Repetition event
* - Compare 1 to 4 event
* 8 global interrupts are generated for the whole HRTIM:
* - System fault and Fault 1 to 5 (regardless of the timing unit attribution)
* - DLL calibration done
* - Burst mode period completed
@verbatim
===============================================================================
##### HRTIM interrupts handling #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the HRTIM
interrupts:
(+) HRTIM interrupt handler
(+) Callback function called when Fault1 interrupt occurs
(+) Callback function called when Fault2 interrupt occurs
(+) Callback function called when Fault3 interrupt occurs
(+) Callback function called when Fault4 interrupt occurs
(+) Callback function called when Fault5 interrupt occurs
(+) Callback function called when Fault6 interrupt occurs
(+) Callback function called when system Fault interrupt occurs
(+) Callback function called when DLL ready interrupt occurs
(+) Callback function called when burst mode period interrupt occurs
(+) Callback function called when synchronization input interrupt occurs
(+) Callback function called when a timer register update interrupt occurs
(+) Callback function called when a timer repetition interrupt occurs
(+) Callback function called when a compare 1 match interrupt occurs
(+) Callback function called when a compare 2 match interrupt occurs
(+) Callback function called when a compare 3 match interrupt occurs
(+) Callback function called when a compare 4 match interrupt occurs
(+) Callback function called when a capture 1 interrupt occurs
(+) Callback function called when a capture 2 interrupt occurs
(+) Callback function called when a delayed protection interrupt occurs
(+) Callback function called when a timer counter reset interrupt occurs
(+) Callback function called when a timer output 1 set interrupt occurs
(+) Callback function called when a timer output 1 reset interrupt occurs
(+) Callback function called when a timer output 2 set interrupt occurs
(+) Callback function called when a timer output 2 reset interrupt occurs
(+) Callback function called when a timer output 2 reset interrupt occurs
(+) Callback function called upon completion of a burst DMA transfer
(+) HRTIM callback function registration
(+) HRTIM callback function unregistration
(+) HRTIM Timer x callback function registration
(+) HRTIM Timer x callback function unregistration
@endverbatim
* @{
*/
/**
* @brief This function handles HRTIM interrupt request.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be any value of HRTIM_Timer_Index
* @retval None
*/
void HAL_HRTIM_IRQHandler(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* HRTIM interrupts handling */
if (TimerIdx == HRTIM_TIMERINDEX_COMMON)
{
HRTIM_HRTIM_ISR(hhrtim);
}
else if (TimerIdx == HRTIM_TIMERINDEX_MASTER)
{
/* Master related interrupts handling */
HRTIM_Master_ISR(hhrtim);
}
else
{
/* Timing unit related interrupts handling */
HRTIM_Timer_ISR(hhrtim, TimerIdx);
}
}
/**
* @brief Callback function invoked when a fault 1 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle * @retval None
* @retval None
*/
__weak void HAL_HRTIM_Fault1Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault1Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a fault 2 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_Fault2Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault2Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a fault 3 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_Fault3Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault3Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a fault 4 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_Fault4Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault4Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a fault 5 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_Fault5Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault5Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a fault 6 interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_Fault6Callback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Fault6Callback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a system fault interrupt occurred
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_SystemFaultCallback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_SystemFaultCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the DLL calibration is completed
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_DLLCalibrationReadyCallback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_DLLCalibrationCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the end of the burst mode period is reached
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_BurstModePeriodCallback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_BurstModeCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a synchronization input event is received
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_SynchronizationEventCallback(HRTIM_HandleTypeDef * hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_SynchronizationEventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when timer registers are updated
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_RegistersUpdateCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_RegistersUpdateCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when timer repetition period has elapsed
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_RepetitionEventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_RepetitionEventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer counter matches the value
* programmed in the compare 1 register
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Compare1EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_Compare1EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer counter matches the value
* programmed in the compare 2 register
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
*/
__weak void HAL_HRTIM_Compare2EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_Compare2EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer counter matches the value
* programmed in the compare 3 register
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Compare3EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_Compare3EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer counter matches the value
* programmed in the compare 4 register.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Compare4EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Master_Compare4EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x capture 1 event occurs
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Capture1EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Capture1EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x capture 2 event occurs
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Capture2EventCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Capture2EventCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the delayed idle or balanced idle mode is
* entered.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_DelayedProtectionCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_DelayedProtectionCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x counter reset/roll-over
* event occurs.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_CounterResetCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_CounterResetCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x output 1 is set
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Output1SetCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Output1SetCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x output 1 is reset
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Output1ResetCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Output1ResetCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x output 2 is set
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Output2SetCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Output2SetCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when the timer x output 2 is reset
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_Output2ResetCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_Timer_Output2ResetCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a DMA burst transfer is completed
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_MASTER for master timer
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
__weak void HAL_HRTIM_BurstDMATransferCallback(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
UNUSED(TimerIdx);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_BurstDMATransferCallback could be implemented in the user file
*/
}
/**
* @brief Callback function invoked when a DMA error occurs
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
__weak void HAL_HRTIM_ErrorCallback(HRTIM_HandleTypeDef *hhrtim)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hhrtim);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_HRTIM_ErrorCallback could be implemented in the user file
*/
}
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
/**
* @brief HRTIM callback function registration
* @param hhrtim pointer to HAL HRTIM handle
* @param CallbackID ID of the HRTIM callback function to register
* This parameter can be one of the following values:
* @arg HAL_HRTIM_FAULT1CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT2CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT3CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT4CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT5CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT6CALLBACK_CB_ID
* @arg HAL_HRTIM_SYSTEMFAULTCALLBACK_CB_ID
* @arg HAL_HRTIM_DLLCALBRATIONREADYCALLBACK_CB_ID
* @arg HAL_HRTIM_BURSTMODEPERIODCALLBACK_CB_ID
* @arg HAL_HRTIM_SYNCHRONIZATIONEVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_ERRORCALLBACK_CB_ID
* @arg HAL_HRTIM_MSPINIT_CB_ID
* @arg HAL_HRTIM_MSPDEINIT_CB_ID
* @param pCallback Callback function pointer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_RegisterCallback(HRTIM_HandleTypeDef * hhrtim,
HAL_HRTIM_CallbackIDTypeDef CallbackID,
pHRTIM_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hhrtim);
if (HAL_HRTIM_STATE_READY == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_FAULT1CALLBACK_CB_ID :
hhrtim->Fault1Callback = pCallback;
break;
case HAL_HRTIM_FAULT2CALLBACK_CB_ID :
hhrtim->Fault2Callback = pCallback;
break;
case HAL_HRTIM_FAULT3CALLBACK_CB_ID :
hhrtim->Fault3Callback = pCallback;
break;
case HAL_HRTIM_FAULT4CALLBACK_CB_ID :
hhrtim->Fault4Callback = pCallback;
break;
case HAL_HRTIM_FAULT5CALLBACK_CB_ID :
hhrtim->Fault5Callback = pCallback;
break;
case HAL_HRTIM_FAULT6CALLBACK_CB_ID :
hhrtim->Fault6Callback = pCallback;
break;
case HAL_HRTIM_SYSTEMFAULTCALLBACK_CB_ID :
hhrtim->SystemFaultCallback = pCallback;
break;
case HAL_HRTIM_DLLCALBRATIONREADYCALLBACK_CB_ID :
hhrtim->DLLCalibrationReadyCallback = pCallback;
break;
case HAL_HRTIM_BURSTMODEPERIODCALLBACK_CB_ID :
hhrtim->BurstModePeriodCallback = pCallback;
break;
case HAL_HRTIM_SYNCHRONIZATIONEVENTCALLBACK_CB_ID :
hhrtim->SynchronizationEventCallback = pCallback;
break;
case HAL_HRTIM_ERRORCALLBACK_CB_ID :
hhrtim->ErrorCallback = pCallback;
break;
case HAL_HRTIM_MSPINIT_CB_ID :
hhrtim->MspInitCallback = pCallback;
break;
case HAL_HRTIM_MSPDEINIT_CB_ID :
hhrtim->MspDeInitCallback = pCallback;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_HRTIM_STATE_RESET == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_MSPINIT_CB_ID :
hhrtim->MspInitCallback = pCallback;
break;
case HAL_HRTIM_MSPDEINIT_CB_ID :
hhrtim->MspDeInitCallback = pCallback;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hhrtim);
return status;
}
/**
* @brief HRTIM callback function un-registration
* @param hhrtim pointer to HAL HRTIM handle
* @param CallbackID ID of the HRTIM callback function to unregister
* This parameter can be one of the following values:
* @arg HAL_HRTIM_FAULT1CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT2CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT3CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT4CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT5CALLBACK_CB_ID
* @arg HAL_HRTIM_FAULT6CALLBACK_CB_ID
* @arg HAL_HRTIM_SYSTEMFAULTCALLBACK_CB_ID
* @arg HAL_HRTIM_DLLCALBRATIONREADYCALLBACK_CB_ID
* @arg HAL_HRTIM_BURSTMODEPERIODCALLBACK_CB_ID
* @arg HAL_HRTIM_SYNCHRONIZATIONEVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_ERRORCALLBACK_CB_ID
* @arg HAL_HRTIM_MSPINIT_CB_ID
* @arg HAL_HRTIM_MSPDEINIT_CB_ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_UnRegisterCallback(HRTIM_HandleTypeDef * hhrtim,
HAL_HRTIM_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hhrtim);
if (HAL_HRTIM_STATE_READY == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_FAULT1CALLBACK_CB_ID :
hhrtim->Fault1Callback = HAL_HRTIM_Fault1Callback;
break;
case HAL_HRTIM_FAULT2CALLBACK_CB_ID :
hhrtim->Fault2Callback = HAL_HRTIM_Fault2Callback;
break;
case HAL_HRTIM_FAULT3CALLBACK_CB_ID :
hhrtim->Fault3Callback = HAL_HRTIM_Fault3Callback;
break;
case HAL_HRTIM_FAULT4CALLBACK_CB_ID :
hhrtim->Fault4Callback = HAL_HRTIM_Fault4Callback;
break;
case HAL_HRTIM_FAULT5CALLBACK_CB_ID :
hhrtim->Fault5Callback = HAL_HRTIM_Fault5Callback;
break;
case HAL_HRTIM_FAULT6CALLBACK_CB_ID :
hhrtim->Fault6Callback = HAL_HRTIM_Fault6Callback;
break;
case HAL_HRTIM_SYSTEMFAULTCALLBACK_CB_ID :
hhrtim->SystemFaultCallback = HAL_HRTIM_SystemFaultCallback;
break;
case HAL_HRTIM_DLLCALBRATIONREADYCALLBACK_CB_ID :
hhrtim->DLLCalibrationReadyCallback = HAL_HRTIM_DLLCalibrationReadyCallback;
break;
case HAL_HRTIM_BURSTMODEPERIODCALLBACK_CB_ID :
hhrtim->BurstModePeriodCallback = HAL_HRTIM_BurstModePeriodCallback;
break;
case HAL_HRTIM_SYNCHRONIZATIONEVENTCALLBACK_CB_ID :
hhrtim->SynchronizationEventCallback = HAL_HRTIM_SynchronizationEventCallback;
break;
case HAL_HRTIM_ERRORCALLBACK_CB_ID :
hhrtim->ErrorCallback = HAL_HRTIM_ErrorCallback;
break;
case HAL_HRTIM_MSPINIT_CB_ID :
hhrtim->MspInitCallback = HAL_HRTIM_MspInit;
break;
case HAL_HRTIM_MSPDEINIT_CB_ID :
hhrtim->MspDeInitCallback = HAL_HRTIM_MspDeInit;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_HRTIM_STATE_RESET == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_MSPINIT_CB_ID :
hhrtim->MspInitCallback = HAL_HRTIM_MspInit;
break;
case HAL_HRTIM_MSPDEINIT_CB_ID :
hhrtim->MspDeInitCallback = HAL_HRTIM_MspDeInit;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hhrtim);
return status;
}
/**
* @brief HRTIM Timer x callback function registration
* @param hhrtim pointer to HAL HRTIM handle
* @param CallbackID ID of the HRTIM Timer x callback function to register
* This parameter can be one of the following values:
* @arg HAL_HRTIM_REGISTERSUPDATECALLBACK_CB_ID
* @arg HAL_HRTIM_REPETITIONEVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE1EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE2EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE3EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE4EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_CAPTURE1EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_CAPTURE2EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_DELAYEDPROTECTIONCALLBACK_CB_ID
* @arg HAL_HRTIM_COUNTERRESETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT1SETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT1RESETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT2SETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT2RESETCALLBACK_CB_ID
* @arg HAL_HRTIM_BURSTDMATRANSFERCALLBACK_CB_ID
* @param pCallback Callback function pointer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_TIMxRegisterCallback(HRTIM_HandleTypeDef * hhrtim,
HAL_HRTIM_CallbackIDTypeDef CallbackID,
pHRTIM_TIMxCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hhrtim);
if (HAL_HRTIM_STATE_READY == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_REGISTERSUPDATECALLBACK_CB_ID :
hhrtim->RegistersUpdateCallback = pCallback;
break;
case HAL_HRTIM_REPETITIONEVENTCALLBACK_CB_ID :
hhrtim->RepetitionEventCallback = pCallback;
break;
case HAL_HRTIM_COMPARE1EVENTCALLBACK_CB_ID :
hhrtim->Compare1EventCallback = pCallback;
break;
case HAL_HRTIM_COMPARE2EVENTCALLBACK_CB_ID :
hhrtim->Compare2EventCallback = pCallback;
break;
case HAL_HRTIM_COMPARE3EVENTCALLBACK_CB_ID :
hhrtim->Compare3EventCallback = pCallback;
break;
case HAL_HRTIM_COMPARE4EVENTCALLBACK_CB_ID :
hhrtim->Compare4EventCallback = pCallback;
break;
case HAL_HRTIM_CAPTURE1EVENTCALLBACK_CB_ID :
hhrtim->Capture1EventCallback = pCallback;
break;
case HAL_HRTIM_CAPTURE2EVENTCALLBACK_CB_ID :
hhrtim->Capture2EventCallback = pCallback;
break;
case HAL_HRTIM_DELAYEDPROTECTIONCALLBACK_CB_ID :
hhrtim->DelayedProtectionCallback = pCallback;
break;
case HAL_HRTIM_COUNTERRESETCALLBACK_CB_ID :
hhrtim->CounterResetCallback = pCallback;
break;
case HAL_HRTIM_OUTPUT1SETCALLBACK_CB_ID :
hhrtim->Output1SetCallback = pCallback;
break;
case HAL_HRTIM_OUTPUT1RESETCALLBACK_CB_ID :
hhrtim->Output1ResetCallback = pCallback;
break;
case HAL_HRTIM_OUTPUT2SETCALLBACK_CB_ID :
hhrtim->Output2SetCallback = pCallback;
break;
case HAL_HRTIM_OUTPUT2RESETCALLBACK_CB_ID :
hhrtim->Output2ResetCallback = pCallback;
break;
case HAL_HRTIM_BURSTDMATRANSFERCALLBACK_CB_ID :
hhrtim->BurstDMATransferCallback = pCallback;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hhrtim);
return status;
}
/**
* @brief HRTIM Timer x callback function un-registration
* @param hhrtim pointer to HAL HRTIM handle
* @param CallbackID ID of the HRTIM callback Timer x function to unregister
* This parameter can be one of the following values:
* @arg HAL_HRTIM_REGISTERSUPDATECALLBACK_CB_ID
* @arg HAL_HRTIM_REPETITIONEVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE1EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE2EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE3EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_COMPARE4EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_CAPTURE1EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_CAPTURE2EVENTCALLBACK_CB_ID
* @arg HAL_HRTIM_DELAYEDPROTECTIONCALLBACK_CB_ID
* @arg HAL_HRTIM_COUNTERRESETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT1SETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT1RESETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT2SETCALLBACK_CB_ID
* @arg HAL_HRTIM_OUTPUT2RESETCALLBACK_CB_ID
* @arg HAL_HRTIM_BURSTDMATRANSFERCALLBACK_CB_ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HRTIM_TIMxUnRegisterCallback(HRTIM_HandleTypeDef * hhrtim,
HAL_HRTIM_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hhrtim);
if (HAL_HRTIM_STATE_READY == hhrtim->State)
{
switch (CallbackID)
{
case HAL_HRTIM_REGISTERSUPDATECALLBACK_CB_ID :
hhrtim->RegistersUpdateCallback = HAL_HRTIM_RegistersUpdateCallback;
break;
case HAL_HRTIM_REPETITIONEVENTCALLBACK_CB_ID :
hhrtim->RepetitionEventCallback = HAL_HRTIM_RepetitionEventCallback;
break;
case HAL_HRTIM_COMPARE1EVENTCALLBACK_CB_ID :
hhrtim->Compare1EventCallback = HAL_HRTIM_Compare1EventCallback;
break;
case HAL_HRTIM_COMPARE2EVENTCALLBACK_CB_ID :
hhrtim->Compare2EventCallback = HAL_HRTIM_Compare2EventCallback;
break;
case HAL_HRTIM_COMPARE3EVENTCALLBACK_CB_ID :
hhrtim->Compare3EventCallback = HAL_HRTIM_Compare3EventCallback;
break;
case HAL_HRTIM_COMPARE4EVENTCALLBACK_CB_ID :
hhrtim->Compare4EventCallback = HAL_HRTIM_Compare4EventCallback;
break;
case HAL_HRTIM_CAPTURE1EVENTCALLBACK_CB_ID :
hhrtim->Capture1EventCallback = HAL_HRTIM_Capture1EventCallback;
break;
case HAL_HRTIM_CAPTURE2EVENTCALLBACK_CB_ID :
hhrtim->Capture2EventCallback = HAL_HRTIM_Capture2EventCallback;
break;
case HAL_HRTIM_DELAYEDPROTECTIONCALLBACK_CB_ID :
hhrtim->DelayedProtectionCallback = HAL_HRTIM_DelayedProtectionCallback;
break;
case HAL_HRTIM_COUNTERRESETCALLBACK_CB_ID :
hhrtim->CounterResetCallback = HAL_HRTIM_CounterResetCallback;
break;
case HAL_HRTIM_OUTPUT1SETCALLBACK_CB_ID :
hhrtim->Output1SetCallback = HAL_HRTIM_Output1SetCallback;
break;
case HAL_HRTIM_OUTPUT1RESETCALLBACK_CB_ID :
hhrtim->Output1ResetCallback = HAL_HRTIM_Output1ResetCallback;
break;
case HAL_HRTIM_OUTPUT2SETCALLBACK_CB_ID :
hhrtim->Output2SetCallback = HAL_HRTIM_Output2SetCallback;
break;
case HAL_HRTIM_OUTPUT2RESETCALLBACK_CB_ID :
hhrtim->Output2ResetCallback = HAL_HRTIM_Output2ResetCallback;
break;
case HAL_HRTIM_BURSTDMATRANSFERCALLBACK_CB_ID :
hhrtim->BurstDMATransferCallback = HAL_HRTIM_BurstDMATransferCallback;
break;
default :
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the state */
hhrtim->State = HAL_HRTIM_STATE_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hhrtim);
return status;
}
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
/**
* @}
*/
/**
* @}
*/
/** @addtogroup HRTIM_Private_Functions
* @{
*/
/**
* @brief Configure the master timer time base
* @param hhrtim pointer to HAL HRTIM handle
* @param pTimeBaseCfg pointer to the time base configuration structure
* @retval None
*/
static void HRTIM_MasterBase_Config(HRTIM_HandleTypeDef * hhrtim,
HRTIM_TimeBaseCfgTypeDef * pTimeBaseCfg)
{
uint32_t hrtim_mcr;
/* Configure master timer */
hrtim_mcr = hhrtim->Instance->sMasterRegs.MCR;
/* Set the prescaler ratio */
hrtim_mcr &= (uint32_t) ~(HRTIM_MCR_CK_PSC);
hrtim_mcr |= (uint32_t)pTimeBaseCfg->PrescalerRatio;
/* Set the operating mode */
hrtim_mcr &= (uint32_t) ~(HRTIM_MCR_CONT | HRTIM_MCR_RETRIG);
hrtim_mcr |= (uint32_t)pTimeBaseCfg->Mode;
/* Update the HRTIM registers */
hhrtim->Instance->sMasterRegs.MCR = hrtim_mcr;
hhrtim->Instance->sMasterRegs.MPER = pTimeBaseCfg->Period;
hhrtim->Instance->sMasterRegs.MREP = pTimeBaseCfg->RepetitionCounter;
}
/**
* @brief Configure timing unit (Timer A to Timer F) time base
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param pTimeBaseCfg pointer to the time base configuration structure
* @retval None
*/
static void HRTIM_TimingUnitBase_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx ,
HRTIM_TimeBaseCfgTypeDef * pTimeBaseCfg)
{
uint32_t hrtim_timcr;
/* Configure master timing unit */
hrtim_timcr = hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR;
/* Set the prescaler ratio */
hrtim_timcr &= (uint32_t) ~(HRTIM_TIMCR_CK_PSC);
hrtim_timcr |= (uint32_t)pTimeBaseCfg->PrescalerRatio;
/* Set the operating mode */
hrtim_timcr &= (uint32_t) ~(HRTIM_TIMCR_CONT | HRTIM_TIMCR_RETRIG);
hrtim_timcr |= (uint32_t)pTimeBaseCfg->Mode;
/* Update the HRTIM registers */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR = hrtim_timcr;
hhrtim->Instance->sTimerxRegs[TimerIdx].PERxR = pTimeBaseCfg->Period;
hhrtim->Instance->sTimerxRegs[TimerIdx].REPxR = pTimeBaseCfg->RepetitionCounter;
}
/**
* @brief Configure the master timer in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param pTimerCfg pointer to the timer configuration data structure
* @retval None
*/
static void HRTIM_MasterWaveform_Config(HRTIM_HandleTypeDef * hhrtim,
HRTIM_TimerCfgTypeDef * pTimerCfg)
{
uint32_t hrtim_mcr;
uint32_t hrtim_bmcr;
/* Configure master timer */
hrtim_mcr = hhrtim->Instance->sMasterRegs.MCR;
hrtim_bmcr = hhrtim->Instance->sCommonRegs.BMCR;
/* Enable/Disable the half mode */
hrtim_mcr &= ~(HRTIM_MCR_HALF);
hrtim_mcr |= pTimerCfg->HalfModeEnable;
/* INTLVD bits are set to 00 */
hrtim_mcr &= ~(HRTIM_MCR_INTLVD);
if ((pTimerCfg->HalfModeEnable == HRTIM_HALFMODE_ENABLED) || (pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_DUAL))
{
/* INTLVD bits set to 00 */
hrtim_mcr &= ~(HRTIM_MCR_INTLVD);
hrtim_mcr |= (HRTIM_MCR_HALF);
}
else if ( pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_TRIPLE)
{
hrtim_mcr |= (HRTIM_MCR_INTLVD_0);
hrtim_mcr &= ~(HRTIM_MCR_INTLVD_1);
}
else if ( pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_QUAD)
{
hrtim_mcr |= (HRTIM_MCR_INTLVD_1);
hrtim_mcr &= ~(HRTIM_MCR_INTLVD_0);
}
else
{
hrtim_mcr &= ~(HRTIM_MCR_HALF);
hrtim_mcr &= ~(HRTIM_MCR_INTLVD);
}
/* Enable/Disable the timer start upon synchronization event reception */
hrtim_mcr &= ~(HRTIM_MCR_SYNCSTRTM);
hrtim_mcr |= pTimerCfg->StartOnSync;
/* Enable/Disable the timer reset upon synchronization event reception */
hrtim_mcr &= ~(HRTIM_MCR_SYNCRSTM);
hrtim_mcr |= pTimerCfg->ResetOnSync;
/* Enable/Disable the DAC synchronization event generation */
hrtim_mcr &= ~(HRTIM_MCR_DACSYNC);
hrtim_mcr |= pTimerCfg->DACSynchro;
/* Enable/Disable preload mechanism for timer registers */
hrtim_mcr &= ~(HRTIM_MCR_PREEN);
hrtim_mcr |= pTimerCfg->PreloadEnable;
/* Master timer registers update handling */
hrtim_mcr &= ~(HRTIM_MCR_BRSTDMA);
hrtim_mcr |= (pTimerCfg->UpdateGating << 2U);
/* Enable/Disable registers update on repetition */
hrtim_mcr &= ~(HRTIM_MCR_MREPU);
hrtim_mcr |= pTimerCfg->RepetitionUpdate;
/* Set the timer burst mode */
hrtim_bmcr &= ~(HRTIM_BMCR_MTBM);
hrtim_bmcr |= pTimerCfg->BurstMode;
/* Update the HRTIM registers */
hhrtim->Instance->sMasterRegs.MCR = hrtim_mcr;
hhrtim->Instance->sCommonRegs.BMCR = hrtim_bmcr;
}
/**
* @brief Configure timing unit (Timer A to Timer F) in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param pTimerCfg pointer to the timer configuration data structure
* @retval None
*/
static void HRTIM_TimingUnitWaveform_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCfgTypeDef * pTimerCfg)
{
uint32_t hrtim_timcr;
uint32_t hrtim_timfltr;
uint32_t hrtim_timoutr;
uint32_t hrtim_timrstr;
uint32_t hrtim_bmcr;
/* UPDGAT bitfield must be reset before programming a new value */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR &= ~(HRTIM_TIMCR_UPDGAT);
/* Configure timing unit (Timer A to Timer F) */
hrtim_timcr = hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR;
hrtim_timfltr = hhrtim->Instance->sTimerxRegs[TimerIdx].FLTxR;
hrtim_timoutr = hhrtim->Instance->sTimerxRegs[TimerIdx].OUTxR;
hrtim_bmcr = hhrtim->Instance->sCommonRegs.BMCR;
/* Enable/Disable the half mode */
hrtim_timcr &= ~(HRTIM_TIMCR_HALF);
hrtim_timcr |= pTimerCfg->HalfModeEnable;
if ((pTimerCfg->HalfModeEnable == HRTIM_HALFMODE_ENABLED) || (pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_DUAL))
{
/* INTLVD bits set to 00 */
hrtim_timcr &= ~(HRTIM_TIMCR_INTLVD);
hrtim_timcr |= (HRTIM_TIMCR_HALF);
}
else if ( pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_TRIPLE)
{
hrtim_timcr |= (HRTIM_TIMCR_INTLVD_0);
hrtim_timcr &= ~(HRTIM_TIMCR_INTLVD_1);
}
else if ( pTimerCfg->InterleavedMode == HRTIM_INTERLEAVED_MODE_QUAD)
{
hrtim_timcr |= (HRTIM_TIMCR_INTLVD_1);
hrtim_timcr &= ~(HRTIM_TIMCR_INTLVD_0);
}
else
{
hrtim_timcr &= ~(HRTIM_TIMCR_HALF);
hrtim_timcr &= ~(HRTIM_TIMCR_INTLVD);
}
/* Enable/Disable the timer start upon synchronization event reception */
hrtim_timcr &= ~(HRTIM_TIMCR_SYNCSTRT);
hrtim_timcr |= pTimerCfg->StartOnSync;
/* Enable/Disable the timer reset upon synchronization event reception */
hrtim_timcr &= ~(HRTIM_TIMCR_SYNCRST);
hrtim_timcr |= pTimerCfg->ResetOnSync;
/* Enable/Disable the DAC synchronization event generation */
hrtim_timcr &= ~(HRTIM_TIMCR_DACSYNC);
hrtim_timcr |= pTimerCfg->DACSynchro;
/* Enable/Disable preload mechanism for timer registers */
hrtim_timcr &= ~(HRTIM_TIMCR_PREEN);
hrtim_timcr |= pTimerCfg->PreloadEnable;
/* Timing unit registers update handling */
hrtim_timcr &= ~(HRTIM_TIMCR_UPDGAT);
hrtim_timcr |= pTimerCfg->UpdateGating;
/* Enable/Disable registers update on repetition */
hrtim_timcr &= ~(HRTIM_TIMCR_TREPU);
if (pTimerCfg->RepetitionUpdate == HRTIM_UPDATEONREPETITION_ENABLED)
{
hrtim_timcr |= HRTIM_TIMCR_TREPU;
}
/* Set the push-pull mode */
hrtim_timcr &= ~(HRTIM_TIMCR_PSHPLL);
hrtim_timcr |= pTimerCfg->PushPull;
/* Enable/Disable registers update on timer counter reset */
hrtim_timcr &= ~(HRTIM_TIMCR_TRSTU);
hrtim_timcr |= pTimerCfg->ResetUpdate;
/* Set the timer update trigger */
hrtim_timcr &= ~(HRTIM_TIMCR_TIMUPDATETRIGGER);
hrtim_timcr |= pTimerCfg->UpdateTrigger;
/* Enable/Disable the fault channel at timer level */
hrtim_timfltr &= ~(HRTIM_FLTR_FLTxEN);
hrtim_timfltr |= (pTimerCfg->FaultEnable & HRTIM_FLTR_FLTxEN);
/* Lock/Unlock fault sources at timer level */
hrtim_timfltr &= ~(HRTIM_FLTR_FLTLCK);
hrtim_timfltr |= pTimerCfg->FaultLock;
/* Enable/Disable dead time insertion at timer level */
hrtim_timoutr &= ~(HRTIM_OUTR_DTEN);
hrtim_timoutr |= pTimerCfg->DeadTimeInsertion;
/* Enable/Disable delayed protection at timer level
Delayed Idle is available whatever the timer operating mode (regular, push-pull)
Balanced Idle is only available in push-pull mode
*/
if ( ((pTimerCfg->DelayedProtectionMode != HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV6)
&& (pTimerCfg->DelayedProtectionMode != HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV7))
|| (pTimerCfg->PushPull == HRTIM_TIMPUSHPULLMODE_ENABLED))
{
hrtim_timoutr &= ~(HRTIM_OUTR_DLYPRT| HRTIM_OUTR_DLYPRTEN);
hrtim_timoutr |= pTimerCfg->DelayedProtectionMode;
}
/* Set the BIAR mode : one bit for both outputs */
hrtim_timoutr &= ~(HRTIM_OUTR_BIAR);
hrtim_timoutr |= (pTimerCfg->BalancedIdleAutomaticResume);
/* Set the timer counter reset trigger */
hrtim_timrstr = pTimerCfg->ResetTrigger;
/* Set the timer burst mode */
switch (TimerIdx)
{
case HRTIM_TIMERINDEX_TIMER_A:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TABM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 1U);
break;
}
case HRTIM_TIMERINDEX_TIMER_B:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TBBM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 2U);
break;
}
case HRTIM_TIMERINDEX_TIMER_C:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TCBM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 3U);
break;
}
case HRTIM_TIMERINDEX_TIMER_D:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TDBM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 4U);
break;
}
case HRTIM_TIMERINDEX_TIMER_E:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TEBM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 5U);
break;
}
case HRTIM_TIMERINDEX_TIMER_F:
{
hrtim_bmcr &= ~(HRTIM_BMCR_TFBM);
hrtim_bmcr |= ( pTimerCfg->BurstMode << 6U);
break;
}
default:
break;
}
/* Update the HRTIM registers */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR = hrtim_timcr;
hhrtim->Instance->sTimerxRegs[TimerIdx].FLTxR = hrtim_timfltr;
hhrtim->Instance->sTimerxRegs[TimerIdx].OUTxR = hrtim_timoutr;
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = hrtim_timrstr;
hhrtim->Instance->sCommonRegs.BMCR = hrtim_bmcr;
}
/**
* @brief Control timing unit (timer A to timer F) in waveform mode
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param pTimerCtl pointer to the timer configuration data structure
* @retval None
*/
static void HRTIM_TimingUnitWaveform_Control(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
HRTIM_TimerCtlTypeDef * pTimerCtl)
{
uint32_t hrtim_timcr2;
/* Configure timing unit (Timer A to Timer F) */
hrtim_timcr2 = hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2;
/* Set the UpDown counting Mode */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_UDM);
hrtim_timcr2 |= (pTimerCtl->UpDownMode << HRTIM_TIMCR2_UDM_Pos) ;
/* Set the TrigHalf Mode : requires the counter to be disabled */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_TRGHLF);
hrtim_timcr2 |= pTimerCtl->TrigHalf;
/* define the compare event operating mode */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_GTCMP1);
hrtim_timcr2 |= pTimerCtl->GreaterCMP1;
/* define the compare event operating mode */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_GTCMP3);
hrtim_timcr2 |= pTimerCtl->GreaterCMP3;
if (pTimerCtl->DualChannelDacEnable == HRTIM_TIMER_DCDE_ENABLED)
{
/* Set the DualChannel DAC Reset trigger : requires DCDE enabled */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_DCDR);
hrtim_timcr2 |= pTimerCtl->DualChannelDacReset;
/* Set the DualChannel DAC Step trigger : requires DCDE enabled */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_DCDS);
hrtim_timcr2 |= pTimerCtl->DualChannelDacStep;
/* Enable the DualChannel DAC trigger */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_DCDE);
hrtim_timcr2 |= pTimerCtl->DualChannelDacEnable;
}
/* Update the HRTIM registers */
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2 = hrtim_timcr2;
}
/**
* @brief Configure timing RollOver Mode (Timer A to Timer F)
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param pRollOverMode: a combination of the timer RollOver Mode configuration
* @retval None
*/
static void HRTIM_TimingUnitRollOver_Config(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t pRollOverMode)
{
uint32_t hrtim_timcr2;
/* Configure timing unit (Timer A to Timer F) */
hrtim_timcr2 = hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2;
if ((hrtim_timcr2 & HRTIM_TIMCR2_UDM) != 0U)
{
/* xxROM bitfield must be reset before programming a new value */
hrtim_timcr2 &= ~(HRTIM_TIMCR2_ROM | HRTIM_TIMCR2_OUTROM |
HRTIM_TIMCR2_ADROM | HRTIM_TIMCR2_BMROM | HRTIM_TIMCR2_FEROM);
/* Update the HRTIM TIMxCR2 register */
hrtim_timcr2 |= pRollOverMode & (HRTIM_TIMCR2_ROM | HRTIM_TIMCR2_OUTROM |
HRTIM_TIMCR2_ADROM | HRTIM_TIMCR2_BMROM | HRTIM_TIMCR2_FEROM);
hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxCR2 = hrtim_timcr2;
}
}
/**
* @brief Configure a capture unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param CaptureUnit Capture unit identifier
* @param Event Event reference
* @retval None
*/
static void HRTIM_CaptureUnitConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t CaptureUnit,
uint32_t Event)
{
uint32_t CaptureTrigger = 0xFFFFFFFFU;
switch (Event)
{
case HRTIM_EVENT_1:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_1;
break;
}
case HRTIM_EVENT_2:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_2;
break;
}
case HRTIM_EVENT_3:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_3;
break;
}
case HRTIM_EVENT_4:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_4;
break;
}
case HRTIM_EVENT_5:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_5;
break;
}
case HRTIM_EVENT_6:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_6;
break;
}
case HRTIM_EVENT_7:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_7;
break;
}
case HRTIM_EVENT_8:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_8;
break;
}
case HRTIM_EVENT_9:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_9;
break;
}
case HRTIM_EVENT_10:
{
CaptureTrigger = HRTIM_CAPTURETRIGGER_EEV_10;
break;
}
default:
break;
}
switch (CaptureUnit)
{
case HRTIM_CAPTUREUNIT_1:
{
hhrtim->TimerParam[TimerIdx].CaptureTrigger1 = CaptureTrigger;
break;
}
case HRTIM_CAPTUREUNIT_2:
{
hhrtim->TimerParam[TimerIdx].CaptureTrigger2 = CaptureTrigger;
break;
}
default:
break;
}
}
/**
* @brief Configure the output of a timing unit
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param Output timing unit output identifier
* @param pOutputCfg pointer to the output configuration data structure
* @retval None
*/
static void HRTIM_OutputConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Output,
HRTIM_OutputCfgTypeDef * pOutputCfg)
{
uint32_t hrtim_outr;
uint32_t hrtim_dtr;
uint32_t shift = 0U;
hrtim_outr = hhrtim->Instance->sTimerxRegs[TimerIdx].OUTxR;
hrtim_dtr = hhrtim->Instance->sTimerxRegs[TimerIdx].DTxR;
switch (Output)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
/* Set the output set/reset crossbar */
hhrtim->Instance->sTimerxRegs[TimerIdx].SETx1R = pOutputCfg->SetSource;
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx1R = pOutputCfg->ResetSource;
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
/* Set the output set/reset crossbar */
hhrtim->Instance->sTimerxRegs[TimerIdx].SETx2R = pOutputCfg->SetSource;
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx2R = pOutputCfg->ResetSource;
shift = 16U;
break;
}
default:
break;
}
/* Clear output config */
hrtim_outr &= ~((HRTIM_OUTR_POL1 |
HRTIM_OUTR_IDLM1 |
HRTIM_OUTR_IDLES1|
HRTIM_OUTR_FAULT1|
HRTIM_OUTR_CHP1 |
HRTIM_OUTR_DIDL1) << shift);
/* Set the polarity */
hrtim_outr |= (pOutputCfg->Polarity << shift);
/* Set the IDLE mode */
hrtim_outr |= (pOutputCfg->IdleMode << shift);
/* Set the IDLE state */
hrtim_outr |= (pOutputCfg->IdleLevel << shift);
/* Set the FAULT state */
hrtim_outr |= (pOutputCfg->FaultLevel << shift);
/* Set the chopper mode */
hrtim_outr |= (pOutputCfg->ChopperModeEnable << shift);
/* Set the burst mode entry mode : deadtime insertion when entering the idle
state during a burst mode operation is allowed only under the following
conditions:
- the outputs is active during the burst mode (IDLES=1U)
- positive deadtimes (SDTR/SDTF set to 0U)
*/
if ((pOutputCfg->IdleLevel == HRTIM_OUTPUTIDLELEVEL_ACTIVE) &&
((hrtim_dtr & HRTIM_DTR_SDTR) == (uint32_t)RESET) &&
((hrtim_dtr & HRTIM_DTR_SDTF) == (uint32_t)RESET))
{
hrtim_outr |= (pOutputCfg->BurstModeEntryDelayed << shift);
}
/* Update HRTIM register */
hhrtim->Instance->sTimerxRegs[TimerIdx].OUTxR = hrtim_outr;
}
/**
* @brief Configure an external event channel
* @param hhrtim pointer to HAL HRTIM handle
* @param Event Event channel identifier
* @param pEventCfg pointer to the event channel configuration data structure
* @retval None
*/
static void HRTIM_EventConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t Event,
HRTIM_EventCfgTypeDef *pEventCfg)
{
uint32_t hrtim_eecr1;
uint32_t hrtim_eecr2;
uint32_t hrtim_eecr3;
/* Configure external event channel */
hrtim_eecr1 = hhrtim->Instance->sCommonRegs.EECR1;
hrtim_eecr2 = hhrtim->Instance->sCommonRegs.EECR2;
hrtim_eecr3 = hhrtim->Instance->sCommonRegs.EECR3;
switch (Event)
{
case HRTIM_EVENT_NONE:
{
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR1 = 0U;
hhrtim->Instance->sCommonRegs.EECR2 = 0U;
hhrtim->Instance->sCommonRegs.EECR3 = 0U;
break;
}
case HRTIM_EVENT_1:
{
hrtim_eecr1 &= ~(HRTIM_EECR1_EE1SRC | HRTIM_EECR1_EE1POL | HRTIM_EECR1_EE1SNS | HRTIM_EECR1_EE1FAST);
hrtim_eecr1 |= (pEventCfg->Source & HRTIM_EECR1_EE1SRC);
hrtim_eecr1 |= (pEventCfg->Polarity & HRTIM_EECR1_EE1POL);
hrtim_eecr1 |= (pEventCfg->Sensitivity & HRTIM_EECR1_EE1SNS);
/* Update the HRTIM registers (all bitfields but EE1FAST bit) */
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
/* Update the HRTIM registers (EE1FAST bit) */
hrtim_eecr1 |= (pEventCfg->FastMode & HRTIM_EECR1_EE1FAST);
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
break;
}
case HRTIM_EVENT_2:
{
hrtim_eecr1 &= ~(HRTIM_EECR1_EE2SRC | HRTIM_EECR1_EE2POL | HRTIM_EECR1_EE2SNS | HRTIM_EECR1_EE2FAST);
hrtim_eecr1 |= ((pEventCfg->Source << 6U) & HRTIM_EECR1_EE2SRC);
hrtim_eecr1 |= ((pEventCfg->Polarity << 6U) & HRTIM_EECR1_EE2POL);
hrtim_eecr1 |= ((pEventCfg->Sensitivity << 6U) & HRTIM_EECR1_EE2SNS);
/* Update the HRTIM registers (all bitfields but EE2FAST bit) */
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
/* Update the HRTIM registers (EE2FAST bit) */
hrtim_eecr1 |= ((pEventCfg->FastMode << 6U) & HRTIM_EECR1_EE2FAST);
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
break;
}
case HRTIM_EVENT_3:
{
hrtim_eecr1 &= ~(HRTIM_EECR1_EE3SRC | HRTIM_EECR1_EE3POL | HRTIM_EECR1_EE3SNS | HRTIM_EECR1_EE3FAST);
hrtim_eecr1 |= ((pEventCfg->Source << 12U) & HRTIM_EECR1_EE3SRC);
hrtim_eecr1 |= ((pEventCfg->Polarity << 12U) & HRTIM_EECR1_EE3POL);
hrtim_eecr1 |= ((pEventCfg->Sensitivity << 12U) & HRTIM_EECR1_EE3SNS);
/* Update the HRTIM registers (all bitfields but EE3FAST bit) */
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
/* Update the HRTIM registers (EE3FAST bit) */
hrtim_eecr1 |= ((pEventCfg->FastMode << 12U) & HRTIM_EECR1_EE3FAST);
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
break;
}
case HRTIM_EVENT_4:
{
hrtim_eecr1 &= ~(HRTIM_EECR1_EE4SRC | HRTIM_EECR1_EE4POL | HRTIM_EECR1_EE4SNS | HRTIM_EECR1_EE4FAST);
hrtim_eecr1 |= ((pEventCfg->Source << 18U) & HRTIM_EECR1_EE4SRC);
hrtim_eecr1 |= ((pEventCfg->Polarity << 18U) & HRTIM_EECR1_EE4POL);
hrtim_eecr1 |= ((pEventCfg->Sensitivity << 18U) & HRTIM_EECR1_EE4SNS);
/* Update the HRTIM registers (all bitfields but EE4FAST bit) */
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
/* Update the HRTIM registers (EE4FAST bit) */
hrtim_eecr1 |= ((pEventCfg->FastMode << 18U) & HRTIM_EECR1_EE4FAST);
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
break;
}
case HRTIM_EVENT_5:
{
hrtim_eecr1 &= ~(HRTIM_EECR1_EE5SRC | HRTIM_EECR1_EE5POL | HRTIM_EECR1_EE5SNS | HRTIM_EECR1_EE5FAST);
hrtim_eecr1 |= ((pEventCfg->Source << 24U) & HRTIM_EECR1_EE5SRC);
hrtim_eecr1 |= ((pEventCfg->Polarity << 24U) & HRTIM_EECR1_EE5POL);
hrtim_eecr1 |= ((pEventCfg->Sensitivity << 24U) & HRTIM_EECR1_EE5SNS);
/* Update the HRTIM registers (all bitfields but EE5FAST bit) */
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
/* Update the HRTIM registers (EE5FAST bit) */
hrtim_eecr1 |= ((pEventCfg->FastMode << 24U) & HRTIM_EECR1_EE5FAST);
hhrtim->Instance->sCommonRegs.EECR1 = hrtim_eecr1;
break;
}
case HRTIM_EVENT_6:
{
hrtim_eecr2 &= ~(HRTIM_EECR2_EE6SRC | HRTIM_EECR2_EE6POL | HRTIM_EECR2_EE6SNS);
hrtim_eecr2 |= (pEventCfg->Source & HRTIM_EECR2_EE6SRC);
hrtim_eecr2 |= (pEventCfg->Polarity & HRTIM_EECR2_EE6POL);
hrtim_eecr2 |= (pEventCfg->Sensitivity & HRTIM_EECR2_EE6SNS);
hrtim_eecr3 &= ~(HRTIM_EECR3_EE6F);
hrtim_eecr3 |= (pEventCfg->Filter & HRTIM_EECR3_EE6F);
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR2 = hrtim_eecr2;
hhrtim->Instance->sCommonRegs.EECR3 = hrtim_eecr3;
break;
}
case HRTIM_EVENT_7:
{
hrtim_eecr2 &= ~(HRTIM_EECR2_EE7SRC | HRTIM_EECR2_EE7POL | HRTIM_EECR2_EE7SNS);
hrtim_eecr2 |= ((pEventCfg->Source << 6U) & HRTIM_EECR2_EE7SRC);
hrtim_eecr2 |= ((pEventCfg->Polarity << 6U) & HRTIM_EECR2_EE7POL);
hrtim_eecr2 |= ((pEventCfg->Sensitivity << 6U) & HRTIM_EECR2_EE7SNS);
hrtim_eecr3 &= ~(HRTIM_EECR3_EE7F);
hrtim_eecr3 |= ((pEventCfg->Filter << 6U) & HRTIM_EECR3_EE7F);
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR2 = hrtim_eecr2;
hhrtim->Instance->sCommonRegs.EECR3 = hrtim_eecr3;
break;
}
case HRTIM_EVENT_8:
{
hrtim_eecr2 &= ~(HRTIM_EECR2_EE8SRC | HRTIM_EECR2_EE8POL | HRTIM_EECR2_EE8SNS);
hrtim_eecr2 |= ((pEventCfg->Source << 12U) & HRTIM_EECR2_EE8SRC);
hrtim_eecr2 |= ((pEventCfg->Polarity << 12U) & HRTIM_EECR2_EE8POL);
hrtim_eecr2 |= ((pEventCfg->Sensitivity << 12U) & HRTIM_EECR2_EE8SNS);
hrtim_eecr3 &= ~(HRTIM_EECR3_EE8F);
hrtim_eecr3 |= ((pEventCfg->Filter << 12U) & HRTIM_EECR3_EE8F );
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR2 = hrtim_eecr2;
hhrtim->Instance->sCommonRegs.EECR3 = hrtim_eecr3;
break;
}
case HRTIM_EVENT_9:
{
hrtim_eecr2 &= ~(HRTIM_EECR2_EE9SRC | HRTIM_EECR2_EE9POL | HRTIM_EECR2_EE9SNS);
hrtim_eecr2 |= ((pEventCfg->Source << 18U) & HRTIM_EECR2_EE9SRC);
hrtim_eecr2 |= ((pEventCfg->Polarity << 18U) & HRTIM_EECR2_EE9POL);
hrtim_eecr2 |= ((pEventCfg->Sensitivity << 18U) & HRTIM_EECR2_EE9SNS);
hrtim_eecr3 &= ~(HRTIM_EECR3_EE9F);
hrtim_eecr3 |= ((pEventCfg->Filter << 18U) & HRTIM_EECR3_EE9F);
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR2 = hrtim_eecr2;
hhrtim->Instance->sCommonRegs.EECR3 = hrtim_eecr3;
break;
}
case HRTIM_EVENT_10:
{
hrtim_eecr2 &= ~(HRTIM_EECR2_EE10SRC | HRTIM_EECR2_EE10POL | HRTIM_EECR2_EE10SNS);
hrtim_eecr2 |= ((pEventCfg->Source << 24U) & HRTIM_EECR2_EE10SRC);
hrtim_eecr2 |= ((pEventCfg->Polarity << 24U) & HRTIM_EECR2_EE10POL);
hrtim_eecr2 |= ((pEventCfg->Sensitivity << 24U) & HRTIM_EECR2_EE10SNS);
hrtim_eecr3 &= ~(HRTIM_EECR3_EE10F);
hrtim_eecr3 |= ((pEventCfg->Filter << 24U) & HRTIM_EECR3_EE10F);
/* Update the HRTIM registers */
hhrtim->Instance->sCommonRegs.EECR2 = hrtim_eecr2;
hhrtim->Instance->sCommonRegs.EECR3 = hrtim_eecr3;
break;
}
default:
break;
}
}
/**
* @brief Configure the timer counter reset
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param Event Event channel identifier
* @retval None
*/
static void HRTIM_TIM_ResetConfig(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t Event)
{
switch (Event)
{
case HRTIM_EVENT_1:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_1;
break;
}
case HRTIM_EVENT_2:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_2;
break;
}
case HRTIM_EVENT_3:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_3;
break;
}
case HRTIM_EVENT_4:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_4;
break;
}
case HRTIM_EVENT_5:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_5;
break;
}
case HRTIM_EVENT_6:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_6;
break;
}
case HRTIM_EVENT_7:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_7;
break;
}
case HRTIM_EVENT_8:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_8;
break;
}
case HRTIM_EVENT_9:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_9;
break;
}
case HRTIM_EVENT_10:
{
hhrtim->Instance->sTimerxRegs[TimerIdx].RSTxR = HRTIM_TIMRESETTRIGGER_EEV_10;
break;
}
default:
break;
}
}
/**
* @brief Return the interrupt to enable or disable according to the
* OC mode.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval Interrupt to enable or disable
*/
static uint32_t HRTIM_GetITFromOCMode(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
uint32_t hrtim_set;
uint32_t hrtim_reset;
uint32_t interrupt = 0U;
switch (OCChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
/* Retreives actual OC mode and set interrupt accordingly */
hrtim_set = hhrtim->Instance->sTimerxRegs[TimerIdx].SETx1R;
hrtim_reset = hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx1R;
if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP1) == HRTIM_OUTPUTSET_TIMCMP1) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP1) == HRTIM_OUTPUTRESET_TIMCMP1))
{
/* OC mode: HRTIM_BASICOCMODE_TOGGLE */
interrupt = HRTIM_TIM_IT_CMP1;
}
else if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP1) == HRTIM_OUTPUTSET_TIMCMP1) &&
(hrtim_reset == 0U))
{
/* OC mode: HRTIM_BASICOCMODE_ACTIVE */
interrupt = HRTIM_TIM_IT_SET1;
}
else if ((hrtim_set == 0U) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP1) == HRTIM_OUTPUTRESET_TIMCMP1))
{
/* OC mode: HRTIM_BASICOCMODE_INACTIVE */
interrupt = HRTIM_TIM_IT_RST1;
}
else
{
/* nothing to do */
}
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
/* Retreives actual OC mode and set interrupt accordingly */
hrtim_set = hhrtim->Instance->sTimerxRegs[TimerIdx].SETx2R;
hrtim_reset = hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx2R;
if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP2) == HRTIM_OUTPUTSET_TIMCMP2) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP2) == HRTIM_OUTPUTRESET_TIMCMP2))
{
/* OC mode: HRTIM_BASICOCMODE_TOGGLE */
interrupt = HRTIM_TIM_IT_CMP2;
}
else if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP2) == HRTIM_OUTPUTSET_TIMCMP2) &&
(hrtim_reset == 0U))
{
/* OC mode: HRTIM_BASICOCMODE_ACTIVE */
interrupt = HRTIM_TIM_IT_SET2;
}
else if ((hrtim_set == 0U) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP2) == HRTIM_OUTPUTRESET_TIMCMP2))
{
/* OC mode: HRTIM_BASICOCMODE_INACTIVE */
interrupt = HRTIM_TIM_IT_RST2;
}
else
{
/* nothing to do */
}
break;
}
default:
break;
}
return interrupt;
}
/**
* @brief Return the DMA request to enable or disable according to the
* OC mode.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @param OCChannel Timer output
* This parameter can be one of the following values:
* @arg HRTIM_OUTPUT_TA1: Timer A - Output 1
* @arg HRTIM_OUTPUT_TA2: Timer A - Output 2
* @arg HRTIM_OUTPUT_TB1: Timer B - Output 1
* @arg HRTIM_OUTPUT_TB2: Timer B - Output 2
* @arg HRTIM_OUTPUT_TC1: Timer C - Output 1
* @arg HRTIM_OUTPUT_TC2: Timer C - Output 2
* @arg HRTIM_OUTPUT_TD1: Timer D - Output 1
* @arg HRTIM_OUTPUT_TD2: Timer D - Output 2
* @arg HRTIM_OUTPUT_TE1: Timer E - Output 1
* @arg HRTIM_OUTPUT_TE2: Timer E - Output 2
* @arg HRTIM_OUTPUT_TF1: Timer F - Output 1
* @arg HRTIM_OUTPUT_TF2: Timer F - Output 2
* @retval DMA request to enable or disable
*/
static uint32_t HRTIM_GetDMAFromOCMode(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx,
uint32_t OCChannel)
{
uint32_t hrtim_set;
uint32_t hrtim_reset;
uint32_t dma_request = 0U;
switch (OCChannel)
{
case HRTIM_OUTPUT_TA1:
case HRTIM_OUTPUT_TB1:
case HRTIM_OUTPUT_TC1:
case HRTIM_OUTPUT_TD1:
case HRTIM_OUTPUT_TE1:
case HRTIM_OUTPUT_TF1:
{
/* Retreives actual OC mode and set dma_request accordingly */
hrtim_set = hhrtim->Instance->sTimerxRegs[TimerIdx].SETx1R;
hrtim_reset = hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx1R;
if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP1) == HRTIM_OUTPUTSET_TIMCMP1) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP1) == HRTIM_OUTPUTRESET_TIMCMP1))
{
/* OC mode: HRTIM_BASICOCMODE_TOGGLE */
dma_request = HRTIM_TIM_DMA_CMP1;
}
else if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP1) == HRTIM_OUTPUTSET_TIMCMP1) &&
(hrtim_reset == 0U))
{
/* OC mode: HRTIM_BASICOCMODE_ACTIVE */
dma_request = HRTIM_TIM_DMA_SET1;
}
else if ((hrtim_set == 0U) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP1) == HRTIM_OUTPUTRESET_TIMCMP1))
{
/* OC mode: HRTIM_BASICOCMODE_INACTIVE */
dma_request = HRTIM_TIM_DMA_RST1;
}
else
{
/* nothing to do */
}
break;
}
case HRTIM_OUTPUT_TA2:
case HRTIM_OUTPUT_TB2:
case HRTIM_OUTPUT_TC2:
case HRTIM_OUTPUT_TD2:
case HRTIM_OUTPUT_TE2:
case HRTIM_OUTPUT_TF2:
{
/* Retreives actual OC mode and set dma_request accordingly */
hrtim_set = hhrtim->Instance->sTimerxRegs[TimerIdx].SETx2R;
hrtim_reset = hhrtim->Instance->sTimerxRegs[TimerIdx].RSTx2R;
if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP2) == HRTIM_OUTPUTSET_TIMCMP2) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP2) == HRTIM_OUTPUTRESET_TIMCMP2))
{
/* OC mode: HRTIM_BASICOCMODE_TOGGLE */
dma_request = HRTIM_TIM_DMA_CMP2;
}
else if (((hrtim_set & HRTIM_OUTPUTSET_TIMCMP2) == HRTIM_OUTPUTSET_TIMCMP2) &&
(hrtim_reset == 0U))
{
/* OC mode: HRTIM_BASICOCMODE_ACTIVE */
dma_request = HRTIM_TIM_DMA_SET2;
}
else if ((hrtim_set == 0U) &&
((hrtim_reset & HRTIM_OUTPUTRESET_TIMCMP2) == HRTIM_OUTPUTRESET_TIMCMP2))
{
/* OC mode: HRTIM_BASICOCMODE_INACTIVE */
dma_request = HRTIM_TIM_DMA_RST2;
}
else
{
/* nothing to do */
}
break;
}
default:
break;
}
return dma_request;
}
static DMA_HandleTypeDef * HRTIM_GetDMAHandleFromTimerIdx(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
DMA_HandleTypeDef * hdma = (DMA_HandleTypeDef *)NULL;
switch (TimerIdx)
{
case HRTIM_TIMERINDEX_MASTER:
{
hdma = hhrtim->hdmaMaster;
break;
}
case HRTIM_TIMERINDEX_TIMER_A:
{
hdma = hhrtim->hdmaTimerA;
break;
}
case HRTIM_TIMERINDEX_TIMER_B:
{
hdma = hhrtim->hdmaTimerB;
break;
}
case HRTIM_TIMERINDEX_TIMER_C:
{
hdma = hhrtim->hdmaTimerC;
break;
}
case HRTIM_TIMERINDEX_TIMER_D:
{
hdma = hhrtim->hdmaTimerD;
break;
}
case HRTIM_TIMERINDEX_TIMER_E:
{
hdma = hhrtim->hdmaTimerE;
break;
}
case HRTIM_TIMERINDEX_TIMER_F:
{
hdma = hhrtim->hdmaTimerF;
break;
}
default:
break;
}
return hdma;
}
static uint32_t GetTimerIdxFromDMAHandle(HRTIM_HandleTypeDef * hhrtim,
DMA_HandleTypeDef * hdma)
{
uint32_t timed_idx = 0xFFFFFFFFU;
if (hdma == hhrtim->hdmaMaster)
{
timed_idx = HRTIM_TIMERINDEX_MASTER;
}
else if (hdma == hhrtim->hdmaTimerA)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_A;
}
else if (hdma == hhrtim->hdmaTimerB)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_B;
}
else if (hdma == hhrtim->hdmaTimerC)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_C;
}
else if (hdma == hhrtim->hdmaTimerD)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_D;
}
else if (hdma == hhrtim->hdmaTimerE)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_E;
}
else if (hdma == hhrtim->hdmaTimerF)
{
timed_idx = HRTIM_TIMERINDEX_TIMER_F;
}
else
{
/* nothing to do */
}
return timed_idx;
}
/**
* @brief Force an immediate transfer from the preload to the active
* registers.
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* @retval None
*/
static void HRTIM_ForceRegistersUpdate(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
switch (TimerIdx)
{
case HRTIM_TIMERINDEX_MASTER:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_MSWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_A:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TASWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_B:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TBSWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_C:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TCSWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_D:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TDSWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_E:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TESWU;
break;
}
case HRTIM_TIMERINDEX_TIMER_F:
{
hhrtim->Instance->sCommonRegs.CR2 |= HRTIM_CR2_TFSWU;
break;
}
default:
break;
}
}
/**
* @brief HRTIM interrupts service routine
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
static void HRTIM_HRTIM_ISR(HRTIM_HandleTypeDef * hhrtim)
{
uint32_t isrflags = READ_REG(hhrtim->Instance->sCommonRegs.ISR);
uint32_t ierits = READ_REG(hhrtim->Instance->sCommonRegs.IER);
/* Fault 1 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT1) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT1) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT1);
/* Invoke Fault 1 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault1Callback(hhrtim);
#else
HAL_HRTIM_Fault1Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Fault 2 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT2) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT2) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT2);
/* Invoke Fault 2 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault2Callback(hhrtim);
#else
HAL_HRTIM_Fault2Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Fault 3 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT3) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT3) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT3);
/* Invoke Fault 3 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault3Callback(hhrtim);
#else
HAL_HRTIM_Fault3Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Fault 4 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT4) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT4) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT4);
/* Invoke Fault 4 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault4Callback(hhrtim);
#else
HAL_HRTIM_Fault4Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Fault 5 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT5) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT5) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT5);
/* Invoke Fault 5 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault5Callback(hhrtim);
#else
HAL_HRTIM_Fault5Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Fault 6 event */
if((uint32_t)(isrflags & HRTIM_FLAG_FLT6) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_FLT6) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_FLT6);
/* Invoke Fault 6 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Fault6Callback(hhrtim);
#else
HAL_HRTIM_Fault6Callback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* System fault event */
if((uint32_t)(isrflags & HRTIM_FLAG_SYSFLT) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_SYSFLT) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_SYSFLT);
/* Invoke System fault event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->SystemFaultCallback(hhrtim);
#else
HAL_HRTIM_SystemFaultCallback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
}
/**
* @brief Master timer interrupts service routine
* @param hhrtim pointer to HAL HRTIM handle
* @retval None
*/
static void HRTIM_Master_ISR(HRTIM_HandleTypeDef * hhrtim)
{
uint32_t isrflags = READ_REG(hhrtim->Instance->sCommonRegs.ISR);
uint32_t ierits = READ_REG(hhrtim->Instance->sCommonRegs.IER);
uint32_t misrflags = READ_REG(hhrtim->Instance->sMasterRegs.MISR);
uint32_t mdierits = READ_REG(hhrtim->Instance->sMasterRegs.MDIER);
/* DLL calibration ready event */
if((uint32_t)(isrflags & HRTIM_FLAG_DLLRDY) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_DLLRDY) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_DLLRDY);
/* Set HRTIM State */
hhrtim->State = HAL_HRTIM_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hhrtim);
/* Invoke System fault event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->DLLCalibrationReadyCallback(hhrtim);
#else
HAL_HRTIM_DLLCalibrationReadyCallback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Burst mode period event */
if((uint32_t)(isrflags & HRTIM_FLAG_BMPER) != (uint32_t)RESET)
{
if((uint32_t)(ierits & HRTIM_IT_BMPER) != (uint32_t)RESET)
{
__HAL_HRTIM_CLEAR_IT(hhrtim, HRTIM_IT_BMPER);
/* Invoke Burst mode period event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->BurstModePeriodCallback(hhrtim);
#else
HAL_HRTIM_BurstModePeriodCallback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer compare 1 event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MCMP1) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MCMP1) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MCMP1);
/* Invoke compare 1 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare1EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare1EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer compare 2 event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MCMP2) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MCMP2) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MCMP2);
/* Invoke compare 2 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare2EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare2EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer compare 3 event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MCMP3) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MCMP3) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MCMP3);
/* Invoke compare 3 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare3EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare3EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer compare 4 event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MCMP4) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MCMP4) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MCMP4);
/* Invoke compare 4 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare4EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare4EventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer repetition event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MREP) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MREP) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MREP);
/* Invoke repetition event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->RepetitionEventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_RepetitionEventCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Synchronization input event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_SYNC) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_SYNC) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_SYNC);
/* Invoke synchronization event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->SynchronizationEventCallback(hhrtim);
#else
HAL_HRTIM_SynchronizationEventCallback(hhrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Master timer registers update event */
if((uint32_t)(misrflags & HRTIM_MASTER_FLAG_MUPD) != (uint32_t)RESET)
{
if((uint32_t)(mdierits & HRTIM_MASTER_IT_MUPD) != (uint32_t)RESET)
{
__HAL_HRTIM_MASTER_CLEAR_IT(hhrtim, HRTIM_MASTER_IT_MUPD);
/* Invoke registers update event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->RegistersUpdateCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_RegistersUpdateCallback(hhrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
}
/**
* @brief Timer interrupts service routine
* @param hhrtim pointer to HAL HRTIM handle
* @param TimerIdx Timer index
* This parameter can be one of the following values:
* @arg HRTIM_TIMERINDEX_TIMER_A for timer A
* @arg HRTIM_TIMERINDEX_TIMER_B for timer B
* @arg HRTIM_TIMERINDEX_TIMER_C for timer C
* @arg HRTIM_TIMERINDEX_TIMER_D for timer D
* @arg HRTIM_TIMERINDEX_TIMER_E for timer E
* @arg HRTIM_TIMERINDEX_TIMER_F for timer F
* @retval None
*/
static void HRTIM_Timer_ISR(HRTIM_HandleTypeDef * hhrtim,
uint32_t TimerIdx)
{
uint32_t tisrflags = READ_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxISR);
uint32_t tdierits = READ_REG(hhrtim->Instance->sTimerxRegs[TimerIdx].TIMxDIER);
/* Timer compare 1 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CMP1) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CMP1) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP1);
/* Invoke compare 1 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare1EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Compare1EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer compare 2 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CMP2) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CMP2) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP2);
/* Invoke compare 2 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare2EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Compare2EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer compare 3 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CMP3) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CMP3) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP3);
/* Invoke compare 3 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare3EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Compare3EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer compare 4 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CMP4) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CMP4) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CMP4);
/* Invoke compare 4 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Compare4EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Compare4EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer repetition event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_REP) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_REP) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_REP);
/* Invoke repetition event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->RepetitionEventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_RepetitionEventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer registers update event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_UPD) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_UPD) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_UPD);
/* Invoke registers update event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->RegistersUpdateCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_RegistersUpdateCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer capture 1 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CPT1) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CPT1) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT1);
/* Invoke capture 1 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Capture1EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Capture1EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer capture 2 event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_CPT2) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_CPT2) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_CPT2);
/* Invoke capture 2 event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Capture2EventCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Capture2EventCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer output 1 set event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_SET1) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_SET1) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_SET1);
/* Invoke output 1 set event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Output1SetCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Output1SetCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer output 1 reset event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_RST1) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_RST1) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_RST1);
/* Invoke output 1 reset event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Output1ResetCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Output1ResetCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer output 2 set event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_SET2) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_SET2) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_SET2);
/* Invoke output 2 set event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Output2SetCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Output2SetCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer output 2 reset event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_RST2) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_RST2) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_RST2);
/* Invoke output 2 reset event callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->Output2ResetCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_Output2ResetCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Timer reset event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_RST) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_RST) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_RST);
/* Invoke timer reset callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->CounterResetCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_CounterResetCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
/* Delayed protection event */
if((uint32_t)(tisrflags & HRTIM_TIM_FLAG_DLYPRT) != (uint32_t)RESET)
{
if((uint32_t)(tdierits & HRTIM_TIM_IT_DLYPRT) != (uint32_t)RESET)
{
__HAL_HRTIM_TIMER_CLEAR_IT(hhrtim, TimerIdx, HRTIM_TIM_IT_DLYPRT);
/* Invoke delayed protection callback */
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hhrtim->DelayedProtectionCallback(hhrtim, TimerIdx);
#else
HAL_HRTIM_DelayedProtectionCallback(hhrtim, TimerIdx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
}
}
/**
* @brief DMA callback invoked upon master timer related DMA request completion
* @param hdma pointer to DMA handle.
* @retval None
*/
static void HRTIM_DMAMasterCplt(DMA_HandleTypeDef *hdma)
{
HRTIM_HandleTypeDef * hrtim = (HRTIM_HandleTypeDef *)((DMA_HandleTypeDef* )hdma)->Parent;
if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MCMP1) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare1EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare1EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MCMP2) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare2EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare2EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MCMP3) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare3EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare3EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MCMP4) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare4EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_Compare4EventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_SYNC) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->SynchronizationEventCallback(hrtim);
#else
HAL_HRTIM_SynchronizationEventCallback(hrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MUPD) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->RegistersUpdateCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_RegistersUpdateCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sMasterRegs.MDIER & HRTIM_MASTER_DMA_MREP) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->RepetitionEventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#else
HAL_HRTIM_RepetitionEventCallback(hrtim, HRTIM_TIMERINDEX_MASTER);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else
{
/* nothing to do */
}
}
/**
* @brief DMA callback invoked upon timer A..F related DMA request completion
* @param hdma pointer to DMA handle.
* @retval None
*/
static void HRTIM_DMATimerxCplt(DMA_HandleTypeDef *hdma)
{
uint8_t timer_idx;
HRTIM_HandleTypeDef * hrtim = (HRTIM_HandleTypeDef *)((DMA_HandleTypeDef* )hdma)->Parent;
timer_idx = (uint8_t)GetTimerIdxFromDMAHandle(hrtim, hdma);
if ( !IS_HRTIM_TIMING_UNIT(timer_idx) ) {return;}
if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CMP1) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare1EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Compare1EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CMP2) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare2EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Compare2EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CMP3) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare3EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Compare3EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CMP4) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Compare4EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Compare4EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_UPD) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->RegistersUpdateCallback(hrtim, timer_idx);
#else
HAL_HRTIM_RegistersUpdateCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CPT1) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Capture1EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Capture1EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_CPT2) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Capture2EventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Capture2EventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_SET1) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Output1SetCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Output1SetCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_RST1) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Output1ResetCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Output1ResetCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_SET2) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Output2SetCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Output2SetCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_RST2) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->Output2ResetCallback(hrtim, timer_idx);
#else
HAL_HRTIM_Output2ResetCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_RST) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->CounterResetCallback(hrtim, timer_idx);
#else
HAL_HRTIM_CounterResetCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_DLYPRT) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->DelayedProtectionCallback(hrtim, timer_idx);
#else
HAL_HRTIM_DelayedProtectionCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else if ((hrtim->Instance->sTimerxRegs[timer_idx].TIMxDIER & HRTIM_TIM_DMA_REP) != (uint32_t)RESET)
{
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->RepetitionEventCallback(hrtim, timer_idx);
#else
HAL_HRTIM_RepetitionEventCallback(hrtim, timer_idx);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
else
{
/* nothing to do */
}
}
/**
* @brief DMA error callback
* @param hdma pointer to DMA handle.
* @retval None
*/
static void HRTIM_DMAError(DMA_HandleTypeDef *hdma)
{
HRTIM_HandleTypeDef * hrtim = (HRTIM_HandleTypeDef *)((DMA_HandleTypeDef* )hdma)->Parent;
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->ErrorCallback(hrtim);
#else
HAL_HRTIM_ErrorCallback(hrtim);
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
/**
* @brief DMA callback invoked upon burst DMA transfer completion
* @param hdma pointer to DMA handle.
* @retval None
*/
static void HRTIM_BurstDMACplt(DMA_HandleTypeDef *hdma)
{
HRTIM_HandleTypeDef * hrtim = (HRTIM_HandleTypeDef *)((DMA_HandleTypeDef* )hdma)->Parent;
#if (USE_HAL_HRTIM_REGISTER_CALLBACKS == 1)
hrtim->BurstDMATransferCallback(hrtim, GetTimerIdxFromDMAHandle(hrtim, hdma));
#else
HAL_HRTIM_BurstDMATransferCallback(hrtim, GetTimerIdxFromDMAHandle(hrtim, hdma));
#endif /* USE_HAL_HRTIM_REGISTER_CALLBACKS */
}
/**
* @}
*/
/**
* @}
*/
#endif /* HRTIM1 */
#endif /* HAL_HRTIM_MODULE_ENABLED */
/**
* @}
*/
| 390,302 |
C
| 34.156098 | 190 | 0.608355 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_fdcan.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_fdcan.c
* @author MCD Application Team
* @brief FDCAN HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Flexible DataRate Controller Area Network
* (FDCAN) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral Configuration and Control functions
* + Peripheral State and Error functions
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
(#) Initialize the FDCAN peripheral using HAL_FDCAN_Init function.
(#) If needed , configure the reception filters and optional features using
the following configuration functions:
(++) HAL_FDCAN_ConfigFilter
(++) HAL_FDCAN_ConfigGlobalFilter
(++) HAL_FDCAN_ConfigExtendedIdMask
(++) HAL_FDCAN_ConfigRxFifoOverwrite
(++) HAL_FDCAN_ConfigRamWatchdog
(++) HAL_FDCAN_ConfigTimestampCounter
(++) HAL_FDCAN_EnableTimestampCounter
(++) HAL_FDCAN_DisableTimestampCounter
(++) HAL_FDCAN_ConfigTimeoutCounter
(++) HAL_FDCAN_EnableTimeoutCounter
(++) HAL_FDCAN_DisableTimeoutCounter
(++) HAL_FDCAN_ConfigTxDelayCompensation
(++) HAL_FDCAN_EnableTxDelayCompensation
(++) HAL_FDCAN_DisableTxDelayCompensation
(++) HAL_FDCAN_EnableISOMode
(++) HAL_FDCAN_DisableISOMode
(++) HAL_FDCAN_EnableEdgeFiltering
(++) HAL_FDCAN_DisableEdgeFiltering
(#) Start the FDCAN module using HAL_FDCAN_Start function. At this level
the node is active on the bus: it can send and receive messages.
(#) The following Tx control functions can only be called when the FDCAN
module is started:
(++) HAL_FDCAN_AddMessageToTxFifoQ
(++) HAL_FDCAN_AbortTxRequest
(#) After having submitted a Tx request in Tx Fifo or Queue, it is possible to
get Tx buffer location used to place the Tx request thanks to
HAL_FDCAN_GetLatestTxFifoQRequestBuffer API.
It is then possible to abort later on the corresponding Tx Request using
HAL_FDCAN_AbortTxRequest API.
(#) When a message is received into the FDCAN message RAM, it can be
retrieved using the HAL_FDCAN_GetRxMessage function.
(#) Calling the HAL_FDCAN_Stop function stops the FDCAN module by entering
it to initialization mode and re-enabling access to configuration
registers through the configuration functions listed here above.
(#) All other control functions can be called any time after initialization
phase, no matter if the FDCAN module is started or stopped.
*** Polling mode operation ***
==============================
[..]
(#) Reception and transmission states can be monitored via the following
functions:
(++) HAL_FDCAN_IsTxBufferMessagePending
(++) HAL_FDCAN_GetRxFifoFillLevel
(++) HAL_FDCAN_GetTxFifoFreeLevel
*** Interrupt mode operation ***
================================
[..]
(#) There are two interrupt lines: line 0 and 1.
By default, all interrupts are assigned to line 0. Interrupt lines
can be configured using HAL_FDCAN_ConfigInterruptLines function.
(#) Notifications are activated using HAL_FDCAN_ActivateNotification
function. Then, the process can be controlled through one of the
available user callbacks: HAL_FDCAN_xxxCallback.
*** Callback registration ***
=============================================
The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Function HAL_FDCAN_RegisterCallback() or HAL_FDCAN_RegisterXXXCallback()
to register an interrupt callback.
Function HAL_FDCAN_RegisterCallback() allows to register following callbacks:
(+) TxFifoEmptyCallback : Tx Fifo Empty Callback.
(+) HighPriorityMessageCallback : High Priority Message Callback.
(+) TimestampWraparoundCallback : Timestamp Wraparound Callback.
(+) TimeoutOccurredCallback : Timeout Occurred Callback.
(+) ErrorCallback : Error Callback.
(+) MspInitCallback : FDCAN MspInit.
(+) MspDeInitCallback : FDCAN MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback,
TxBufferCompleteCallback, TxBufferAbortCallback and ErrorStatusCallback use dedicated
register callbacks : respectively HAL_FDCAN_RegisterTxEventFifoCallback(),
HAL_FDCAN_RegisterRxFifo0Callback(), HAL_FDCAN_RegisterRxFifo1Callback(),
HAL_FDCAN_RegisterTxBufferCompleteCallback(), HAL_FDCAN_RegisterTxBufferAbortCallback()
and HAL_FDCAN_RegisterErrorStatusCallback().
Use function HAL_FDCAN_UnRegisterCallback() to reset a callback to the default
weak function.
HAL_FDCAN_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) TxFifoEmptyCallback : Tx Fifo Empty Callback.
(+) HighPriorityMessageCallback : High Priority Message Callback.
(+) TimestampWraparoundCallback : Timestamp Wraparound Callback.
(+) TimeoutOccurredCallback : Timeout Occurred Callback.
(+) ErrorCallback : Error Callback.
(+) MspInitCallback : FDCAN MspInit.
(+) MspDeInitCallback : FDCAN MspDeInit.
For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback,
TxBufferCompleteCallback and TxBufferAbortCallback, use dedicated
unregister callbacks : respectively HAL_FDCAN_UnRegisterTxEventFifoCallback(),
HAL_FDCAN_UnRegisterRxFifo0Callback(), HAL_FDCAN_UnRegisterRxFifo1Callback(),
HAL_FDCAN_UnRegisterTxBufferCompleteCallback(), HAL_FDCAN_UnRegisterTxBufferAbortCallback()
and HAL_FDCAN_UnRegisterErrorStatusCallback().
By default, after the HAL_FDCAN_Init() and when the state is HAL_FDCAN_STATE_RESET,
all callbacks are set to the corresponding weak functions:
examples HAL_FDCAN_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak function in the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit() only when
these callbacks are null (not registered beforehand).
if not, MspInit or MspDeInit are not null, the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
Callbacks can be registered/unregistered in HAL_FDCAN_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_FDCAN_STATE_READY or HAL_FDCAN_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_FDCAN_RegisterCallback() before calling HAL_FDCAN_DeInit()
or HAL_FDCAN_Init() function.
When The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available and all callbacks
are set to the corresponding weak functions.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#if defined(FDCAN1)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup FDCAN FDCAN
* @brief FDCAN HAL module driver
* @{
*/
#ifdef HAL_FDCAN_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup FDCAN_Private_Constants
* @{
*/
#define FDCAN_TIMEOUT_VALUE 10U
#define FDCAN_TX_EVENT_FIFO_MASK (FDCAN_IR_TEFL | FDCAN_IR_TEFF | FDCAN_IR_TEFN)
#define FDCAN_RX_FIFO0_MASK (FDCAN_IR_RF0L | FDCAN_IR_RF0F | FDCAN_IR_RF0N)
#define FDCAN_RX_FIFO1_MASK (FDCAN_IR_RF1L | FDCAN_IR_RF1F | FDCAN_IR_RF1N)
#define FDCAN_ERROR_MASK (FDCAN_IR_ELO | FDCAN_IR_WDI | FDCAN_IR_PEA | FDCAN_IR_PED | FDCAN_IR_ARA)
#define FDCAN_ERROR_STATUS_MASK (FDCAN_IR_EP | FDCAN_IR_EW | FDCAN_IR_BO)
#define FDCAN_ELEMENT_MASK_STDID ((uint32_t)0x1FFC0000U) /* Standard Identifier */
#define FDCAN_ELEMENT_MASK_EXTID ((uint32_t)0x1FFFFFFFU) /* Extended Identifier */
#define FDCAN_ELEMENT_MASK_RTR ((uint32_t)0x20000000U) /* Remote Transmission Request */
#define FDCAN_ELEMENT_MASK_XTD ((uint32_t)0x40000000U) /* Extended Identifier */
#define FDCAN_ELEMENT_MASK_ESI ((uint32_t)0x80000000U) /* Error State Indicator */
#define FDCAN_ELEMENT_MASK_TS ((uint32_t)0x0000FFFFU) /* Timestamp */
#define FDCAN_ELEMENT_MASK_DLC ((uint32_t)0x000F0000U) /* Data Length Code */
#define FDCAN_ELEMENT_MASK_BRS ((uint32_t)0x00100000U) /* Bit Rate Switch */
#define FDCAN_ELEMENT_MASK_FDF ((uint32_t)0x00200000U) /* FD Format */
#define FDCAN_ELEMENT_MASK_EFC ((uint32_t)0x00800000U) /* Event FIFO Control */
#define FDCAN_ELEMENT_MASK_MM ((uint32_t)0xFF000000U) /* Message Marker */
#define FDCAN_ELEMENT_MASK_FIDX ((uint32_t)0x7F000000U) /* Filter Index */
#define FDCAN_ELEMENT_MASK_ANMF ((uint32_t)0x80000000U) /* Accepted Non-matching Frame */
#define FDCAN_ELEMENT_MASK_ET ((uint32_t)0x00C00000U) /* Event type */
#define SRAMCAN_FLS_NBR (28U) /* Max. Filter List Standard Number */
#define SRAMCAN_FLE_NBR ( 8U) /* Max. Filter List Extended Number */
#define SRAMCAN_RF0_NBR ( 3U) /* RX FIFO 0 Elements Number */
#define SRAMCAN_RF1_NBR ( 3U) /* RX FIFO 1 Elements Number */
#define SRAMCAN_TEF_NBR ( 3U) /* TX Event FIFO Elements Number */
#define SRAMCAN_TFQ_NBR ( 3U) /* TX FIFO/Queue Elements Number */
#define SRAMCAN_FLS_SIZE ( 1U * 4U) /* Filter Standard Element Size in bytes */
#define SRAMCAN_FLE_SIZE ( 2U * 4U) /* Filter Extended Element Size in bytes */
#define SRAMCAN_RF0_SIZE (18U * 4U) /* RX FIFO 0 Elements Size in bytes */
#define SRAMCAN_RF1_SIZE (18U * 4U) /* RX FIFO 1 Elements Size in bytes */
#define SRAMCAN_TEF_SIZE ( 2U * 4U) /* TX Event FIFO Elements Size in bytes */
#define SRAMCAN_TFQ_SIZE (18U * 4U) /* TX FIFO/Queue Elements Size in bytes */
#define SRAMCAN_FLSSA ((uint32_t)0) /* Filter List Standard Start
Address */
#define SRAMCAN_FLESA ((uint32_t)(SRAMCAN_FLSSA + (SRAMCAN_FLS_NBR * SRAMCAN_FLS_SIZE))) /* Filter List Extended Start
Address */
#define SRAMCAN_RF0SA ((uint32_t)(SRAMCAN_FLESA + (SRAMCAN_FLE_NBR * SRAMCAN_FLE_SIZE))) /* Rx FIFO 0 Start Address */
#define SRAMCAN_RF1SA ((uint32_t)(SRAMCAN_RF0SA + (SRAMCAN_RF0_NBR * SRAMCAN_RF0_SIZE))) /* Rx FIFO 1 Start Address */
#define SRAMCAN_TEFSA ((uint32_t)(SRAMCAN_RF1SA + (SRAMCAN_RF1_NBR * SRAMCAN_RF1_SIZE))) /* Tx Event FIFO Start
Address */
#define SRAMCAN_TFQSA ((uint32_t)(SRAMCAN_TEFSA + (SRAMCAN_TEF_NBR * SRAMCAN_TEF_SIZE))) /* Tx FIFO/Queue Start
Address */
#define SRAMCAN_SIZE ((uint32_t)(SRAMCAN_TFQSA + (SRAMCAN_TFQ_NBR * SRAMCAN_TFQ_SIZE))) /* Message RAM size */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @addtogroup FDCAN_Private_Variables
* @{
*/
static const uint8_t DLCtoBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64};
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan);
static void FDCAN_CopyMessageToRAM(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxHeaderTypeDef *pTxHeader, uint8_t *pTxData,
uint32_t BufferIndex);
/* Exported functions --------------------------------------------------------*/
/** @defgroup FDCAN_Exported_Functions FDCAN Exported Functions
* @{
*/
/** @defgroup FDCAN_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Initialize and configure the FDCAN.
(+) De-initialize the FDCAN.
(+) Enter FDCAN peripheral in power down mode.
(+) Exit power down mode.
(+) Register callbacks.
(+) Unregister callbacks.
@endverbatim
* @{
*/
/**
* @brief Initializes the FDCAN peripheral according to the specified
* parameters in the FDCAN_InitTypeDef structure.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_Init(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t tickstart;
/* Check FDCAN handle */
if (hfdcan == NULL)
{
return HAL_ERROR;
}
/* Check function parameters */
assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance));
if (hfdcan->Instance == FDCAN1)
{
assert_param(IS_FDCAN_CKDIV(hfdcan->Init.ClockDivider));
}
assert_param(IS_FDCAN_FRAME_FORMAT(hfdcan->Init.FrameFormat));
assert_param(IS_FDCAN_MODE(hfdcan->Init.Mode));
assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.AutoRetransmission));
assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.TransmitPause));
assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.ProtocolException));
assert_param(IS_FDCAN_NOMINAL_PRESCALER(hfdcan->Init.NominalPrescaler));
assert_param(IS_FDCAN_NOMINAL_SJW(hfdcan->Init.NominalSyncJumpWidth));
assert_param(IS_FDCAN_NOMINAL_TSEG1(hfdcan->Init.NominalTimeSeg1));
assert_param(IS_FDCAN_NOMINAL_TSEG2(hfdcan->Init.NominalTimeSeg2));
if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS)
{
assert_param(IS_FDCAN_DATA_PRESCALER(hfdcan->Init.DataPrescaler));
assert_param(IS_FDCAN_DATA_SJW(hfdcan->Init.DataSyncJumpWidth));
assert_param(IS_FDCAN_DATA_TSEG1(hfdcan->Init.DataTimeSeg1));
assert_param(IS_FDCAN_DATA_TSEG2(hfdcan->Init.DataTimeSeg2));
}
assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.StdFiltersNbr, SRAMCAN_FLS_NBR));
assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.ExtFiltersNbr, SRAMCAN_FLE_NBR));
assert_param(IS_FDCAN_TX_FIFO_QUEUE_MODE(hfdcan->Init.TxFifoQueueMode));
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
if (hfdcan->State == HAL_FDCAN_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hfdcan->Lock = HAL_UNLOCKED;
/* Reset callbacks to legacy functions */
hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* Legacy weak TxEventFifoCallback */
hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* Legacy weak RxFifo0Callback */
hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* Legacy weak RxFifo1Callback */
hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */
hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* Legacy weak
TxBufferCompleteCallback */
hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* Legacy weak
TxBufferAbortCallback */
hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback; /* Legacy weak
HighPriorityMessageCallback */
hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback; /* Legacy weak
TimestampWraparoundCallback */
hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback; /* Legacy weak
TimeoutOccurredCallback */
hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback; /* Legacy weak ErrorCallback */
hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* Legacy weak ErrorStatusCallback */
if (hfdcan->MspInitCallback == NULL)
{
hfdcan->MspInitCallback = HAL_FDCAN_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware: CLOCK, NVIC */
hfdcan->MspInitCallback(hfdcan);
}
#else
if (hfdcan->State == HAL_FDCAN_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hfdcan->Lock = HAL_UNLOCKED;
/* Init the low level hardware: CLOCK, NVIC */
HAL_FDCAN_MspInit(hfdcan);
}
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
/* Exit from Sleep mode */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR);
/* Get tick */
tickstart = HAL_GetTick();
/* Check Sleep mode acknowledge */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA)
{
if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
}
/* Request initialisation */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until the INIT bit into CCCR register is set */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
}
/* Enable configuration change */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE);
/* Check FDCAN instance */
if (hfdcan->Instance == FDCAN1)
{
/* Configure Clock divider */
FDCAN_CONFIG->CKDIV = hfdcan->Init.ClockDivider;
}
/* Set the no automatic retransmission */
if (hfdcan->Init.AutoRetransmission == ENABLE)
{
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR);
}
else
{
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR);
}
/* Set the transmit pause feature */
if (hfdcan->Init.TransmitPause == ENABLE)
{
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP);
}
else
{
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP);
}
/* Set the Protocol Exception Handling */
if (hfdcan->Init.ProtocolException == ENABLE)
{
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD);
}
else
{
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD);
}
/* Set FDCAN Frame Format */
MODIFY_REG(hfdcan->Instance->CCCR, FDCAN_FRAME_FD_BRS, hfdcan->Init.FrameFormat);
/* Reset FDCAN Operation Mode */
CLEAR_BIT(hfdcan->Instance->CCCR, (FDCAN_CCCR_TEST | FDCAN_CCCR_MON | FDCAN_CCCR_ASM));
CLEAR_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK);
/* Set FDCAN Operating Mode:
| Normal | Restricted | Bus | Internal | External
| | Operation | Monitoring | LoopBack | LoopBack
CCCR.TEST | 0 | 0 | 0 | 1 | 1
CCCR.MON | 0 | 0 | 1 | 1 | 0
TEST.LBCK | 0 | 0 | 0 | 1 | 1
CCCR.ASM | 0 | 1 | 0 | 0 | 0
*/
if (hfdcan->Init.Mode == FDCAN_MODE_RESTRICTED_OPERATION)
{
/* Enable Restricted Operation mode */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM);
}
else if (hfdcan->Init.Mode != FDCAN_MODE_NORMAL)
{
if (hfdcan->Init.Mode != FDCAN_MODE_BUS_MONITORING)
{
/* Enable write access to TEST register */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TEST);
/* Enable LoopBack mode */
SET_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK);
if (hfdcan->Init.Mode == FDCAN_MODE_INTERNAL_LOOPBACK)
{
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON);
}
}
else
{
/* Enable bus monitoring mode */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON);
}
}
else
{
/* Nothing to do: normal mode */
}
/* Set the nominal bit timing register */
hfdcan->Instance->NBTP = ((((uint32_t)hfdcan->Init.NominalSyncJumpWidth - 1U) << FDCAN_NBTP_NSJW_Pos) | \
(((uint32_t)hfdcan->Init.NominalTimeSeg1 - 1U) << FDCAN_NBTP_NTSEG1_Pos) | \
(((uint32_t)hfdcan->Init.NominalTimeSeg2 - 1U) << FDCAN_NBTP_NTSEG2_Pos) | \
(((uint32_t)hfdcan->Init.NominalPrescaler - 1U) << FDCAN_NBTP_NBRP_Pos));
/* If FD operation with BRS is selected, set the data bit timing register */
if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS)
{
hfdcan->Instance->DBTP = ((((uint32_t)hfdcan->Init.DataSyncJumpWidth - 1U) << FDCAN_DBTP_DSJW_Pos) | \
(((uint32_t)hfdcan->Init.DataTimeSeg1 - 1U) << FDCAN_DBTP_DTSEG1_Pos) | \
(((uint32_t)hfdcan->Init.DataTimeSeg2 - 1U) << FDCAN_DBTP_DTSEG2_Pos) | \
(((uint32_t)hfdcan->Init.DataPrescaler - 1U) << FDCAN_DBTP_DBRP_Pos));
}
/* Select between Tx FIFO and Tx Queue operation modes */
SET_BIT(hfdcan->Instance->TXBC, hfdcan->Init.TxFifoQueueMode);
/* Calculate each RAM block address */
FDCAN_CalcultateRamBlockAddresses(hfdcan);
/* Initialize the Latest Tx request buffer index */
hfdcan->LatestTxFifoQRequest = 0U;
/* Initialize the error code */
hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE;
/* Initialize the FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Deinitializes the FDCAN peripheral registers to their default reset values.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DeInit(FDCAN_HandleTypeDef *hfdcan)
{
/* Check FDCAN handle */
if (hfdcan == NULL)
{
return HAL_ERROR;
}
/* Check function parameters */
assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance));
/* Stop the FDCAN module: return value is voluntary ignored */
(void)HAL_FDCAN_Stop(hfdcan);
/* Disable Interrupt lines */
CLEAR_BIT(hfdcan->Instance->ILE, (FDCAN_INTERRUPT_LINE0 | FDCAN_INTERRUPT_LINE1));
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
if (hfdcan->MspDeInitCallback == NULL)
{
hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: CLOCK, NVIC */
hfdcan->MspDeInitCallback(hfdcan);
#else
/* DeInit the low level hardware: CLOCK, NVIC */
HAL_FDCAN_MspDeInit(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
/* Reset the FDCAN ErrorCode */
hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_RESET;
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the FDCAN MSP.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_MspInit(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitializes the FDCAN MSP.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_MspDeInit(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_MspDeInit could be implemented in the user file
*/
}
/**
* @brief Enter FDCAN peripheral in sleep mode.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnterPowerDownMode(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t tickstart;
/* Request clock stop */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until FDCAN is ready for power down */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == 0U)
{
if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Exit power down mode.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ExitPowerDownMode(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t tickstart;
/* Reset clock stop request */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR);
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until FDCAN exits sleep mode */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA)
{
if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
}
/* Enter normal operation */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT);
/* Return function status */
return HAL_OK;
}
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/**
* @brief Register a FDCAN CallBack.
* To be used instead of the weak predefined callback
* @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains
* the configuration information for FDCAN module
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID
* @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID
* @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID
* @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID
* @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID
* @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID,
void (* pCallback)(FDCAN_HandleTypeDef *_hFDCAN))
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
switch (CallbackID)
{
case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID :
hfdcan->TxFifoEmptyCallback = pCallback;
break;
case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID :
hfdcan->HighPriorityMessageCallback = pCallback;
break;
case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID :
hfdcan->TimestampWraparoundCallback = pCallback;
break;
case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID :
hfdcan->TimeoutOccurredCallback = pCallback;
break;
case HAL_FDCAN_ERROR_CALLBACK_CB_ID :
hfdcan->ErrorCallback = pCallback;
break;
case HAL_FDCAN_MSPINIT_CB_ID :
hfdcan->MspInitCallback = pCallback;
break;
case HAL_FDCAN_MSPDEINIT_CB_ID :
hfdcan->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hfdcan->State == HAL_FDCAN_STATE_RESET)
{
switch (CallbackID)
{
case HAL_FDCAN_MSPINIT_CB_ID :
hfdcan->MspInitCallback = pCallback;
break;
case HAL_FDCAN_MSPDEINIT_CB_ID :
hfdcan->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Unregister a FDCAN CallBack.
* FDCAN callback is redirected to the weak predefined callback
* @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains
* the configuration information for FDCAN module
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID
* @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID
* @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID
* @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID
* @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID
* @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
switch (CallbackID)
{
case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID :
hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback;
break;
case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID :
hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback;
break;
case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID :
hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback;
break;
case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID :
hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback;
break;
case HAL_FDCAN_ERROR_CALLBACK_CB_ID :
hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback;
break;
case HAL_FDCAN_MSPINIT_CB_ID :
hfdcan->MspInitCallback = HAL_FDCAN_MspInit;
break;
case HAL_FDCAN_MSPDEINIT_CB_ID :
hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit;
break;
default :
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hfdcan->State == HAL_FDCAN_STATE_RESET)
{
switch (CallbackID)
{
case HAL_FDCAN_MSPINIT_CB_ID :
hfdcan->MspInitCallback = HAL_FDCAN_MspInit;
break;
case HAL_FDCAN_MSPDEINIT_CB_ID :
hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit;
break;
default :
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Tx Event Fifo FDCAN Callback
* To be used instead of the weak HAL_FDCAN_TxEventFifoCallback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Tx Event Fifo Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_TxEventFifoCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxEventFifoCallback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Tx Event Fifo FDCAN Callback
* Tx Event Fifo FDCAN Callback is redirected to the weak HAL_FDCAN_TxEventFifoCallback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* Legacy weak TxEventFifoCallback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Rx Fifo 0 FDCAN Callback
* To be used instead of the weak HAL_FDCAN_RxFifo0Callback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Rx Fifo 0 Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_RxFifo0CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->RxFifo0Callback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Rx Fifo 0 FDCAN Callback
* Rx Fifo 0 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo0Callback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* Legacy weak RxFifo0Callback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Rx Fifo 1 FDCAN Callback
* To be used instead of the weak HAL_FDCAN_RxFifo1Callback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Rx Fifo 1 Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_RxFifo1CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->RxFifo1Callback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Rx Fifo 1 FDCAN Callback
* Rx Fifo 1 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo1Callback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* Legacy weak RxFifo1Callback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Tx Buffer Complete FDCAN Callback
* To be used instead of the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Tx Buffer Complete Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_TxBufferCompleteCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxBufferCompleteCallback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Tx Buffer Complete FDCAN Callback
* Tx Buffer Complete FDCAN Callback is redirected to
* the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* Legacy weak TxBufferCompleteCallback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Tx Buffer Abort FDCAN Callback
* To be used instead of the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Tx Buffer Abort Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_TxBufferAbortCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxBufferAbortCallback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Tx Buffer Abort FDCAN Callback
* Tx Buffer Abort FDCAN Callback is redirected to
* the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* Legacy weak TxBufferAbortCallback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Register Error Status FDCAN Callback
* To be used instead of the weak HAL_FDCAN_ErrorStatusCallback() predefined callback
* @param hfdcan FDCAN handle
* @param pCallback pointer to the Error Status Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_RegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan,
pFDCAN_ErrorStatusCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->ErrorStatusCallback = pCallback;
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief UnRegister the Error Status FDCAN Callback
* Error Status FDCAN Callback is redirected to the weak HAL_FDCAN_ErrorStatusCallback() predefined callback
* @param hfdcan FDCAN handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_UnRegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan)
{
HAL_StatusTypeDef status = HAL_OK;
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* Legacy weak ErrorStatusCallback */
}
else
{
/* Update the error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup FDCAN_Exported_Functions_Group2 Configuration functions
* @brief FDCAN Configuration functions.
*
@verbatim
==============================================================================
##### Configuration functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) HAL_FDCAN_ConfigFilter : Configure the FDCAN reception filters
(+) HAL_FDCAN_ConfigGlobalFilter : Configure the FDCAN global filter
(+) HAL_FDCAN_ConfigExtendedIdMask : Configure the extended ID mask
(+) HAL_FDCAN_ConfigRxFifoOverwrite : Configure the Rx FIFO operation mode
(+) HAL_FDCAN_ConfigRamWatchdog : Configure the RAM watchdog
(+) HAL_FDCAN_ConfigTimestampCounter : Configure the timestamp counter
(+) HAL_FDCAN_EnableTimestampCounter : Enable the timestamp counter
(+) HAL_FDCAN_DisableTimestampCounter : Disable the timestamp counter
(+) HAL_FDCAN_GetTimestampCounter : Get the timestamp counter value
(+) HAL_FDCAN_ResetTimestampCounter : Reset the timestamp counter to zero
(+) HAL_FDCAN_ConfigTimeoutCounter : Configure the timeout counter
(+) HAL_FDCAN_EnableTimeoutCounter : Enable the timeout counter
(+) HAL_FDCAN_DisableTimeoutCounter : Disable the timeout counter
(+) HAL_FDCAN_GetTimeoutCounter : Get the timeout counter value
(+) HAL_FDCAN_ResetTimeoutCounter : Reset the timeout counter to its start value
(+) HAL_FDCAN_ConfigTxDelayCompensation : Configure the transmitter delay compensation
(+) HAL_FDCAN_EnableTxDelayCompensation : Enable the transmitter delay compensation
(+) HAL_FDCAN_DisableTxDelayCompensation : Disable the transmitter delay compensation
(+) HAL_FDCAN_EnableISOMode : Enable ISO 11898-1 protocol mode
(+) HAL_FDCAN_DisableISOMode : Disable ISO 11898-1 protocol mode
(+) HAL_FDCAN_EnableEdgeFiltering : Enable edge filtering during bus integration
(+) HAL_FDCAN_DisableEdgeFiltering : Disable edge filtering during bus integration
@endverbatim
* @{
*/
/**
* @brief Configure the FDCAN reception filter according to the specified
* parameters in the FDCAN_FilterTypeDef structure.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param sFilterConfig pointer to an FDCAN_FilterTypeDef structure that
* contains the filter configuration information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigFilter(FDCAN_HandleTypeDef *hfdcan, FDCAN_FilterTypeDef *sFilterConfig)
{
uint32_t FilterElementW1;
uint32_t FilterElementW2;
uint32_t *FilterAddress;
HAL_FDCAN_StateTypeDef state = hfdcan->State;
if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY))
{
/* Check function parameters */
assert_param(IS_FDCAN_ID_TYPE(sFilterConfig->IdType));
assert_param(IS_FDCAN_FILTER_CFG(sFilterConfig->FilterConfig));
if (sFilterConfig->IdType == FDCAN_STANDARD_ID)
{
/* Check function parameters */
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.StdFiltersNbr - 1U)));
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x7FFU));
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x7FFU));
assert_param(IS_FDCAN_STD_FILTER_TYPE(sFilterConfig->FilterType));
/* Build filter element */
FilterElementW1 = ((sFilterConfig->FilterType << 30U) |
(sFilterConfig->FilterConfig << 27U) |
(sFilterConfig->FilterID1 << 16U) |
sFilterConfig->FilterID2);
/* Calculate filter address */
FilterAddress = (uint32_t *)(hfdcan->msgRam.StandardFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLS_SIZE));
/* Write filter element to the message RAM */
*FilterAddress = FilterElementW1;
}
else /* sFilterConfig->IdType == FDCAN_EXTENDED_ID */
{
/* Check function parameters */
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.ExtFiltersNbr - 1U)));
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x1FFFFFFFU));
assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x1FFFFFFFU));
assert_param(IS_FDCAN_EXT_FILTER_TYPE(sFilterConfig->FilterType));
/* Build first word of filter element */
FilterElementW1 = ((sFilterConfig->FilterConfig << 29U) | sFilterConfig->FilterID1);
/* Build second word of filter element */
FilterElementW2 = ((sFilterConfig->FilterType << 30U) | sFilterConfig->FilterID2);
/* Calculate filter address */
FilterAddress = (uint32_t *)(hfdcan->msgRam.ExtendedFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLE_SIZE));
/* Write filter element to the message RAM */
*FilterAddress = FilterElementW1;
FilterAddress++;
*FilterAddress = FilterElementW2;
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED;
return HAL_ERROR;
}
}
/**
* @brief Configure the FDCAN global filter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param NonMatchingStd Defines how received messages with 11-bit IDs that
* do not match any element of the filter list are treated.
* This parameter can be a value of @arg FDCAN_Non_Matching_Frames.
* @param NonMatchingExt Defines how received messages with 29-bit IDs that
* do not match any element of the filter list are treated.
* This parameter can be a value of @arg FDCAN_Non_Matching_Frames.
* @param RejectRemoteStd Filter or reject all the remote 11-bit IDs frames.
* This parameter can be a value of @arg FDCAN_Reject_Remote_Frames.
* @param RejectRemoteExt Filter or reject all the remote 29-bit IDs frames.
* This parameter can be a value of @arg FDCAN_Reject_Remote_Frames.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigGlobalFilter(FDCAN_HandleTypeDef *hfdcan,
uint32_t NonMatchingStd,
uint32_t NonMatchingExt,
uint32_t RejectRemoteStd,
uint32_t RejectRemoteExt)
{
/* Check function parameters */
assert_param(IS_FDCAN_NON_MATCHING(NonMatchingStd));
assert_param(IS_FDCAN_NON_MATCHING(NonMatchingExt));
assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteStd));
assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteExt));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Configure global filter */
MODIFY_REG(hfdcan->Instance->RXGFC, (FDCAN_RXGFC_ANFS |
FDCAN_RXGFC_ANFE |
FDCAN_RXGFC_RRFS |
FDCAN_RXGFC_RRFE),
((NonMatchingStd << FDCAN_RXGFC_ANFS_Pos) |
(NonMatchingExt << FDCAN_RXGFC_ANFE_Pos) |
(RejectRemoteStd << FDCAN_RXGFC_RRFS_Pos) |
(RejectRemoteExt << FDCAN_RXGFC_RRFE_Pos)));
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Configure the extended ID mask.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param Mask Extended ID Mask.
This parameter must be a number between 0 and 0x1FFFFFFF
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigExtendedIdMask(FDCAN_HandleTypeDef *hfdcan, uint32_t Mask)
{
/* Check function parameters */
assert_param(IS_FDCAN_MAX_VALUE(Mask, 0x1FFFFFFFU));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Configure the extended ID mask */
hfdcan->Instance->XIDAM = Mask;
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Configure the Rx FIFO operation mode.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param RxFifo Rx FIFO.
* This parameter can be one of the following values:
* @arg FDCAN_RX_FIFO0: Rx FIFO 0
* @arg FDCAN_RX_FIFO1: Rx FIFO 1
* @param OperationMode operation mode.
* This parameter can be a value of @arg FDCAN_Rx_FIFO_operation_mode.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigRxFifoOverwrite(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo, uint32_t OperationMode)
{
/* Check function parameters */
assert_param(IS_FDCAN_RX_FIFO(RxFifo));
assert_param(IS_FDCAN_RX_FIFO_MODE(OperationMode));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
if (RxFifo == FDCAN_RX_FIFO0)
{
/* Select FIFO 0 Operation Mode */
MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F0OM, (OperationMode << FDCAN_RXGFC_F0OM_Pos));
}
else /* RxFifo == FDCAN_RX_FIFO1 */
{
/* Select FIFO 1 Operation Mode */
MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F1OM, (OperationMode << FDCAN_RXGFC_F1OM_Pos));
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Configure the RAM watchdog.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param CounterStartValue Start value of the Message RAM Watchdog Counter,
* This parameter must be a number between 0x00 and 0xFF,
* with the reset value of 0x00 the counter is disabled.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigRamWatchdog(FDCAN_HandleTypeDef *hfdcan, uint32_t CounterStartValue)
{
/* Check function parameters */
assert_param(IS_FDCAN_MAX_VALUE(CounterStartValue, 0xFFU));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Configure the RAM watchdog counter start value */
MODIFY_REG(hfdcan->Instance->RWD, FDCAN_RWD_WDC, CounterStartValue);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Configure the timestamp counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TimestampPrescaler Timestamp Counter Prescaler.
* This parameter can be a value of @arg FDCAN_Timestamp_Prescaler.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampPrescaler)
{
/* Check function parameters */
assert_param(IS_FDCAN_TIMESTAMP_PRESCALER(TimestampPrescaler));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Configure prescaler */
MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TCP, TimestampPrescaler);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Enable the timestamp counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TimestampOperation Timestamp counter operation.
* This parameter can be a value of @arg FDCAN_Timestamp.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnableTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampOperation)
{
/* Check function parameters */
assert_param(IS_FDCAN_TIMESTAMP(TimestampOperation));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Enable timestamp counter */
MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS, TimestampOperation);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Disable the timestamp counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DisableTimestampCounter(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Disable timestamp counter */
CLEAR_BIT(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Get the timestamp counter value.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval Timestamp counter value
*/
uint16_t HAL_FDCAN_GetTimestampCounter(FDCAN_HandleTypeDef *hfdcan)
{
return (uint16_t)(hfdcan->Instance->TSCV);
}
/**
* @brief Reset the timestamp counter to zero.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ResetTimestampCounter(FDCAN_HandleTypeDef *hfdcan)
{
if ((hfdcan->Instance->TSCC & FDCAN_TSCC_TSS) != FDCAN_TIMESTAMP_EXTERNAL)
{
/* Reset timestamp counter.
Actually any write operation to TSCV clears the counter */
CLEAR_REG(hfdcan->Instance->TSCV);
}
else
{
/* Update error code.
Unable to reset external counter */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED;
return HAL_ERROR;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Configure the timeout counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TimeoutOperation Timeout counter operation.
* This parameter can be a value of @arg FDCAN_Timeout_Operation.
* @param TimeoutPeriod Start value of the timeout down-counter.
* This parameter must be a number between 0x0000 and 0xFFFF
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigTimeoutCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimeoutOperation,
uint32_t TimeoutPeriod)
{
/* Check function parameters */
assert_param(IS_FDCAN_TIMEOUT(TimeoutOperation));
assert_param(IS_FDCAN_MAX_VALUE(TimeoutPeriod, 0xFFFFU));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Select timeout operation and configure period */
MODIFY_REG(hfdcan->Instance->TOCC,
(FDCAN_TOCC_TOS | FDCAN_TOCC_TOP), (TimeoutOperation | (TimeoutPeriod << FDCAN_TOCC_TOP_Pos)));
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Enable the timeout counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Enable timeout counter */
SET_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Disable the timeout counter.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DisableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Disable timeout counter */
CLEAR_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Get the timeout counter value.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval Timeout counter value
*/
uint16_t HAL_FDCAN_GetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan)
{
return (uint16_t)(hfdcan->Instance->TOCV);
}
/**
* @brief Reset the timeout counter to its start value.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ResetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan)
{
if ((hfdcan->Instance->TOCC & FDCAN_TOCC_TOS) == FDCAN_TIMEOUT_CONTINUOUS)
{
/* Reset timeout counter to start value */
CLEAR_REG(hfdcan->Instance->TOCV);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code.
Unable to reset counter: controlled only by FIFO empty state */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED;
return HAL_ERROR;
}
}
/**
* @brief Configure the transmitter delay compensation.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TdcOffset Transmitter Delay Compensation Offset.
* This parameter must be a number between 0x00 and 0x7F.
* @param TdcFilter Transmitter Delay Compensation Filter Window Length.
* This parameter must be a number between 0x00 and 0x7F.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan, uint32_t TdcOffset,
uint32_t TdcFilter)
{
/* Check function parameters */
assert_param(IS_FDCAN_MAX_VALUE(TdcOffset, 0x7FU));
assert_param(IS_FDCAN_MAX_VALUE(TdcFilter, 0x7FU));
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Configure TDC offset and filter window */
hfdcan->Instance->TDCR = ((TdcFilter << FDCAN_TDCR_TDCF_Pos) | (TdcOffset << FDCAN_TDCR_TDCO_Pos));
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Enable the transmitter delay compensation.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Enable transmitter delay compensation */
SET_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Disable the transmitter delay compensation.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DisableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Disable transmitter delay compensation */
CLEAR_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Enable ISO 11898-1 protocol mode.
* CAN FD frame format is according to ISO 11898-1 standard.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnableISOMode(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Disable Non ISO protocol mode */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Disable ISO 11898-1 protocol mode.
* CAN FD frame format is according to Bosch CAN FD specification V1.0.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DisableISOMode(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Enable Non ISO protocol mode */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Enable edge filtering during bus integration.
* Two consecutive dominant tq are required to detect an edge for hard synchronization.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_EnableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Enable edge filtering */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Disable edge filtering during bus integration.
* One dominant tq is required to detect an edge for hard synchronization.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DisableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Disable edge filtering */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup FDCAN_Exported_Functions_Group3 Control functions
* @brief Control functions
*
@verbatim
==============================================================================
##### Control functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) HAL_FDCAN_Start : Start the FDCAN module
(+) HAL_FDCAN_Stop : Stop the FDCAN module and enable access to configuration registers
(+) HAL_FDCAN_AddMessageToTxFifoQ : Add a message to the Tx FIFO/Queue and activate the corresponding
transmission request
(+) HAL_FDCAN_GetLatestTxFifoQRequestBuffer : Get Tx buffer index of latest Tx FIFO/Queue request
(+) HAL_FDCAN_AbortTxRequest : Abort transmission request
(+) HAL_FDCAN_GetRxMessage : Get an FDCAN frame from the Rx FIFO zone into the message RAM
(+) HAL_FDCAN_GetTxEvent : Get an FDCAN Tx event from the Tx Event FIFO zone
into the message RAM
(+) HAL_FDCAN_GetHighPriorityMessageStatus : Get high priority message status
(+) HAL_FDCAN_GetProtocolStatus : Get protocol status
(+) HAL_FDCAN_GetErrorCounters : Get error counter values
(+) HAL_FDCAN_IsTxBufferMessagePending : Check if a transmission request is pending
on the selected Tx buffer
(+) HAL_FDCAN_GetRxFifoFillLevel : Return Rx FIFO fill level
(+) HAL_FDCAN_GetTxFifoFreeLevel : Return Tx FIFO free level
(+) HAL_FDCAN_IsRestrictedOperationMode : Check if the FDCAN peripheral entered Restricted Operation Mode
(+) HAL_FDCAN_ExitRestrictedOperationMode : Exit Restricted Operation Mode
@endverbatim
* @{
*/
/**
* @brief Start the FDCAN module.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_Start(FDCAN_HandleTypeDef *hfdcan)
{
if (hfdcan->State == HAL_FDCAN_STATE_READY)
{
/* Change FDCAN peripheral state */
hfdcan->State = HAL_FDCAN_STATE_BUSY;
/* Request leave initialisation */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT);
/* Reset the FDCAN ErrorCode */
hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE;
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY;
return HAL_ERROR;
}
}
/**
* @brief Stop the FDCAN module and enable access to configuration registers.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_Stop(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t Counter = 0U;
if (hfdcan->State == HAL_FDCAN_STATE_BUSY)
{
/* Request initialisation */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT);
/* Wait until the INIT bit into CCCR register is set */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U)
{
/* Check for the Timeout */
if (Counter > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
/* Increment counter */
Counter++;
}
/* Reset counter */
Counter = 0U;
/* Exit from Sleep mode */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR);
/* Wait until FDCAN exits sleep mode */
while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA)
{
/* Check for the Timeout */
if (Counter > FDCAN_TIMEOUT_VALUE)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT;
/* Change FDCAN state */
hfdcan->State = HAL_FDCAN_STATE_ERROR;
return HAL_ERROR;
}
/* Increment counter */
Counter++;
}
/* Enable configuration change */
SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE);
/* Reset Latest Tx FIFO/Queue Request Buffer Index */
hfdcan->LatestTxFifoQRequest = 0U;
/* Change FDCAN peripheral state */
hfdcan->State = HAL_FDCAN_STATE_READY;
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED;
return HAL_ERROR;
}
}
/**
* @brief Add a message to the Tx FIFO/Queue and activate the corresponding transmission request
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure.
* @param pTxData pointer to a buffer containing the payload of the Tx frame.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_AddMessageToTxFifoQ(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxHeaderTypeDef *pTxHeader,
uint8_t *pTxData)
{
uint32_t PutIndex;
/* Check function parameters */
assert_param(IS_FDCAN_ID_TYPE(pTxHeader->IdType));
if (pTxHeader->IdType == FDCAN_STANDARD_ID)
{
assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x7FFU));
}
else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */
{
assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x1FFFFFFFU));
}
assert_param(IS_FDCAN_FRAME_TYPE(pTxHeader->TxFrameType));
assert_param(IS_FDCAN_DLC(pTxHeader->DataLength));
assert_param(IS_FDCAN_ESI(pTxHeader->ErrorStateIndicator));
assert_param(IS_FDCAN_BRS(pTxHeader->BitRateSwitch));
assert_param(IS_FDCAN_FDF(pTxHeader->FDFormat));
assert_param(IS_FDCAN_EFC(pTxHeader->TxEventFifoControl));
assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->MessageMarker, 0xFFU));
if (hfdcan->State == HAL_FDCAN_STATE_BUSY)
{
/* Check that the Tx FIFO/Queue is not full */
if ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQF) != 0U)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_FULL;
return HAL_ERROR;
}
else
{
/* Retrieve the Tx FIFO PutIndex */
PutIndex = ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQPI) >> FDCAN_TXFQS_TFQPI_Pos);
/* Add the message to the Tx FIFO/Queue */
FDCAN_CopyMessageToRAM(hfdcan, pTxHeader, pTxData, PutIndex);
/* Activate the corresponding transmission request */
hfdcan->Instance->TXBAR = ((uint32_t)1 << PutIndex);
/* Store the Latest Tx FIFO/Queue Request Buffer Index */
hfdcan->LatestTxFifoQRequest = ((uint32_t)1 << PutIndex);
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED;
return HAL_ERROR;
}
}
/**
* @brief Get Tx buffer index of latest Tx FIFO/Queue request
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval Tx buffer index of last Tx FIFO/Queue request
* - Any value of @arg FDCAN_Tx_location if Tx request has been submitted.
* - 0 if no Tx FIFO/Queue request have been submitted.
*/
uint32_t HAL_FDCAN_GetLatestTxFifoQRequestBuffer(FDCAN_HandleTypeDef *hfdcan)
{
/* Return Last Tx FIFO/Queue Request Buffer */
return hfdcan->LatestTxFifoQRequest;
}
/**
* @brief Abort transmission request
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param BufferIndex buffer index.
* This parameter can be any combination of @arg FDCAN_Tx_location.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_AbortTxRequest(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndex)
{
/* Check function parameters */
assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndex));
if (hfdcan->State == HAL_FDCAN_STATE_BUSY)
{
/* Add cancellation request */
hfdcan->Instance->TXBCR = BufferIndex;
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED;
return HAL_ERROR;
}
}
/**
* @brief Get an FDCAN frame from the Rx FIFO zone into the message RAM.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param RxLocation Location of the received message to be read.
* This parameter can be a value of @arg FDCAN_Rx_location.
* @param pRxHeader pointer to a FDCAN_RxHeaderTypeDef structure.
* @param pRxData pointer to a buffer where the payload of the Rx frame will be stored.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_GetRxMessage(FDCAN_HandleTypeDef *hfdcan, uint32_t RxLocation,
FDCAN_RxHeaderTypeDef *pRxHeader, uint8_t *pRxData)
{
uint32_t *RxAddress;
uint8_t *pData;
uint32_t ByteCounter;
uint32_t GetIndex;
HAL_FDCAN_StateTypeDef state = hfdcan->State;
/* Check function parameters */
assert_param(IS_FDCAN_RX_FIFO(RxLocation));
if (state == HAL_FDCAN_STATE_BUSY)
{
if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */
{
/* Check that the Rx FIFO 0 is not empty */
if ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL) == 0U)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY;
return HAL_ERROR;
}
else
{
/* Calculate Rx FIFO 0 element address */
GetIndex = ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0GI) >> FDCAN_RXF0S_F0GI_Pos);
RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO0SA + (GetIndex * SRAMCAN_RF0_SIZE));
}
}
else /* Rx element is assigned to the Rx FIFO 1 */
{
/* Check that the Rx FIFO 1 is not empty */
if ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL) == 0U)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY;
return HAL_ERROR;
}
else
{
/* Calculate Rx FIFO 1 element address */
GetIndex = ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1GI) >> FDCAN_RXF1S_F1GI_Pos);
RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO1SA + (GetIndex * SRAMCAN_RF1_SIZE));
}
}
/* Retrieve IdType */
pRxHeader->IdType = *RxAddress & FDCAN_ELEMENT_MASK_XTD;
/* Retrieve Identifier */
if (pRxHeader->IdType == FDCAN_STANDARD_ID) /* Standard ID element */
{
pRxHeader->Identifier = ((*RxAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U);
}
else /* Extended ID element */
{
pRxHeader->Identifier = (*RxAddress & FDCAN_ELEMENT_MASK_EXTID);
}
/* Retrieve RxFrameType */
pRxHeader->RxFrameType = (*RxAddress & FDCAN_ELEMENT_MASK_RTR);
/* Retrieve ErrorStateIndicator */
pRxHeader->ErrorStateIndicator = (*RxAddress & FDCAN_ELEMENT_MASK_ESI);
/* Increment RxAddress pointer to second word of Rx FIFO element */
RxAddress++;
/* Retrieve RxTimestamp */
pRxHeader->RxTimestamp = (*RxAddress & FDCAN_ELEMENT_MASK_TS);
/* Retrieve DataLength */
pRxHeader->DataLength = (*RxAddress & FDCAN_ELEMENT_MASK_DLC);
/* Retrieve BitRateSwitch */
pRxHeader->BitRateSwitch = (*RxAddress & FDCAN_ELEMENT_MASK_BRS);
/* Retrieve FDFormat */
pRxHeader->FDFormat = (*RxAddress & FDCAN_ELEMENT_MASK_FDF);
/* Retrieve FilterIndex */
pRxHeader->FilterIndex = ((*RxAddress & FDCAN_ELEMENT_MASK_FIDX) >> 24U);
/* Retrieve NonMatchingFrame */
pRxHeader->IsFilterMatchingFrame = ((*RxAddress & FDCAN_ELEMENT_MASK_ANMF) >> 31U);
/* Increment RxAddress pointer to payload of Rx FIFO element */
RxAddress++;
/* Retrieve Rx payload */
pData = (uint8_t *)RxAddress;
for (ByteCounter = 0; ByteCounter < DLCtoBytes[pRxHeader->DataLength >> 16U]; ByteCounter++)
{
pRxData[ByteCounter] = pData[ByteCounter];
}
if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */
{
/* Acknowledge the Rx FIFO 0 that the oldest element is read so that it increments the GetIndex */
hfdcan->Instance->RXF0A = GetIndex;
}
else /* Rx element is assigned to the Rx FIFO 1 */
{
/* Acknowledge the Rx FIFO 1 that the oldest element is read so that it increments the GetIndex */
hfdcan->Instance->RXF1A = GetIndex;
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED;
return HAL_ERROR;
}
}
/**
* @brief Get an FDCAN Tx event from the Tx Event FIFO zone into the message RAM.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param pTxEvent pointer to a FDCAN_TxEventFifoTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_GetTxEvent(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxEventFifoTypeDef *pTxEvent)
{
uint32_t *TxEventAddress;
uint32_t GetIndex;
HAL_FDCAN_StateTypeDef state = hfdcan->State;
if (state == HAL_FDCAN_STATE_BUSY)
{
/* Check that the Tx event FIFO is not empty */
if ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFFL) == 0U)
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY;
return HAL_ERROR;
}
/* Calculate Tx event FIFO element address */
GetIndex = ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFGI) >> FDCAN_TXEFS_EFGI_Pos);
TxEventAddress = (uint32_t *)(hfdcan->msgRam.TxEventFIFOSA + (GetIndex * SRAMCAN_TEF_SIZE));
/* Retrieve IdType */
pTxEvent->IdType = *TxEventAddress & FDCAN_ELEMENT_MASK_XTD;
/* Retrieve Identifier */
if (pTxEvent->IdType == FDCAN_STANDARD_ID) /* Standard ID element */
{
pTxEvent->Identifier = ((*TxEventAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U);
}
else /* Extended ID element */
{
pTxEvent->Identifier = (*TxEventAddress & FDCAN_ELEMENT_MASK_EXTID);
}
/* Retrieve TxFrameType */
pTxEvent->TxFrameType = (*TxEventAddress & FDCAN_ELEMENT_MASK_RTR);
/* Retrieve ErrorStateIndicator */
pTxEvent->ErrorStateIndicator = (*TxEventAddress & FDCAN_ELEMENT_MASK_ESI);
/* Increment TxEventAddress pointer to second word of Tx Event FIFO element */
TxEventAddress++;
/* Retrieve TxTimestamp */
pTxEvent->TxTimestamp = (*TxEventAddress & FDCAN_ELEMENT_MASK_TS);
/* Retrieve DataLength */
pTxEvent->DataLength = (*TxEventAddress & FDCAN_ELEMENT_MASK_DLC);
/* Retrieve BitRateSwitch */
pTxEvent->BitRateSwitch = (*TxEventAddress & FDCAN_ELEMENT_MASK_BRS);
/* Retrieve FDFormat */
pTxEvent->FDFormat = (*TxEventAddress & FDCAN_ELEMENT_MASK_FDF);
/* Retrieve EventType */
pTxEvent->EventType = (*TxEventAddress & FDCAN_ELEMENT_MASK_ET);
/* Retrieve MessageMarker */
pTxEvent->MessageMarker = ((*TxEventAddress & FDCAN_ELEMENT_MASK_MM) >> 24U);
/* Acknowledge the Tx Event FIFO that the oldest element is read so that it increments the GetIndex */
hfdcan->Instance->TXEFA = GetIndex;
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED;
return HAL_ERROR;
}
}
/**
* @brief Get high priority message status.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param HpMsgStatus pointer to an FDCAN_HpMsgStatusTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_GetHighPriorityMessageStatus(FDCAN_HandleTypeDef *hfdcan,
FDCAN_HpMsgStatusTypeDef *HpMsgStatus)
{
HpMsgStatus->FilterList = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FLST) >> FDCAN_HPMS_FLST_Pos);
HpMsgStatus->FilterIndex = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FIDX) >> FDCAN_HPMS_FIDX_Pos);
HpMsgStatus->MessageStorage = (hfdcan->Instance->HPMS & FDCAN_HPMS_MSI);
HpMsgStatus->MessageIndex = (hfdcan->Instance->HPMS & FDCAN_HPMS_BIDX);
/* Return function status */
return HAL_OK;
}
/**
* @brief Get protocol status.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param ProtocolStatus pointer to an FDCAN_ProtocolStatusTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_GetProtocolStatus(FDCAN_HandleTypeDef *hfdcan, FDCAN_ProtocolStatusTypeDef *ProtocolStatus)
{
uint32_t StatusReg;
/* Read the protocol status register */
StatusReg = READ_REG(hfdcan->Instance->PSR);
/* Fill the protocol status structure */
ProtocolStatus->LastErrorCode = (StatusReg & FDCAN_PSR_LEC);
ProtocolStatus->DataLastErrorCode = ((StatusReg & FDCAN_PSR_DLEC) >> FDCAN_PSR_DLEC_Pos);
ProtocolStatus->Activity = (StatusReg & FDCAN_PSR_ACT);
ProtocolStatus->ErrorPassive = ((StatusReg & FDCAN_PSR_EP) >> FDCAN_PSR_EP_Pos);
ProtocolStatus->Warning = ((StatusReg & FDCAN_PSR_EW) >> FDCAN_PSR_EW_Pos);
ProtocolStatus->BusOff = ((StatusReg & FDCAN_PSR_BO) >> FDCAN_PSR_BO_Pos);
ProtocolStatus->RxESIflag = ((StatusReg & FDCAN_PSR_RESI) >> FDCAN_PSR_RESI_Pos);
ProtocolStatus->RxBRSflag = ((StatusReg & FDCAN_PSR_RBRS) >> FDCAN_PSR_RBRS_Pos);
ProtocolStatus->RxFDFflag = ((StatusReg & FDCAN_PSR_REDL) >> FDCAN_PSR_REDL_Pos);
ProtocolStatus->ProtocolException = ((StatusReg & FDCAN_PSR_PXE) >> FDCAN_PSR_PXE_Pos);
ProtocolStatus->TDCvalue = ((StatusReg & FDCAN_PSR_TDCV) >> FDCAN_PSR_TDCV_Pos);
/* Return function status */
return HAL_OK;
}
/**
* @brief Get error counter values.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param ErrorCounters pointer to an FDCAN_ErrorCountersTypeDef structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_GetErrorCounters(FDCAN_HandleTypeDef *hfdcan, FDCAN_ErrorCountersTypeDef *ErrorCounters)
{
uint32_t CountersReg;
/* Read the error counters register */
CountersReg = READ_REG(hfdcan->Instance->ECR);
/* Fill the error counters structure */
ErrorCounters->TxErrorCnt = ((CountersReg & FDCAN_ECR_TEC) >> FDCAN_ECR_TEC_Pos);
ErrorCounters->RxErrorCnt = ((CountersReg & FDCAN_ECR_REC) >> FDCAN_ECR_REC_Pos);
ErrorCounters->RxErrorPassive = ((CountersReg & FDCAN_ECR_RP) >> FDCAN_ECR_RP_Pos);
ErrorCounters->ErrorLogging = ((CountersReg & FDCAN_ECR_CEL) >> FDCAN_ECR_CEL_Pos);
/* Return function status */
return HAL_OK;
}
/**
* @brief Check if a transmission request is pending on the selected Tx buffer.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TxBufferIndex Tx buffer index.
* This parameter can be any combination of @arg FDCAN_Tx_location.
* @retval Status
* - 0 : No pending transmission request on TxBufferIndex list
* - 1 : Pending transmission request on TxBufferIndex.
*/
uint32_t HAL_FDCAN_IsTxBufferMessagePending(FDCAN_HandleTypeDef *hfdcan, uint32_t TxBufferIndex)
{
/* Check function parameters */
assert_param(IS_FDCAN_TX_LOCATION_LIST(TxBufferIndex));
/* Check pending transmission request on the selected buffer */
if ((hfdcan->Instance->TXBRP & TxBufferIndex) == 0U)
{
return 0;
}
return 1;
}
/**
* @brief Return Rx FIFO fill level.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param RxFifo Rx FIFO.
* This parameter can be one of the following values:
* @arg FDCAN_RX_FIFO0: Rx FIFO 0
* @arg FDCAN_RX_FIFO1: Rx FIFO 1
* @retval Rx FIFO fill level.
*/
uint32_t HAL_FDCAN_GetRxFifoFillLevel(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo)
{
uint32_t FillLevel;
/* Check function parameters */
assert_param(IS_FDCAN_RX_FIFO(RxFifo));
if (RxFifo == FDCAN_RX_FIFO0)
{
FillLevel = hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL;
}
else /* RxFifo == FDCAN_RX_FIFO1 */
{
FillLevel = hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL;
}
/* Return Rx FIFO fill level */
return FillLevel;
}
/**
* @brief Return Tx FIFO free level: number of consecutive free Tx FIFO
* elements starting from Tx FIFO GetIndex.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval Tx FIFO free level.
*/
uint32_t HAL_FDCAN_GetTxFifoFreeLevel(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t FreeLevel;
FreeLevel = hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFFL;
/* Return Tx FIFO free level */
return FreeLevel;
}
/**
* @brief Check if the FDCAN peripheral entered Restricted Operation Mode.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval Status
* - 0 : Normal FDCAN operation.
* - 1 : Restricted Operation Mode active.
*/
uint32_t HAL_FDCAN_IsRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t OperationMode;
/* Get Operation Mode */
OperationMode = ((hfdcan->Instance->CCCR & FDCAN_CCCR_ASM) >> FDCAN_CCCR_ASM_Pos);
return OperationMode;
}
/**
* @brief Exit Restricted Operation Mode.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ExitRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan)
{
HAL_FDCAN_StateTypeDef state = hfdcan->State;
if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY))
{
/* Exit Restricted Operation mode */
CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED;
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup FDCAN_Exported_Functions_Group4 Interrupts management
* @brief Interrupts management
*
@verbatim
==============================================================================
##### Interrupts management #####
==============================================================================
[..] This section provides functions allowing to:
(+) HAL_FDCAN_ConfigInterruptLines : Assign interrupts to either Interrupt line 0 or 1
(+) HAL_FDCAN_ActivateNotification : Enable interrupts
(+) HAL_FDCAN_DeactivateNotification : Disable interrupts
(+) HAL_FDCAN_IRQHandler : Handles FDCAN interrupt request
@endverbatim
* @{
*/
/**
* @brief Assign interrupts to either Interrupt line 0 or 1.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param ITList indicates which interrupts group will be assigned to the selected interrupt line.
* This parameter can be any combination of @arg FDCAN_Interrupts_Group.
* @param InterruptLine Interrupt line.
* This parameter can be a value of @arg FDCAN_Interrupt_Line.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ConfigInterruptLines(FDCAN_HandleTypeDef *hfdcan, uint32_t ITList, uint32_t InterruptLine)
{
HAL_FDCAN_StateTypeDef state = hfdcan->State;
/* Check function parameters */
assert_param(IS_FDCAN_IT_GROUP(ITList));
assert_param(IS_FDCAN_IT_LINE(InterruptLine));
if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY))
{
/* Assign list of interrupts to the selected line */
if (InterruptLine == FDCAN_INTERRUPT_LINE0)
{
CLEAR_BIT(hfdcan->Instance->ILS, ITList);
}
else /* InterruptLine == FDCAN_INTERRUPT_LINE1 */
{
SET_BIT(hfdcan->Instance->ILS, ITList);
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED;
return HAL_ERROR;
}
}
/**
* @brief Enable interrupts.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param ActiveITs indicates which interrupts will be enabled.
* This parameter can be any combination of @arg FDCAN_Interrupts.
* @param BufferIndexes Tx Buffer Indexes.
* This parameter can be any combination of @arg FDCAN_Tx_location.
* This parameter is ignored if ActiveITs does not include one of the following:
* - FDCAN_IT_TX_COMPLETE
* - FDCAN_IT_TX_ABORT_COMPLETE
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_ActivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t ActiveITs,
uint32_t BufferIndexes)
{
HAL_FDCAN_StateTypeDef state = hfdcan->State;
uint32_t ITs_lines_selection;
/* Check function parameters */
assert_param(IS_FDCAN_IT(ActiveITs));
if ((ActiveITs & (FDCAN_IT_TX_COMPLETE | FDCAN_IT_TX_ABORT_COMPLETE)) != 0U)
{
assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndexes));
}
if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY))
{
/* Get interrupts line selection */
ITs_lines_selection = hfdcan->Instance->ILS;
/* Enable Interrupt lines */
if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_MISC) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U)))
{
/* Enable Interrupt line 0 */
SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0);
}
if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_MISC) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \
(((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U)))
{
/* Enable Interrupt line 1 */
SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1);
}
if ((ActiveITs & FDCAN_IT_TX_COMPLETE) != 0U)
{
/* Enable Tx Buffer Transmission Interrupt to set TC flag in IR register,
but interrupt will only occur if TC is enabled in IE register */
SET_BIT(hfdcan->Instance->TXBTIE, BufferIndexes);
}
if ((ActiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U)
{
/* Enable Tx Buffer Cancellation Finished Interrupt to set TCF flag in IR register,
but interrupt will only occur if TCF is enabled in IE register */
SET_BIT(hfdcan->Instance->TXBCIE, BufferIndexes);
}
/* Enable the selected interrupts */
__HAL_FDCAN_ENABLE_IT(hfdcan, ActiveITs);
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED;
return HAL_ERROR;
}
}
/**
* @brief Disable interrupts.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param InactiveITs indicates which interrupts will be disabled.
* This parameter can be any combination of @arg FDCAN_Interrupts.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FDCAN_DeactivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t InactiveITs)
{
HAL_FDCAN_StateTypeDef state = hfdcan->State;
uint32_t ITs_enabled;
uint32_t ITs_lines_selection;
/* Check function parameters */
assert_param(IS_FDCAN_IT(InactiveITs));
if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY))
{
/* Disable the selected interrupts */
__HAL_FDCAN_DISABLE_IT(hfdcan, InactiveITs);
if ((InactiveITs & FDCAN_IT_TX_COMPLETE) != 0U)
{
/* Disable Tx Buffer Transmission Interrupts */
CLEAR_REG(hfdcan->Instance->TXBTIE);
}
if ((InactiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U)
{
/* Disable Tx Buffer Cancellation Finished Interrupt */
CLEAR_REG(hfdcan->Instance->TXBCIE);
}
/* Get interrupts enabled and interrupts line selection */
ITs_enabled = hfdcan->Instance->IE;
ITs_lines_selection = hfdcan->Instance->ILS;
/* Check if some interrupts are still enabled on interrupt line 0 */
if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U)))
{
/* Do nothing */
}
else /* no more interrupts enabled on interrupt line 0 */
{
/* Disable interrupt line 0 */
CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0);
}
/* Check if some interrupts are still enabled on interrupt line 1 */
if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \
(((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U)
&& (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U)))
{
/* Do nothing */
}
else /* no more interrupts enabled on interrupt line 1 */
{
/* Disable interrupt line 1 */
CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1);
}
/* Return function status */
return HAL_OK;
}
else
{
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED;
return HAL_ERROR;
}
}
/**
* @brief Handles FDCAN interrupt request.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL status
*/
void HAL_FDCAN_IRQHandler(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t TxEventFifoITs;
uint32_t RxFifo0ITs;
uint32_t RxFifo1ITs;
uint32_t Errors;
uint32_t ErrorStatusITs;
uint32_t TransmittedBuffers;
uint32_t AbortedBuffers;
TxEventFifoITs = hfdcan->Instance->IR & FDCAN_TX_EVENT_FIFO_MASK;
TxEventFifoITs &= hfdcan->Instance->IE;
RxFifo0ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO0_MASK;
RxFifo0ITs &= hfdcan->Instance->IE;
RxFifo1ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO1_MASK;
RxFifo1ITs &= hfdcan->Instance->IE;
Errors = hfdcan->Instance->IR & FDCAN_ERROR_MASK;
Errors &= hfdcan->Instance->IE;
ErrorStatusITs = hfdcan->Instance->IR & FDCAN_ERROR_STATUS_MASK;
ErrorStatusITs &= hfdcan->Instance->IE;
/* High Priority Message interrupt management *******************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_RX_HIGH_PRIORITY_MSG) != 0U)
{
/* Clear the High Priority Message flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->HighPriorityMessageCallback(hfdcan);
#else
/* High Priority Message Callback */
HAL_FDCAN_HighPriorityMessageCallback(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Transmission Abort interrupt management **********************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_TX_ABORT_COMPLETE) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_TX_ABORT_COMPLETE) != 0U)
{
/* List of aborted monitored buffers */
AbortedBuffers = hfdcan->Instance->TXBCF;
AbortedBuffers &= hfdcan->Instance->TXBCIE;
/* Clear the Transmission Cancellation flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_ABORT_COMPLETE);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TxBufferAbortCallback(hfdcan, AbortedBuffers);
#else
/* Transmission Cancellation Callback */
HAL_FDCAN_TxBufferAbortCallback(hfdcan, AbortedBuffers);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Tx event FIFO interrupts management **************************************/
if (TxEventFifoITs != 0U)
{
/* Clear the Tx Event FIFO flags */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, TxEventFifoITs);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TxEventFifoCallback(hfdcan, TxEventFifoITs);
#else
/* Tx Event FIFO Callback */
HAL_FDCAN_TxEventFifoCallback(hfdcan, TxEventFifoITs);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
/* Rx FIFO 0 interrupts management ******************************************/
if (RxFifo0ITs != 0U)
{
/* Clear the Rx FIFO 0 flags */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo0ITs);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->RxFifo0Callback(hfdcan, RxFifo0ITs);
#else
/* Rx FIFO 0 Callback */
HAL_FDCAN_RxFifo0Callback(hfdcan, RxFifo0ITs);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
/* Rx FIFO 1 interrupts management ******************************************/
if (RxFifo1ITs != 0U)
{
/* Clear the Rx FIFO 1 flags */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo1ITs);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->RxFifo1Callback(hfdcan, RxFifo1ITs);
#else
/* Rx FIFO 1 Callback */
HAL_FDCAN_RxFifo1Callback(hfdcan, RxFifo1ITs);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
/* Tx FIFO empty interrupt management ***************************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_TX_FIFO_EMPTY) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_TX_FIFO_EMPTY) != 0U)
{
/* Clear the Tx FIFO empty flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_FIFO_EMPTY);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TxFifoEmptyCallback(hfdcan);
#else
/* Tx FIFO empty Callback */
HAL_FDCAN_TxFifoEmptyCallback(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Transmission Complete interrupt management *******************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_TX_COMPLETE) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_TX_COMPLETE) != 0U)
{
/* List of transmitted monitored buffers */
TransmittedBuffers = hfdcan->Instance->TXBTO;
TransmittedBuffers &= hfdcan->Instance->TXBTIE;
/* Clear the Transmission Complete flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_COMPLETE);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TxBufferCompleteCallback(hfdcan, TransmittedBuffers);
#else
/* Transmission Complete Callback */
HAL_FDCAN_TxBufferCompleteCallback(hfdcan, TransmittedBuffers);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Timestamp Wraparound interrupt management ********************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_TIMESTAMP_WRAPAROUND) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_TIMESTAMP_WRAPAROUND) != 0U)
{
/* Clear the Timestamp Wraparound flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMESTAMP_WRAPAROUND);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TimestampWraparoundCallback(hfdcan);
#else
/* Timestamp Wraparound Callback */
HAL_FDCAN_TimestampWraparoundCallback(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Timeout Occurred interrupt management ************************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_TIMEOUT_OCCURRED) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_TIMEOUT_OCCURRED) != 0U)
{
/* Clear the Timeout Occurred flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMEOUT_OCCURRED);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->TimeoutOccurredCallback(hfdcan);
#else
/* Timeout Occurred Callback */
HAL_FDCAN_TimeoutOccurredCallback(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/* Message RAM access failure interrupt management **************************/
if (__HAL_FDCAN_GET_FLAG(hfdcan, FDCAN_FLAG_RAM_ACCESS_FAILURE) != 0U)
{
if (__HAL_FDCAN_GET_IT_SOURCE(hfdcan, FDCAN_IT_RAM_ACCESS_FAILURE) != 0U)
{
/* Clear the Message RAM access failure flag */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RAM_ACCESS_FAILURE);
/* Update error code */
hfdcan->ErrorCode |= HAL_FDCAN_ERROR_RAM_ACCESS;
}
}
/* Error Status interrupts management ***************************************/
if (ErrorStatusITs != 0U)
{
/* Clear the Error flags */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, ErrorStatusITs);
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->ErrorStatusCallback(hfdcan, ErrorStatusITs);
#else
/* Error Status Callback */
HAL_FDCAN_ErrorStatusCallback(hfdcan, ErrorStatusITs);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
/* Error interrupts management **********************************************/
if (Errors != 0U)
{
/* Clear the Error flags */
__HAL_FDCAN_CLEAR_FLAG(hfdcan, Errors);
/* Update error code */
hfdcan->ErrorCode |= Errors;
}
if (hfdcan->ErrorCode != HAL_FDCAN_ERROR_NONE)
{
#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1
/* Call registered callback*/
hfdcan->ErrorCallback(hfdcan);
#else
/* Error Callback */
HAL_FDCAN_ErrorCallback(hfdcan);
#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */
}
}
/**
* @}
*/
/** @defgroup FDCAN_Exported_Functions_Group5 Callback functions
* @brief FDCAN Callback functions
*
@verbatim
==============================================================================
##### Callback functions #####
==============================================================================
[..]
This subsection provides the following callback functions:
(+) HAL_FDCAN_TxEventFifoCallback
(+) HAL_FDCAN_RxFifo0Callback
(+) HAL_FDCAN_RxFifo1Callback
(+) HAL_FDCAN_TxFifoEmptyCallback
(+) HAL_FDCAN_TxBufferCompleteCallback
(+) HAL_FDCAN_TxBufferAbortCallback
(+) HAL_FDCAN_HighPriorityMessageCallback
(+) HAL_FDCAN_TimestampWraparoundCallback
(+) HAL_FDCAN_TimeoutOccurredCallback
(+) HAL_FDCAN_ErrorCallback
(+) HAL_FDCAN_ErrorStatusCallback
@endverbatim
* @{
*/
/**
* @brief Tx Event callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param TxEventFifoITs indicates which Tx Event FIFO interrupts are signalled.
* This parameter can be any combination of @arg FDCAN_Tx_Event_Fifo_Interrupts.
* @retval None
*/
__weak void HAL_FDCAN_TxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(TxEventFifoITs);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TxEventFifoCallback could be implemented in the user file
*/
}
/**
* @brief Rx FIFO 0 callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param RxFifo0ITs indicates which Rx FIFO 0 interrupts are signalled.
* This parameter can be any combination of @arg FDCAN_Rx_Fifo0_Interrupts.
* @retval None
*/
__weak void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(RxFifo0ITs);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_RxFifo0Callback could be implemented in the user file
*/
}
/**
* @brief Rx FIFO 1 callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param RxFifo1ITs indicates which Rx FIFO 1 interrupts are signalled.
* This parameter can be any combination of @arg FDCAN_Rx_Fifo1_Interrupts.
* @retval None
*/
__weak void HAL_FDCAN_RxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(RxFifo1ITs);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_RxFifo1Callback could be implemented in the user file
*/
}
/**
* @brief Tx FIFO Empty callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_TxFifoEmptyCallback(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TxFifoEmptyCallback could be implemented in the user file
*/
}
/**
* @brief Transmission Complete callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param BufferIndexes Indexes of the transmitted buffers.
* This parameter can be any combination of @arg FDCAN_Tx_location.
* @retval None
*/
__weak void HAL_FDCAN_TxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(BufferIndexes);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TxBufferCompleteCallback could be implemented in the user file
*/
}
/**
* @brief Transmission Cancellation callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param BufferIndexes Indexes of the aborted buffers.
* This parameter can be any combination of @arg FDCAN_Tx_location.
* @retval None
*/
__weak void HAL_FDCAN_TxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(BufferIndexes);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TxBufferAbortCallback could be implemented in the user file
*/
}
/**
* @brief Timestamp Wraparound callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_TimestampWraparoundCallback(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TimestampWraparoundCallback could be implemented in the user file
*/
}
/**
* @brief Timeout Occurred callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_TimeoutOccurredCallback(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_TimeoutOccurredCallback could be implemented in the user file
*/
}
/**
* @brief High Priority Message callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_HighPriorityMessageCallback(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_HighPriorityMessageCallback could be implemented in the user file
*/
}
/**
* @brief Error callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval None
*/
__weak void HAL_FDCAN_ErrorCallback(FDCAN_HandleTypeDef *hfdcan)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_ErrorCallback could be implemented in the user file
*/
}
/**
* @brief Error status callback.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param ErrorStatusITs indicates which Error Status interrupts are signaled.
* This parameter can be any combination of @arg FDCAN_Error_Status_Interrupts.
* @retval None
*/
__weak void HAL_FDCAN_ErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfdcan);
UNUSED(ErrorStatusITs);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FDCAN_ErrorStatusCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup FDCAN_Exported_Functions_Group6 Peripheral State functions
* @brief FDCAN Peripheral State functions
*
@verbatim
==============================================================================
##### Peripheral State functions #####
==============================================================================
[..]
This subsection provides functions allowing to :
(+) HAL_FDCAN_GetState() : Return the FDCAN state.
(+) HAL_FDCAN_GetError() : Return the FDCAN error code if any.
@endverbatim
* @{
*/
/**
* @brief Return the FDCAN state
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval HAL state
*/
HAL_FDCAN_StateTypeDef HAL_FDCAN_GetState(FDCAN_HandleTypeDef *hfdcan)
{
/* Return FDCAN state */
return hfdcan->State;
}
/**
* @brief Return the FDCAN error code
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval FDCAN Error Code
*/
uint32_t HAL_FDCAN_GetError(FDCAN_HandleTypeDef *hfdcan)
{
/* Return FDCAN error code */
return hfdcan->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup FDCAN_Private_Functions FDCAN Private Functions
* @{
*/
/**
* @brief Calculate each RAM block start address and size
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @retval none
*/
static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan)
{
uint32_t RAMcounter;
uint32_t SramCanInstanceBase = SRAMCAN_BASE;
#if defined(FDCAN2)
if (hfdcan->Instance == FDCAN2)
{
SramCanInstanceBase += SRAMCAN_SIZE;
}
#endif /* FDCAN2 */
#if defined(FDCAN3)
if (hfdcan->Instance == FDCAN3)
{
SramCanInstanceBase += SRAMCAN_SIZE * 2U;
}
#endif /* FDCAN3 */
/* Standard filter list start address */
hfdcan->msgRam.StandardFilterSA = SramCanInstanceBase + SRAMCAN_FLSSA;
/* Standard filter elements number */
MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSS, (hfdcan->Init.StdFiltersNbr << FDCAN_RXGFC_LSS_Pos));
/* Extended filter list start address */
hfdcan->msgRam.ExtendedFilterSA = SramCanInstanceBase + SRAMCAN_FLESA;
/* Extended filter elements number */
MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSE, (hfdcan->Init.ExtFiltersNbr << FDCAN_RXGFC_LSE_Pos));
/* Rx FIFO 0 start address */
hfdcan->msgRam.RxFIFO0SA = SramCanInstanceBase + SRAMCAN_RF0SA;
/* Rx FIFO 1 start address */
hfdcan->msgRam.RxFIFO1SA = SramCanInstanceBase + SRAMCAN_RF1SA;
/* Tx event FIFO start address */
hfdcan->msgRam.TxEventFIFOSA = SramCanInstanceBase + SRAMCAN_TEFSA;
/* Tx FIFO/queue start address */
hfdcan->msgRam.TxFIFOQSA = SramCanInstanceBase + SRAMCAN_TFQSA;
/* Flush the allocated Message RAM area */
for (RAMcounter = SramCanInstanceBase; RAMcounter < (SramCanInstanceBase + SRAMCAN_SIZE); RAMcounter += 4U)
{
*(uint32_t *)(RAMcounter) = 0x00000000U;
}
}
/**
* @brief Copy Tx message to the message RAM.
* @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains
* the configuration information for the specified FDCAN.
* @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure.
* @param pTxData pointer to a buffer containing the payload of the Tx frame.
* @param BufferIndex index of the buffer to be configured.
* @retval none
*/
static void FDCAN_CopyMessageToRAM(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxHeaderTypeDef *pTxHeader, uint8_t *pTxData,
uint32_t BufferIndex)
{
uint32_t TxElementW1;
uint32_t TxElementW2;
uint32_t *TxAddress;
uint32_t ByteCounter;
/* Build first word of Tx header element */
if (pTxHeader->IdType == FDCAN_STANDARD_ID)
{
TxElementW1 = (pTxHeader->ErrorStateIndicator |
FDCAN_STANDARD_ID |
pTxHeader->TxFrameType |
(pTxHeader->Identifier << 18U));
}
else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */
{
TxElementW1 = (pTxHeader->ErrorStateIndicator |
FDCAN_EXTENDED_ID |
pTxHeader->TxFrameType |
pTxHeader->Identifier);
}
/* Build second word of Tx header element */
TxElementW2 = ((pTxHeader->MessageMarker << 24U) |
pTxHeader->TxEventFifoControl |
pTxHeader->FDFormat |
pTxHeader->BitRateSwitch |
pTxHeader->DataLength);
/* Calculate Tx element address */
TxAddress = (uint32_t *)(hfdcan->msgRam.TxFIFOQSA + (BufferIndex * SRAMCAN_TFQ_SIZE));
/* Write Tx element header to the message RAM */
*TxAddress = TxElementW1;
TxAddress++;
*TxAddress = TxElementW2;
TxAddress++;
/* Write Tx payload to the message RAM */
for (ByteCounter = 0; ByteCounter < DLCtoBytes[pTxHeader->DataLength >> 16U]; ByteCounter += 4U)
{
*TxAddress = (((uint32_t)pTxData[ByteCounter + 3U] << 24U) |
((uint32_t)pTxData[ByteCounter + 2U] << 16U) |
((uint32_t)pTxData[ByteCounter + 1U] << 8U) |
(uint32_t)pTxData[ByteCounter]);
TxAddress++;
}
}
/**
* @}
*/
#endif /* HAL_FDCAN_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
#endif /* FDCAN1 */
| 122,192 |
C
| 33.743531 | 119 | 0.640631 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_dma.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_dma.c
* @author MCD Application Team
* @brief DMA LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_dma.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (DMA1) || defined (DMA2)
/** @defgroup DMA_LL DMA
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DMA_LL_Private_Macros
* @{
*/
#define IS_LL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \
((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) || \
((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY))
#define IS_LL_DMA_MODE(__VALUE__) (((__VALUE__) == LL_DMA_MODE_NORMAL) || \
((__VALUE__) == LL_DMA_MODE_CIRCULAR))
#define IS_LL_DMA_PERIPHINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_PERIPH_INCREMENT) || \
((__VALUE__) == LL_DMA_PERIPH_NOINCREMENT))
#define IS_LL_DMA_MEMORYINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_MEMORY_INCREMENT) || \
((__VALUE__) == LL_DMA_MEMORY_NOINCREMENT))
#define IS_LL_DMA_PERIPHDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_PDATAALIGN_BYTE) || \
((__VALUE__) == LL_DMA_PDATAALIGN_HALFWORD) || \
((__VALUE__) == LL_DMA_PDATAALIGN_WORD))
#define IS_LL_DMA_MEMORYDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_MDATAALIGN_BYTE) || \
((__VALUE__) == LL_DMA_MDATAALIGN_HALFWORD) || \
((__VALUE__) == LL_DMA_MDATAALIGN_WORD))
#define IS_LL_DMA_NBDATA(__VALUE__) ((__VALUE__) <= (uint32_t)0x0000FFFFU)
#define IS_LL_DMA_PERIPHREQUEST(__VALUE__) ((__VALUE__) <= 115U)
#define IS_LL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == LL_DMA_PRIORITY_LOW) || \
((__VALUE__) == LL_DMA_PRIORITY_MEDIUM) || \
((__VALUE__) == LL_DMA_PRIORITY_HIGH) || \
((__VALUE__) == LL_DMA_PRIORITY_VERYHIGH))
#if defined (DMA1_Channel8)
#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \
(((CHANNEL) == LL_DMA_CHANNEL_1) || \
((CHANNEL) == LL_DMA_CHANNEL_2) || \
((CHANNEL) == LL_DMA_CHANNEL_3) || \
((CHANNEL) == LL_DMA_CHANNEL_4) || \
((CHANNEL) == LL_DMA_CHANNEL_5) || \
((CHANNEL) == LL_DMA_CHANNEL_6) || \
((CHANNEL) == LL_DMA_CHANNEL_7) || \
((CHANNEL) == LL_DMA_CHANNEL_8))) || \
(((INSTANCE) == DMA2) && \
(((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))))
#elif defined (DMA1_Channel6)
#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \
(((CHANNEL) == LL_DMA_CHANNEL_1) || \
((CHANNEL) == LL_DMA_CHANNEL_2) || \
((CHANNEL) == LL_DMA_CHANNEL_3) || \
((CHANNEL) == LL_DMA_CHANNEL_4) || \
((CHANNEL) == LL_DMA_CHANNEL_5) || \
((CHANNEL) == LL_DMA_CHANNEL_6))) || \
(((INSTANCE) == DMA2) && \
(((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))))
#endif /* DMA1_Channel8 */
/**
* @}
*/
/* 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.
* @param DMAx DMAx Instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_DMA_CHANNEL_1
* @arg @ref LL_DMA_CHANNEL_2
* @arg @ref LL_DMA_CHANNEL_3
* @arg @ref LL_DMA_CHANNEL_4
* @arg @ref LL_DMA_CHANNEL_5
* @arg @ref LL_DMA_CHANNEL_6
* @arg @ref LL_DMA_CHANNEL_7 (*)
* @arg @ref LL_DMA_CHANNEL_8 (*)
* @arg @ref LL_DMA_CHANNEL_ALL
* (*) Not on all G4 devices
* @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) || (Channel == LL_DMA_CHANNEL_ALL));
if (Channel == LL_DMA_CHANNEL_ALL)
{
if (DMAx == DMA1)
{
/* Force reset of DMA clock */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA1);
/* Release reset of DMA clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA1);
}
else if (DMAx == DMA2)
{
/* Force reset of DMA clock */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2);
/* Release reset of DMA clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA2);
}
else
{
status = ERROR;
}
}
else
{
tmp = (DMA_Channel_TypeDef *)(__LL_DMA_GET_CHANNEL_INSTANCE(DMAx, Channel));
/* Disable the selected DMAx_Channely */
CLEAR_BIT(tmp->CCR, DMA_CCR_EN);
/* Reset DMAx_Channely control register */
WRITE_REG(tmp->CCR, 0U);
/* Reset DMAx_Channely remaining bytes register */
WRITE_REG(tmp->CNDTR, 0U);
/* Reset DMAx_Channely peripheral address register */
WRITE_REG(tmp->CPAR, 0U);
/* Reset DMAx_Channely memory address register */
WRITE_REG(tmp->CMAR, 0U);
/* Reset Request register field for DMAx Channel */
LL_DMA_SetPeriphRequest(DMAx, Channel, LL_DMAMUX_REQ_MEM2MEM);
if (Channel == LL_DMA_CHANNEL_1)
{
/* Reset interrupt pending bits for DMAx Channel1 */
LL_DMA_ClearFlag_GI1(DMAx);
}
else if (Channel == LL_DMA_CHANNEL_2)
{
/* Reset interrupt pending bits for DMAx Channel2 */
LL_DMA_ClearFlag_GI2(DMAx);
}
else if (Channel == LL_DMA_CHANNEL_3)
{
/* Reset interrupt pending bits for DMAx Channel3 */
LL_DMA_ClearFlag_GI3(DMAx);
}
else if (Channel == LL_DMA_CHANNEL_4)
{
/* Reset interrupt pending bits for DMAx Channel4 */
LL_DMA_ClearFlag_GI4(DMAx);
}
else if (Channel == LL_DMA_CHANNEL_5)
{
/* Reset interrupt pending bits for DMAx Channel5 */
LL_DMA_ClearFlag_GI5(DMAx);
}
else if (Channel == LL_DMA_CHANNEL_6)
{
/* Reset interrupt pending bits for DMAx Channel6 */
LL_DMA_ClearFlag_GI6(DMAx);
}
#if defined (DMA1_Channel7)
else if (Channel == LL_DMA_CHANNEL_7)
{
/* Reset interrupt pending bits for DMAx Channel7 */
LL_DMA_ClearFlag_GI7(DMAx);
}
#endif /* DMA1_Channel7 */
#if defined (DMA1_Channel8)
else if (Channel == LL_DMA_CHANNEL_8)
{
/* Reset interrupt pending bits for DMAx Channel8 */
LL_DMA_ClearFlag_GI8(DMAx);
}
#endif /* DMA1_Channel8 */
else
{
status = ERROR;
}
}
return (uint32_t)status;
}
/**
* @brief Initialize the DMA registers according to the specified parameters in DMA_InitStruct.
* @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_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 (*)
* (*) Not on all G4 devices
* @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));
assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode));
assert_param(IS_LL_DMA_PERIPHINCMODE(DMA_InitStruct->PeriphOrM2MSrcIncMode));
assert_param(IS_LL_DMA_MEMORYINCMODE(DMA_InitStruct->MemoryOrM2MDstIncMode));
assert_param(IS_LL_DMA_PERIPHDATASIZE(DMA_InitStruct->PeriphOrM2MSrcDataSize));
assert_param(IS_LL_DMA_MEMORYDATASIZE(DMA_InitStruct->MemoryOrM2MDstDataSize));
assert_param(IS_LL_DMA_NBDATA(DMA_InitStruct->NbData));
assert_param(IS_LL_DMA_PERIPHREQUEST(DMA_InitStruct->PeriphRequest));
assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority));
/*---------------------------- DMAx CCR Configuration ------------------------
* Configure DMAx_Channely: data transfer direction, data transfer mode,
* peripheral and memory increment mode,
* data size alignment and priority level with parameters :
* - Direction: DMA_CCR_DIR and DMA_CCR_MEM2MEM bits
* - Mode: DMA_CCR_CIRC bit
* - PeriphOrM2MSrcIncMode: DMA_CCR_PINC bit
* - MemoryOrM2MDstIncMode: DMA_CCR_MINC bit
* - PeriphOrM2MSrcDataSize: DMA_CCR_PSIZE[1:0] bits
* - MemoryOrM2MDstDataSize: DMA_CCR_MSIZE[1:0] bits
* - Priority: DMA_CCR_PL[1:0] bits
*/
LL_DMA_ConfigTransfer(DMAx, Channel, DMA_InitStruct->Direction | \
DMA_InitStruct->Mode | \
DMA_InitStruct->PeriphOrM2MSrcIncMode | \
DMA_InitStruct->MemoryOrM2MDstIncMode | \
DMA_InitStruct->PeriphOrM2MSrcDataSize | \
DMA_InitStruct->MemoryOrM2MDstDataSize | \
DMA_InitStruct->Priority);
/*-------------------------- DMAx CMAR Configuration -------------------------
* Configure the memory or destination base address with parameter :
* - MemoryOrM2MDstAddress: DMA_CMAR_MA[31:0] bits
*/
LL_DMA_SetMemoryAddress(DMAx, Channel, DMA_InitStruct->MemoryOrM2MDstAddress);
/*-------------------------- DMAx CPAR Configuration -------------------------
* Configure the peripheral or source base address with parameter :
* - PeriphOrM2MSrcAddress: DMA_CPAR_PA[31:0] bits
*/
LL_DMA_SetPeriphAddress(DMAx, Channel, DMA_InitStruct->PeriphOrM2MSrcAddress);
/*--------------------------- DMAx CNDTR Configuration -----------------------
* Configure the peripheral base address with parameter :
* - NbData: DMA_CNDTR_NDT[15:0] bits
*/
LL_DMA_SetDataLength(DMAx, Channel, DMA_InitStruct->NbData);
/*--------------------------- DMAMUXx CCR Configuration ----------------------
* Configure the DMA request for DMA Channels on DMAMUX Channel x with parameter :
* - PeriphRequest: DMA_CxCR[7:0] bits
*/
LL_DMA_SetPeriphRequest(DMAx, Channel, DMA_InitStruct->PeriphRequest);
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->PeriphOrM2MSrcAddress = (uint32_t)0x00000000U;
DMA_InitStruct->MemoryOrM2MDstAddress = (uint32_t)0x00000000U;
DMA_InitStruct->Direction = LL_DMA_DIRECTION_PERIPH_TO_MEMORY;
DMA_InitStruct->Mode = LL_DMA_MODE_NORMAL;
DMA_InitStruct->PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
DMA_InitStruct->MemoryOrM2MDstIncMode = LL_DMA_MEMORY_NOINCREMENT;
DMA_InitStruct->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE;
DMA_InitStruct->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
DMA_InitStruct->NbData = (uint32_t)0x00000000U;
DMA_InitStruct->PeriphRequest = LL_DMAMUX_REQ_MEM2MEM;
DMA_InitStruct->Priority = LL_DMA_PRIORITY_LOW;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* DMA1 || DMA2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 15,814 |
C
| 40.949602 | 104 | 0.488175 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_lptim.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_lptim.c
* @author MCD Application Team
* @brief LPTIM LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_lptim.h"
#include "stm32g4xx_ll_bus.h"
#include "stm32g4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
/** @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))
#define IS_LL_LPTIM_OUTPUT_POLARITY(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_REGULAR) \
|| ((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_INVERSE))
/**
* @}
*/
/* 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_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM1);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1);
}
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;
LPTIM_InitStruct->Polarity = LL_LPTIM_OUTPUT_POLARITY_REGULAR;
}
/**
* @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));
assert_param(IS_LL_LPTIM_OUTPUT_POLARITY(LPTIM_InitStruct->Polarity));
/* 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 */
/* Set WAVEPOL bitfield according to Polarity value */
MODIFY_REG(LPTIMx->CFGR,
(LPTIM_CFGR_CKSEL | LPTIM_CFGR_PRESC | LPTIM_CFGR_WAVE | LPTIM_CFGR_WAVPOL),
LPTIM_InitStruct->ClockSource | \
LPTIM_InitStruct->Prescaler | \
LPTIM_InitStruct->Waveform | \
LPTIM_InitStruct->Polarity);
}
return result;
}
/**
* @brief Disable the LPTIM instance
* @rmtoll CR ENABLE LL_LPTIM_Disable
* @param LPTIMx Low-Power Timer instance
* @note The following sequence is required to solve LPTIM disable HW limitation.
* Please check Errata Sheet ES0335 for more details under "MCU may remain
* stuck in LPTIM interrupt when entering Stop mode" section.
* @retval None
*/
void LL_LPTIM_Disable(LPTIM_TypeDef *LPTIMx)
{
LL_RCC_ClocksTypeDef rcc_clock;
uint32_t tmpclksource = 0;
uint32_t tmpIER;
uint32_t tmpCFGR;
uint32_t tmpCMP;
uint32_t tmpARR;
uint32_t primask_bit;
uint32_t tmpOR;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(LPTIMx));
/* Enter critical section */
primask_bit = __get_PRIMASK();
__set_PRIMASK(1) ;
/********** Save LPTIM Config *********/
/* Save LPTIM source clock */
switch ((uint32_t)LPTIMx)
{
case LPTIM1_BASE:
tmpclksource = LL_RCC_GetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE);
break;
default:
break;
}
/* Save LPTIM configuration registers */
tmpIER = LPTIMx->IER;
tmpCFGR = LPTIMx->CFGR;
tmpCMP = LPTIMx->CMP;
tmpARR = LPTIMx->ARR;
tmpOR = LPTIMx->OR;
/************* Reset LPTIM ************/
(void)LL_LPTIM_DeInit(LPTIMx);
/********* Restore LPTIM Config *******/
LL_RCC_GetSystemClocksFreq(&rcc_clock);
if ((tmpCMP != 0UL) || (tmpARR != 0UL))
{
/* Force LPTIM source kernel clock from APB */
switch ((uint32_t)LPTIMx)
{
case LPTIM1_BASE:
LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE_PCLK1);
break;
default:
break;
}
if (tmpCMP != 0UL)
{
/* Restore CMP and ARR registers (LPTIM should be enabled first) */
LPTIMx->CR |= LPTIM_CR_ENABLE;
LPTIMx->CMP = tmpCMP;
/* Polling on CMP write ok status after above restore operation */
do
{
rcc_clock.SYSCLK_Frequency--; /* Used for timeout */
} while (((LL_LPTIM_IsActiveFlag_CMPOK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL));
LL_LPTIM_ClearFlag_CMPOK(LPTIMx);
}
if (tmpARR != 0UL)
{
LPTIMx->CR |= LPTIM_CR_ENABLE;
LPTIMx->ARR = tmpARR;
LL_RCC_GetSystemClocksFreq(&rcc_clock);
/* Polling on ARR write ok status after above restore operation */
do
{
rcc_clock.SYSCLK_Frequency--; /* Used for timeout */
}
while (((LL_LPTIM_IsActiveFlag_ARROK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL));
LL_LPTIM_ClearFlag_ARROK(LPTIMx);
}
/* Restore LPTIM source kernel clock */
LL_RCC_SetLPTIMClockSource(tmpclksource);
}
/* Restore configuration registers (LPTIM should be disabled first) */
LPTIMx->CR &= ~(LPTIM_CR_ENABLE);
LPTIMx->IER = tmpIER;
LPTIMx->CFGR = tmpCFGR;
LPTIMx->OR = tmpOR;
/* Exit critical section: restore previous priority mask */
__set_PRIMASK(primask_bit);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 9,251 |
C
| 29.635761 | 103 | 0.556697 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_sai_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 */
/**
* @}
*/
| 3,790 |
C
| 28.161538 | 117 | 0.501847 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_rtc_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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.
(+) If you do not intend to have tamper using RTC clock, you can bypass its initialization
by setting ClockEnable init 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.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @addtogroup RTCEx
* @brief RTC Extended HAL module driver
* @{
*/
#ifdef HAL_RTC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* 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(hrtc->Instance->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(hrtc->Instance->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;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Get the RTC_CR register and clear the bits to be configured */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE));
/* Configure the Time Stamp TSEDGE before Enable bit to avoid unwanted TSF setting. */
SET_BIT(hrtc->Instance->CR, (uint32_t)TimeStampEdge);
/* clear interrupt flag if any */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CITSF);
/* Enable IT timestamp */
SET_BIT(hrtc->Instance->CR, (RTC_CR_TSE | RTC_CR_TSIE));
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* RTC timestamp Interrupt Configuration: EXTI configuration (always rising edge)*/
__HAL_RTC_TIMESTAMP_EXTI_RISING_IT();
__HAL_RTC_TIMESTAMP_EXTI_ENABLE_IT();
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);
/* clear event or interrupt flag */
WRITE_REG(hrtc->Instance->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF));
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE));
__HAL_RTC_TIMESTAMP_EXTI_CLEAR_IT();
/* 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(hrtc->Instance->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(hrtc->Instance->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, tmpdate;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get the TimeStamp time and date registers values */
tmptime = (uint32_t)READ_BIT(hrtc->Instance->TSTR, RTC_TR_RESERVED_MASK);
tmpdate = (uint32_t)READ_BIT(hrtc->Instance->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 = (uint32_t)READ_BIT(hrtc->Instance->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)) >> RTC_TSDR_DU_Pos);
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(hrtc->Instance->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF));
return HAL_OK;
}
/**
* @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 interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Clear the EXTI Flag for RTC TimeStamp */
__HAL_RTC_TIMESTAMP_EXTI_CLEAR_FLAG();
__IO uint32_t misr = READ_REG(hrtc->Instance->MISR);
/* Get the TimeStamp interrupt source enable */
if ((misr & RTC_MISR_TSMF) != 0U)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call TimeStampEvent registered Callback */
hrtc->TimeStampEventCallback(hrtc);
#else
/* TIMESTAMP callback */
HAL_RTCEx_TimeStampEventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
/* check if TimeStamp is Internal, since ITSE bit is set in the CR */
if ((misr & RTC_MISR_ITSMF) != 0U)
{
/* internal Timestamp interrupt */
/* ITSF flag is set, TSF must be cleared together with ITSF (this will clear timestamp time and date registers) */
WRITE_REG(hrtc->Instance->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF));
}
else
{
/* Clear the TIMESTAMP interrupt pending bit (this will clear timestamp time and date registers) */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CTSF);
}
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
/**
* @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(hrtc->Instance->SR, RTC_SR_TSF) == 0U)
{
if (READ_BIT(hrtc->Instance->SR, RTC_SR_TSOVF) != 0U)
{
/* Clear the TIMESTAMP OverRun Flag */
WRITE_REG(hrtc->Instance->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;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
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(hrtc->Instance->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(hrtc->Instance->ICSR, RTC_ICSR_INITF) == 0U)
{
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is reset and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->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(hrtc->Instance->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock);
/* Configure the Wakeup Timer counter */
WRITE_REG(hrtc->Instance->WUTR, (uint32_t)WakeUpCounter);
/* Enable the Wakeup Timer */
SET_BIT(hrtc->Instance->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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(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(hrtc->Instance->CR, RTC_CR_WUTE);
/* Clear flag Wake-Up */
__HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF);
/* 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(hrtc->Instance->ICSR, RTC_ICSR_INITF) == 0U)
{
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is reset and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->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 */
WRITE_REG(hrtc->Instance->WUTR, (uint32_t)WakeUpCounter);
/* Configure the clock source */
MODIFY_REG(hrtc->Instance->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock);
/* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */
__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT();
__HAL_RTC_WAKEUPTIMER_EXTI_RISING_IT();
/* Configure the Interrupt in the RTC_CR register and Enable the Wakeup Timer */
SET_BIT(hrtc->Instance->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(hrtc->Instance->CR, RTC_CR_WUTE | RTC_CR_WUTIE);
__HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_IT();
tickstart = HAL_GetTick();
/* Wait till RTC WUTWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->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)
{
/* Get the counter value */
return (uint32_t)(READ_BIT(hrtc->Instance->WUTR, RTC_WUTR_WUT));
}
/**
* @brief Handle Wake Up Timer interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get the pending status of the WAKEUPTIMER Interrupt */
if (READ_BIT(hrtc->Instance->SR, RTC_SR_WUTF) != 0U)
{
/* Clear the WAKEUPTIMER interrupt pending bit */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CWUTF);
__HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_IT();
#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;
}
/**
* @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(hrtc->Instance->SR, RTC_SR_WUTF) == 0U)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Clear the WAKEUPTIMER Flag */
WRITE_REG(hrtc->Instance->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.
(+) 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(hrtc->Instance->ICSR, RTC_ICSR_RECALPF) != 0U)
{
tickstart = HAL_GetTick();
/* check if a calibration is pending*/
while (READ_BIT(hrtc->Instance->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(hrtc->Instance->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 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(hrtc->Instance->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(hrtc->Instance->CR, RTC_CR_REFCKON) == 0U)
{
/* Configure the Shift settings */
MODIFY_REG(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->CR, RTC_CR_COSEL, (uint32_t)CalibOutput);
/* Enable calibration output */
SET_BIT(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->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;
}
/**
* @}
*/
/** @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(hrtc->Instance->SR, RTC_SR_ALRBF) == 0U)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Clear the Alarm Flag */
WRITE_REG(hrtc->Instance->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;
/* 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));
/* 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_TAMP1MF_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_TAMP1MF_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(hrtc->Instance->CR, RTC_CR_TAMPTS) != (sTamper->TimeStampOnTamperDetection))
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(hrtc->Instance->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;
/* 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_TAMP1MF_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)
{
tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1MF_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(hrtc->Instance->CR, RTC_CR_TAMPTS) != sTamper->TimeStampOnTamperDetection)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(hrtc->Instance->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* RTC Tamper Interrupt Configuration: EXTI configuration */
__HAL_RTC_TAMPER_EXTI_ENABLE_IT();
__HAL_RTC_TAMPER_EXTI_RISING_IT();
__HAL_RTC_TAMPER_EXTI_CLEAR_IT();
/* 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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper)
{
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_TAMP1MF_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);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_TAMPER_EXTI_CLEAR_IT();
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
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTCEx_PollForTamperEvent(RTC_HandleTypeDef *hrtc, uint32_t Tamper, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
UNUSED(hrtc);
assert_param(IS_RTC_TAMPER(Tamper));
/* 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 in interrupt mode
* @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)
{
/* Check the parameters */
assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper));
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection));
/* timestamp on internal tamper */
if (READ_BIT(hrtc->Instance->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(hrtc->Instance->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* Control register 1 */
SET_BIT(TAMP->CR1, sIntTamper->IntTamper);
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_IT(RTC_HandleTypeDef *hrtc, RTC_InternalTamperTypeDef *sIntTamper)
{
/* Check the parameters */
assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper));
assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection));
/* timestamp on internal tamper */
if (READ_BIT(hrtc->Instance->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
MODIFY_REG(hrtc->Instance->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection);
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
}
/* RTC Tamper Interrupt Configuration: EXTI configuration */
__HAL_RTC_TAMPER_EXTI_ENABLE_IT();
__HAL_RTC_TAMPER_EXTI_RISING_IT();
/* Interrupt enable register */
SET_BIT(TAMP->IER, sIntTamper->IntTamper);
/* 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);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_TAMPER_EXTI_CLEAR_IT();
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;
}
/**
* @brief Handle Tamper interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTCEx_TamperIRQHandler(RTC_HandleTypeDef *hrtc)
{
uint32_t tmp;
/* Get interrupt status */
tmp = READ_REG(TAMP->MISR);
/* Check enable interrupts */
tmp &= READ_REG(TAMP->IER);
/* Immediately clear flags */
WRITE_REG(TAMP->SCR, tmp);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_TAMPER_EXTI_CLEAR_IT();
/* Check Tamper1 status */
if ((tmp & RTC_TAMPER_1) == RTC_TAMPER_1)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 1 Event registered Callback */
hrtc->Tamper1EventCallback(hrtc);
#else
/* Tamper1 callback */
HAL_RTCEx_Tamper1EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Check Tamper2 status */
if ((tmp & RTC_TAMPER_2) == RTC_TAMPER_2)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Tamper 2 Event registered Callback */
hrtc->Tamper2EventCallback(hrtc);
#else
/* Tamper2 callback */
HAL_RTCEx_Tamper2EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
#if (RTC_TAMP_NB == 3)
/* 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 */
}
#endif /* RTC_TAMP_NB */
#ifdef RTC_TAMP_INT_1_SUPPORT
/* 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 */
}
#endif /* RTC_TAMP_INT_1_SUPPORT */
#ifdef RTC_TAMP_INT_2_SUPPORT
/* 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 */
}
#endif /* RTC_TAMP_INT_2_SUPPORT */
/* Check Internal Tamper3 status */
if ((tmp & RTC_INT_TAMPER_3) == RTC_INT_TAMPER_3)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 3 Event registered Callback */
hrtc->InternalTamper3EventCallback(hrtc);
#else
/* Internal Tamper3 callback */
HAL_RTCEx_InternalTamper3EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Check Internal Tamper4 status */
if ((tmp & RTC_INT_TAMPER_4) == RTC_INT_TAMPER_4)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 4 Event registered Callback */
hrtc->InternalTamper4EventCallback(hrtc);
#else
/* Internal Tamper4 callback */
HAL_RTCEx_InternalTamper4EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Check Internal Tamper5 status */
if ((tmp & RTC_INT_TAMPER_5) == RTC_INT_TAMPER_5)
{
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Internal Tamper 5 Event registered Callback */
hrtc->InternalTamper5EventCallback(hrtc);
#else
/* Internal Tamper5 callback */
HAL_RTCEx_InternalTamper5EventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
#ifdef RTC_TAMP_INT_6_SUPPORT
/* 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 */
}
#endif /* RTC_TAMP_INT_6_SUPPORT */
#ifdef RTC_TAMP_INT_7_SUPPORT
/* 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 */
}
#endif /* RTC_TAMP_INT_7_SUPPORT */
}
/**
* @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
*/
}
#if (RTC_TAMP_NB == 3)
/**
* @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
*/
}
#endif /* RTC_TAMP_NB */
#ifdef RTC_TAMP_INT_1_SUPPORT
/**
* @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
*/
}
#endif /* RTC_TAMP_INT_1_SUPPORT */
#ifdef RTC_TAMP_INT_2_SUPPORT
/**
* @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
*/
}
#endif /* RTC_TAMP_INT_2_SUPPORT */
/**
* @brief Internal Tamper 3 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_InternalTamper3EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_InternalTamper3EventCallback could be implemented in the user file
*/
}
/**
* @brief Internal Tamper 4 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_InternalTamper4EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_InternalTamper4EventCallback could be implemented in the user file
*/
}
/**
* @brief Internal Tamper 5 callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTCEx_InternalTamper5EventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTCEx_InternalTamper5EventCallback could be implemented in the user file
*/
}
#ifdef RTC_TAMP_INT_6_SUPPORT
/**
* @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
*/
}
#endif /* RTC_TAMP_INT_6_SUPPORT */
#ifdef RTC_TAMP_INT_7_SUPPORT
/**
* @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
*/
}
#endif /* RTC_TAMP_INT_7_SUPPORT */
/**
* @}
*/
/** @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 TAMP Backup data register.
* @param hrtc RTC handle
* @param BackupRegister RTC Backup data Register number.
* This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to
* specify the register.
* @param Data Data to be written in the specified TAMP 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 TAMP 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 to
* specify the register.
* @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);
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_RTC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 62,722 |
C
| 29.330271 | 178 | 0.645404 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_spi.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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
(+++) 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(or _rx) handle to the hspi DMA Tx or Rx handle
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream/Channel
(#) 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.
[..]
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
(#) When the SPI DMA Pause/Stop features are used, we must use the following APIs
the HAL_SPI_DMAPause()/ HAL_SPI_DMAStop() only under the SPI callbacks
[..]
Master Receive mode restriction:
(#) In Master unidirectional receive-only mode (MSTR =1, BIDIMODE=0, RXONLY=1) or
bidirectional receive mode (MSTR=1, BIDIMODE=1, BIDIOE=0), to ensure that the SPI
does not initiate a new transfer the following procedure has to be respected:
(##) HAL_SPI_DeInit()
(##) HAL_SPI_Init()
[..]
Callback registration:
(#) The compilation flag USE_HAL_SPI_REGISTER_CALLBACKS when set to 1U
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.
[..]
Using the HAL it is not possible to reach all supported SPI frequency with the different SPI Modes,
the following table resume the max SPI frequency reached with data size 8bits/16bits,
according to frequency of the APBx Peripheral Clock (fPCLK) used by the SPI instance.
@endverbatim
Additional table :
DataSize = SPI_DATASIZE_8BIT:
+----------------------------------------------------------------------------------------------+
| | | 2Lines Fullduplex | 2Lines RxOnly | 1Line |
| Process | Transfer mode |---------------------|----------------------|----------------------|
| | | Master | Slave | Master | Slave | Master | Slave |
|==============================================================================================|
| T | Polling | Fpclk/4 | Fpclk/8 | NA | NA | NA | NA |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| / | Interrupt | Fpclk/4 | Fpclk/16 | NA | NA | NA | NA |
| R |----------------|----------|----------|-----------|----------|-----------|----------|
| X | DMA | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA |
|=========|================|==========|==========|===========|==========|===========|==========|
| | Polling | Fpclk/4 | Fpclk/8 | Fpclk/16 | Fpclk/8 | Fpclk/8 | Fpclk/8 |
| |----------------|----------|----------|-----------|----------|-----------|----------|
| R | Interrupt | Fpclk/8 | Fpclk/16 | Fpclk/8 | Fpclk/8 | Fpclk/8 | Fpclk/4 |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| | DMA | Fpclk/4 | Fpclk/2 | Fpclk/2 | Fpclk/16 | Fpclk/2 | Fpclk/16 |
|=========|================|==========|==========|===========|==========|===========|==========|
| | Polling | Fpclk/8 | Fpclk/2 | NA | NA | Fpclk/8 | Fpclk/8 |
| |----------------|----------|----------|-----------|----------|-----------|----------|
| T | Interrupt | Fpclk/2 | Fpclk/4 | NA | NA | Fpclk/16 | Fpclk/8 |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| | DMA | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/8 | Fpclk/16 |
+----------------------------------------------------------------------------------------------+
DataSize = SPI_DATASIZE_16BIT:
+----------------------------------------------------------------------------------------------+
| | | 2Lines Fullduplex | 2Lines RxOnly | 1Line |
| Process | Transfer mode |---------------------|----------------------|----------------------|
| | | Master | Slave | Master | Slave | Master | Slave |
|==============================================================================================|
| T | Polling | Fpclk/4 | Fpclk/8 | NA | NA | NA | NA |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| / | Interrupt | Fpclk/4 | Fpclk/16 | NA | NA | NA | NA |
| R |----------------|----------|----------|-----------|----------|-----------|----------|
| X | DMA | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA |
|=========|================|==========|==========|===========|==========|===========|==========|
| | Polling | Fpclk/4 | Fpclk/8 | Fpclk/16 | Fpclk/8 | Fpclk/8 | Fpclk/8 |
| |----------------|----------|----------|-----------|----------|-----------|----------|
| R | Interrupt | Fpclk/8 | Fpclk/16 | Fpclk/8 | Fpclk/8 | Fpclk/8 | Fpclk/4 |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| | DMA | Fpclk/4 | Fpclk/2 | Fpclk/2 | Fpclk/16 | Fpclk/2 | Fpclk/16 |
|=========|================|==========|==========|===========|==========|===========|==========|
| | Polling | Fpclk/8 | Fpclk/2 | NA | NA | Fpclk/8 | Fpclk/8 |
| |----------------|----------|----------|-----------|----------|-----------|----------|
| T | Interrupt | Fpclk/2 | Fpclk/4 | NA | NA | Fpclk/16 | Fpclk/8 |
| X |----------------|----------|----------|-----------|----------|-----------|----------|
| | DMA | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/8 | Fpclk/16 |
+----------------------------------------------------------------------------------------------+
@note The max SPI frequency depend on SPI data size (4bits, 5bits,..., 8bits,...15bits, 16bits),
SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA).
@note
(#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA()
(#) RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA()
(#) TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA()
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 100U
/**
* @}
*/
/* 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_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus State,
uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Fifo, uint32_t State,
uint32_t Timeout, uint32_t Tickstart);
static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi);
#if (USE_SPI_CRC != 0U)
static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi);
static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi);
static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi);
#endif /* USE_SPI_CRC */
static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi);
static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi);
static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi);
static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi);
static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi);
static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart);
/**
* @}
*/
/* 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
(+) 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 frxth;
/* 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));
assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize));
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 (hspi->Init.Mode == SPI_MODE_MASTER)
{
assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler));
}
else
{
/* Baudrate prescaler not use in Motoraola Slave mode. force to default value */
hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
}
}
else
{
assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler));
/* Force polarity and phase to TI protocaol requirements */
hspi->Init.CLKPolarity = SPI_POLARITY_LOW;
hspi->Init.CLKPhase = SPI_PHASE_1EDGE;
}
#if (USE_SPI_CRC != 0U)
assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation));
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial));
assert_param(IS_SPI_CRC_LENGTH(hspi->Init.CRCLength));
}
#else
hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
#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 == 1U)
/* 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);
/* Align by default the rs fifo threshold on the data size */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
frxth = SPI_RXFIFO_THRESHOLD_HF;
}
else
{
frxth = SPI_RXFIFO_THRESHOLD_QF;
}
/* CRC calculation is valid only for 16Bit and 8 Bit */
if ((hspi->Init.DataSize != SPI_DATASIZE_16BIT) && (hspi->Init.DataSize != SPI_DATASIZE_8BIT))
{
/* CRC must be disabled */
hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
}
/*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/
/* Configure : SPI Mode, Communication Mode, Clock polarity and phase, NSS management,
Communication speed, First bit and CRC calculation state */
WRITE_REG(hspi->Instance->CR1, ((hspi->Init.Mode & (SPI_CR1_MSTR | SPI_CR1_SSI)) |
(hspi->Init.Direction & (SPI_CR1_RXONLY | SPI_CR1_BIDIMODE)) |
(hspi->Init.CLKPolarity & SPI_CR1_CPOL) |
(hspi->Init.CLKPhase & SPI_CR1_CPHA) |
(hspi->Init.NSS & SPI_CR1_SSM) |
(hspi->Init.BaudRatePrescaler & SPI_CR1_BR_Msk) |
(hspi->Init.FirstBit & SPI_CR1_LSBFIRST) |
(hspi->Init.CRCCalculation & SPI_CR1_CRCEN)));
#if (USE_SPI_CRC != 0U)
/*---------------------------- SPIx CRCL Configuration -------------------*/
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Align the CRC Length on the data size */
if (hspi->Init.CRCLength == SPI_CRC_LENGTH_DATASIZE)
{
/* CRC Length aligned on the data size : value set by default */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
hspi->Init.CRCLength = SPI_CRC_LENGTH_16BIT;
}
else
{
hspi->Init.CRCLength = SPI_CRC_LENGTH_8BIT;
}
}
/* Configure : CRC Length */
if (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCL);
}
}
#endif /* USE_SPI_CRC */
/* Configure : NSS management, TI Mode, NSS Pulse, Data size and Rx Fifo threshold */
WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16U) & SPI_CR2_SSOE) |
(hspi->Init.TIMode & SPI_CR2_FRF) |
(hspi->Init.NSSPMode & SPI_CR2_NSSP) |
(hspi->Init.DataSize & SPI_CR2_DS_Msk) |
(frxth & SPI_CR2_FRXTH)));
#if (USE_SPI_CRC != 0U)
/*---------------------------- SPIx CRCPOLY Configuration ------------------*/
/* Configure : CRC Polynomial */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
WRITE_REG(hspi->Instance->CRCPR, (hspi->Init.CRCPolynomial & SPI_CRCPR_CRCPOLY_Msk));
}
#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 */
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 == 1U)
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 == 1U)
/**
* @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;
}
/* Process locked */
__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;
/* Process locked */
__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)
{
uint32_t tickstart;
HAL_StatusTypeDef errorcode = HAL_OK;
uint16_t initial_TxXferCount;
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
initial_TxXferCount = Size;
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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 = (uint8_t *)NULL;
hspi->RxXferSize = 0U;
hspi->RxXferCount = 0U;
hspi->TxISR = NULL;
hspi->RxISR = NULL;
/* Configure communication direction : 1Line */
if (hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_TX(hspi);
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Transmit data in 16 Bit mode */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U))
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
}
/* Transmit data in 16 Bit mode */
while (hspi->TxXferCount > 0U)
{
/* Wait until TXE flag is set to send data */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE))
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
}
else
{
/* Timeout management */
if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
}
/* Transmit data in 8 Bit mode */
else
{
if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U))
{
if (hspi->TxXferCount > 1U)
{
/* write on the data register in packing mode */
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= 2U;
}
else
{
*((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr ++;
hspi->TxXferCount--;
}
}
while (hspi->TxXferCount > 0U)
{
/* Wait until TXE flag is set to send data */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE))
{
if (hspi->TxXferCount > 1U)
{
/* write on the data register in packing mode */
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= 2U;
}
else
{
*((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr++;
hspi->TxXferCount--;
}
}
else
{
/* Timeout management */
if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
}
#if (USE_SPI_CRC != 0U)
/* Enable CRC Transmission */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_FLAG;
}
/* Clear overrun flag in 2 Lines communication mode because received is not read */
if (hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
errorcode = HAL_ERROR;
}
error:
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return errorcode;
}
/**
* @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)
{
#if (USE_SPI_CRC != 0U)
__IO uint32_t tmpreg = 0U;
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
#endif /* USE_SPI_CRC */
uint32_t tickstart;
HAL_StatusTypeDef errorcode = HAL_OK;
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);
}
/* Process Locked */
__HAL_LOCK(hspi);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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 = (uint8_t *)NULL;
hspi->TxXferSize = 0U;
hspi->TxXferCount = 0U;
hspi->RxISR = NULL;
hspi->TxISR = NULL;
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
/* this is done to handle the CRCNEXT before the latest data */
hspi->RxXferCount--;
}
#endif /* USE_SPI_CRC */
/* Set the Rx Fifo threshold */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
/* Set RX Fifo threshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set RX Fifo threshold according the reception data length: 8bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
/* Configure communication direction: 1Line */
if (hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_RX(hspi);
}
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Receive data in 8 Bit mode */
if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT)
{
/* Transfer loop */
while (hspi->RxXferCount > 0U)
{
/* Check the RXNE flag */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE))
{
/* read the received data */
(* (uint8_t *)hspi->pRxBuffPtr) = *(__IO uint8_t *)&hspi->Instance->DR;
hspi->pRxBuffPtr += sizeof(uint8_t);
hspi->RxXferCount--;
}
else
{
/* Timeout management */
if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
}
else
{
/* Transfer loop */
while (hspi->RxXferCount > 0U)
{
/* Check the RXNE flag */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE))
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DR;
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount--;
}
else
{
/* Timeout management */
if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
}
#if (USE_SPI_CRC != 0U)
/* Handle the CRC Transmission */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* freeze the CRC before the latest data */
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
/* Read the latest data */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK)
{
/* the latest data has not been received */
errorcode = HAL_TIMEOUT;
goto error;
}
/* Receive last data in 16 Bit mode */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DR;
}
/* Receive last data in 8 Bit mode */
else
{
(*(uint8_t *)hspi->pRxBuffPtr) = *(__IO uint8_t *)&hspi->Instance->DR;
}
/* Wait the CRC data */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
errorcode = HAL_TIMEOUT;
goto error;
}
/* Read CRC to Flush DR and RXNE flag */
if (hspi->Init.DataSize == SPI_DATASIZE_16BIT)
{
/* Read 16bit CRC */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
}
else
{
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
if ((hspi->Init.DataSize == SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT))
{
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
errorcode = HAL_TIMEOUT;
goto error;
}
/* Read 8bit CRC again in case of 16bit CRC in 8bit Data mode */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
}
}
}
#endif /* USE_SPI_CRC */
/* Check the end of the transaction */
if (SPI_EndRxTransaction(hspi, Timeout, tickstart) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_FLAG;
}
#if (USE_SPI_CRC != 0U)
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
#endif /* USE_SPI_CRC */
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
errorcode = HAL_ERROR;
}
error :
hspi->State = HAL_SPI_STATE_READY;
__HAL_UNLOCK(hspi);
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)
{
uint16_t initial_TxXferCount;
uint16_t initial_RxXferCount;
uint32_t tmp_mode;
HAL_SPI_StateTypeDef tmp_state;
uint32_t tickstart;
#if (USE_SPI_CRC != 0U)
__IO uint32_t tmpreg = 0U;
uint32_t spi_cr1;
uint32_t spi_cr2;
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
#endif /* USE_SPI_CRC */
/* Variable used to alternate Rx and Tx during transfer */
uint32_t txallowed = 1U;
HAL_StatusTypeDef errorcode = HAL_OK;
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* Init temporary variables */
tmp_state = hspi->State;
tmp_mode = hspi->Init.Mode;
initial_TxXferCount = Size;
initial_RxXferCount = Size;
#if (USE_SPI_CRC != 0U)
spi_cr1 = READ_REG(hspi->Instance->CR1);
spi_cr2 = READ_REG(hspi->Instance->CR2);
#endif /* USE_SPI_CRC */
if (!((tmp_state == HAL_SPI_STATE_READY) || \
((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX))))
{
errorcode = HAL_BUSY;
goto error;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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;
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
/* Set the Rx Fifo threshold */
if ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) || (initial_RxXferCount > 1U))
{
/* Set fiforxthreshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set fiforxthreshold according the reception data length: 8bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Transmit and Receive data in 16 Bit mode */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U))
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
}
while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U))
{
/* Check TXE flag */
if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U))
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
/* Next Data is a reception (Rx). Tx not allowed */
txallowed = 0U;
#if (USE_SPI_CRC != 0U)
/* Enable CRC Transmission */
if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
/* Set NSS Soft to received correctly the CRC on slave mode with NSS pulse activated */
if ((READ_BIT(spi_cr1, SPI_CR1_MSTR) == 0U) && (READ_BIT(spi_cr2, SPI_CR2_NSSP) == SPI_CR2_NSSP))
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_SSM);
}
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
}
/* Check RXNE flag */
if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) && (hspi->RxXferCount > 0U))
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DR;
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount--;
/* Next Data is a Transmission (Tx). Tx is allowed */
txallowed = 1U;
}
if (((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
/* Transmit and Receive data in 8 Bit mode */
else
{
if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U))
{
if (hspi->TxXferCount > 1U)
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= 2U;
}
else
{
*(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr++;
hspi->TxXferCount--;
}
}
while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U))
{
/* Check TXE flag */
if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U))
{
if (hspi->TxXferCount > 1U)
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= 2U;
}
else
{
*(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr++;
hspi->TxXferCount--;
}
/* Next Data is a reception (Rx). Tx not allowed */
txallowed = 0U;
#if (USE_SPI_CRC != 0U)
/* Enable CRC Transmission */
if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
/* Set NSS Soft to received correctly the CRC on slave mode with NSS pulse activated */
if ((READ_BIT(spi_cr1, SPI_CR1_MSTR) == 0U) && (READ_BIT(spi_cr2, SPI_CR2_NSSP) == SPI_CR2_NSSP))
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_SSM);
}
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
}
/* Wait until RXNE flag is reset */
if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) && (hspi->RxXferCount > 0U))
{
if (hspi->RxXferCount > 1U)
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DR;
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount -= 2U;
if (hspi->RxXferCount <= 1U)
{
/* Set RX Fifo threshold before to switch on 8 bit data size */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
}
else
{
(*(uint8_t *)hspi->pRxBuffPtr) = *(__IO uint8_t *)&hspi->Instance->DR;
hspi->pRxBuffPtr++;
hspi->RxXferCount--;
}
/* Next Data is a Transmission (Tx). Tx is allowed */
txallowed = 1U;
}
if ((((HAL_GetTick() - tickstart) >= Timeout) && ((Timeout != HAL_MAX_DELAY))) || (Timeout == 0U))
{
errorcode = HAL_TIMEOUT;
goto error;
}
}
}
#if (USE_SPI_CRC != 0U)
/* Read CRC from DR to close CRC calculation process */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Wait until TXE flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
errorcode = HAL_TIMEOUT;
goto error;
}
/* Read CRC */
if (hspi->Init.DataSize == SPI_DATASIZE_16BIT)
{
/* Read 16bit CRC */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
}
else
{
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
if (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)
{
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
errorcode = HAL_TIMEOUT;
goto error;
}
/* Read 8bit CRC again in case of 16bit CRC in 8bit Data mode */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
}
}
}
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
/* Clear CRC Flag */
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
errorcode = HAL_ERROR;
}
#endif /* USE_SPI_CRC */
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK)
{
errorcode = HAL_ERROR;
hspi->ErrorCode = HAL_SPI_ERROR_FLAG;
}
error :
hspi->State = HAL_SPI_STATE_READY;
__HAL_UNLOCK(hspi);
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(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
/* 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 = (uint8_t *)NULL;
hspi->RxXferSize = 0U;
hspi->RxXferCount = 0U;
hspi->RxISR = NULL;
/* Set the function for IT treatment */
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)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_TX(hspi);
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
/* Enable TXE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR));
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
error :
__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;
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);
}
/* Process Locked */
__HAL_LOCK(hspi);
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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 = (uint8_t *)NULL;
hspi->TxXferSize = 0U;
hspi->TxXferCount = 0U;
hspi->TxISR = NULL;
/* Check the data size to adapt Rx threshold and the set the function for IT treatment */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
/* Set RX Fifo threshold according the reception data length: 16 bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
hspi->RxISR = SPI_RxISR_16BIT;
}
else
{
/* Set RX Fifo threshold according the reception data length: 8 bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
hspi->RxISR = SPI_RxISR_8BIT;
}
/* Configure communication direction : 1Line */
if (hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_RX(hspi);
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->CRCSize = 1U;
if ((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT))
{
hspi->CRCSize = 2U;
}
SPI_RESET_CRC(hspi);
}
else
{
hspi->CRCSize = 0U;
}
#endif /* USE_SPI_CRC */
/* Enable TXE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
/* Note : The SPI must be enabled after unlocking current process
to avoid the risk of SPI interrupt handle execution before current
process unlock */
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
error :
/* Process Unlocked */
__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)
{
uint32_t tmp_mode;
HAL_SPI_StateTypeDef tmp_state;
HAL_StatusTypeDef errorcode = HAL_OK;
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process locked */
__HAL_LOCK(hspi);
/* Init temporary variables */
tmp_state = hspi->State;
tmp_mode = hspi->Init.Mode;
if (!((tmp_state == HAL_SPI_STATE_READY) || \
((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX))))
{
errorcode = HAL_BUSY;
goto error;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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;
/* Set the function for IT treatment */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
hspi->RxISR = SPI_2linesRxISR_16BIT;
hspi->TxISR = SPI_2linesTxISR_16BIT;
}
else
{
hspi->RxISR = SPI_2linesRxISR_8BIT;
hspi->TxISR = SPI_2linesTxISR_8BIT;
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->CRCSize = 1U;
if ((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT))
{
hspi->CRCSize = 2U;
}
SPI_RESET_CRC(hspi);
}
else
{
hspi->CRCSize = 0U;
}
#endif /* USE_SPI_CRC */
/* Check if packing mode is enabled and if there is more than 2 data to receive */
if ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) || (Size >= 2U))
{
/* Set RX Fifo threshold according the reception data length: 16 bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set RX Fifo threshold according the reception data length: 8 bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
/* Enable TXE, RXNE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
error :
/* Process Unlocked */
__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 = HAL_OK;
/* Check tx dma handle */
assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx));
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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 = (uint8_t *)NULL;
hspi->TxISR = NULL;
hspi->RxISR = NULL;
hspi->RxXferSize = 0U;
hspi->RxXferCount = 0U;
/* Configure communication direction : 1Line */
if (hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_TX(hspi);
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
/* 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_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX);
/* Packing mode is enabled only if the DMA setting is HALWORD */
if ((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->hdmatx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD))
{
/* Check the even/odd of the data size + crc if enabled */
if ((hspi->TxXferCount & 0x1U) == 0U)
{
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX);
hspi->TxXferCount = (hspi->TxXferCount >> 1U);
}
else
{
SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX);
hspi->TxXferCount = (hspi->TxXferCount >> 1U) + 1U;
}
}
/* Enable the Tx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR,
hspi->TxXferCount))
{
/* Update SPI error code */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
hspi->State = HAL_SPI_STATE_READY;
goto error;
}
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Enable the SPI Error Interrupt Bit */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR));
/* Enable Tx DMA Request */
SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN);
error :
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return errorcode;
}
/**
* @brief Receive an amount of data in non-blocking mode with DMA.
* @note In case of MASTER mode and SPI_DIRECTION_2LINES direction, hdmatx shall be defined.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData pointer to data buffer
* @note When the CRC feature is enabled the pData Length must be Size + 1.
* @param Size amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
{
HAL_StatusTypeDef errorcode = HAL_OK;
/* Check rx dma handle */
assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx));
if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
{
hspi->State = HAL_SPI_STATE_BUSY_RX;
/* Check tx dma handle */
assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx));
/* 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);
}
/* Process Locked */
__HAL_LOCK(hspi);
if (hspi->State != HAL_SPI_STATE_READY)
{
errorcode = HAL_BUSY;
goto error;
}
if ((pData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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 = 0U;
hspi->TxXferCount = 0U;
/* Configure communication direction : 1Line */
if (hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */
__HAL_SPI_DISABLE(hspi);
SPI_1LINE_RX(hspi);
}
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX);
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
/* Set RX Fifo threshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set RX Fifo threshold according the reception data length: 8bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
if (hspi->hdmarx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD)
{
/* Set RX Fifo threshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
if ((hspi->RxXferCount & 0x1U) == 0x0U)
{
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX);
hspi->RxXferCount = hspi->RxXferCount >> 1U;
}
else
{
SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX);
hspi->RxXferCount = (hspi->RxXferCount >> 1U) + 1U;
}
}
}
/* 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;
/* Enable the Rx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr,
hspi->RxXferCount))
{
/* Update SPI error code */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
hspi->State = HAL_SPI_STATE_READY;
goto error;
}
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Enable the SPI Error Interrupt Bit */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR));
/* Enable Rx DMA Request */
SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN);
error:
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return errorcode;
}
/**
* @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
* @note When the CRC feature is enabled the pRxData Length must be Size + 1
* @param Size amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData,
uint16_t Size)
{
uint32_t tmp_mode;
HAL_SPI_StateTypeDef tmp_state;
HAL_StatusTypeDef errorcode = HAL_OK;
/* Check rx & tx dma handles */
assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx));
assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx));
/* Check Direction parameter */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process locked */
__HAL_LOCK(hspi);
/* Init temporary variables */
tmp_state = hspi->State;
tmp_mode = hspi->Init.Mode;
if (!((tmp_state == HAL_SPI_STATE_READY) ||
((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX))))
{
errorcode = HAL_BUSY;
goto error;
}
if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U))
{
errorcode = HAL_ERROR;
goto error;
}
/* 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;
#if (USE_SPI_CRC != 0U)
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
#endif /* USE_SPI_CRC */
/* Reset the threshold bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX | SPI_CR2_LDMARX);
/* The packing mode management is enabled by the DMA settings according the spi data size */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
/* Set fiforxthreshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set RX Fifo threshold according the reception data length: 8bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
if (hspi->hdmatx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD)
{
if ((hspi->TxXferSize & 0x1U) == 0x0U)
{
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX);
hspi->TxXferCount = hspi->TxXferCount >> 1U;
}
else
{
SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX);
hspi->TxXferCount = (hspi->TxXferCount >> 1U) + 1U;
}
}
if (hspi->hdmarx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD)
{
/* Set RX Fifo threshold according the reception data length: 16bit */
CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
if ((hspi->RxXferCount & 0x1U) == 0x0U)
{
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX);
hspi->RxXferCount = hspi->RxXferCount >> 1U;
}
else
{
SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX);
hspi->RxXferCount = (hspi->RxXferCount >> 1U) + 1U;
}
}
}
/* 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 AbortCpltCallback */
hspi->hdmarx->XferAbortCallback = NULL;
/* Enable the Rx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr,
hspi->RxXferCount))
{
/* Update SPI error code */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
hspi->State = HAL_SPI_STATE_READY;
goto error;
}
/* Enable Rx DMA Request */
SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN);
/* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing
is performed in DMA reception complete callback */
hspi->hdmatx->XferHalfCpltCallback = NULL;
hspi->hdmatx->XferCpltCallback = NULL;
hspi->hdmatx->XferErrorCallback = NULL;
hspi->hdmatx->XferAbortCallback = NULL;
/* Enable the Tx DMA Stream/Channel */
if (HAL_OK != HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR,
hspi->TxXferCount))
{
/* Update SPI error code */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
hspi->State = HAL_SPI_STATE_READY;
goto error;
}
/* Check if the SPI is already enabled */
if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Enable the SPI Error Interrupt Bit */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR));
/* Enable Tx DMA Request */
SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN);
error :
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return errorcode;
}
/**
* @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.
* 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;
__IO uint32_t resetcount;
/* Initialized local variable */
errorcode = HAL_OK;
resetcount = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U);
count = resetcount;
/* Clear ERRIE interrupt to avoid error interrupts generation during Abort procedure */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE);
/* Disable TXEIE, RXNEIE and ERRIE(mode fault event, overrun error, TI frame error) interrupts */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXEIE))
{
hspi->TxISR = SPI_AbortTx_ISR;
/* Wait HAL_SPI_STATE_ABORT state */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (hspi->State != HAL_SPI_STATE_ABORT);
/* Reset Timeout Counter */
count = resetcount;
}
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE))
{
hspi->RxISR = SPI_AbortRx_ISR;
/* Wait HAL_SPI_STATE_ABORT state */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (hspi->State != HAL_SPI_STATE_ABORT);
/* Reset Timeout Counter */
count = resetcount;
}
/* Disable the SPI DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN))
{
/* Abort the SPI DMA Tx Stream/Channel : use blocking DMA Abort API (no callback) */
if (hspi->hdmatx != NULL)
{
/* Set the SPI DMA Abort callback :
will lead to call HAL_SPI_AbortCpltCallback() at end of DMA abort procedure */
hspi->hdmatx->XferAbortCallback = NULL;
/* Abort DMA Tx Handle linked to SPI Peripheral */
if (HAL_DMA_Abort(hspi->hdmatx) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable Tx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXDMAEN));
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable SPI Peripheral */
__HAL_SPI_DISABLE(hspi);
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
}
}
/* Disable the SPI DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN))
{
/* Abort the SPI DMA Rx Stream/Channel : use blocking DMA Abort API (no callback) */
if (hspi->hdmarx != NULL)
{
/* Set the SPI DMA Abort callback :
will lead to call HAL_SPI_AbortCpltCallback() at end of DMA abort procedure */
hspi->hdmarx->XferAbortCallback = NULL;
/* Abort DMA Rx Handle linked to SPI Peripheral */
if (HAL_DMA_Abort(hspi->hdmarx) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable peripheral */
__HAL_SPI_DISABLE(hspi);
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable Rx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_RXDMAEN));
}
}
/* Reset Tx and Rx transfer counters */
hspi->RxXferCount = 0U;
hspi->TxXferCount = 0U;
/* 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;
}
/* Clear the Error flags in the SR register */
__HAL_SPI_CLEAR_OVRFLAG(hspi);
__HAL_SPI_CLEAR_FREFLAG(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.
* 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;
uint32_t abortcplt ;
__IO uint32_t count;
__IO uint32_t resetcount;
/* Initialized local variable */
errorcode = HAL_OK;
abortcplt = 1U;
resetcount = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U);
count = resetcount;
/* Clear ERRIE interrupt to avoid error interrupts generation during Abort procedure */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE);
/* Change Rx and Tx Irq Handler to Disable TXEIE, RXNEIE and ERRIE interrupts */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXEIE))
{
hspi->TxISR = SPI_AbortTx_ISR;
/* Wait HAL_SPI_STATE_ABORT state */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (hspi->State != HAL_SPI_STATE_ABORT);
/* Reset Timeout Counter */
count = resetcount;
}
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE))
{
hspi->RxISR = SPI_AbortRx_ISR;
/* Wait HAL_SPI_STATE_ABORT state */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (hspi->State != HAL_SPI_STATE_ABORT);
/* Reset Timeout Counter */
count = resetcount;
}
/* If DMA Tx and/or DMA Rx Handles are associated to SPI Handle, DMA Abort complete callbacks should be initialised
before any call to DMA Abort functions */
/* DMA Tx Handle is valid */
if (hspi->hdmatx != NULL)
{
/* Set DMA Abort Complete callback if UART DMA Tx request if enabled.
Otherwise, set it to NULL */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN))
{
hspi->hdmatx->XferAbortCallback = SPI_DMATxAbortCallback;
}
else
{
hspi->hdmatx->XferAbortCallback = NULL;
}
}
/* DMA Rx Handle is valid */
if (hspi->hdmarx != NULL)
{
/* Set DMA Abort Complete callback if UART DMA Rx request if enabled.
Otherwise, set it to NULL */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN))
{
hspi->hdmarx->XferAbortCallback = SPI_DMARxAbortCallback;
}
else
{
hspi->hdmarx->XferAbortCallback = NULL;
}
}
/* Disable the SPI DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN))
{
/* Abort the SPI DMA Tx Stream/Channel */
if (hspi->hdmatx != NULL)
{
/* Abort DMA Tx Handle linked to SPI Peripheral */
if (HAL_DMA_Abort_IT(hspi->hdmatx) != HAL_OK)
{
hspi->hdmatx->XferAbortCallback = NULL;
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
else
{
abortcplt = 0U;
}
}
}
/* Disable the SPI DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN))
{
/* Abort the SPI DMA Rx Stream/Channel */
if (hspi->hdmarx != NULL)
{
/* Abort DMA Rx Handle linked to SPI Peripheral */
if (HAL_DMA_Abort_IT(hspi->hdmarx) != HAL_OK)
{
hspi->hdmarx->XferAbortCallback = NULL;
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
else
{
abortcplt = 0U;
}
}
}
if (abortcplt == 1U)
{
/* Reset Tx and Rx transfer counters */
hspi->RxXferCount = 0U;
hspi->TxXferCount = 0U;
/* 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;
}
/* Clear the Error flags in the SR register */
__HAL_SPI_CLEAR_OVRFLAG(hspi);
__HAL_SPI_CLEAR_FREFLAG(hspi);
/* Restore hspi->State to Ready */
hspi->State = HAL_SPI_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->AbortCpltCallback(hspi);
#else
HAL_SPI_AbortCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
return errorcode;
}
/**
* @brief Pause the DMA Transfer.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi)
{
/* Process Locked */
__HAL_LOCK(hspi);
/* Disable the SPI DMA Tx & Rx requests */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
/**
* @brief Resume the DMA Transfer.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi)
{
/* Process Locked */
__HAL_LOCK(hspi);
/* Enable the SPI DMA Tx & Rx requests */
SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
/**
* @brief Stop the DMA Transfer.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi)
{
HAL_StatusTypeDef errorcode = HAL_OK;
/* The Lock is not implemented on this API to allow the user application
to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback():
when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback()
*/
/* Abort the SPI DMA tx Stream/Channel */
if (hspi->hdmatx != NULL)
{
if (HAL_OK != HAL_DMA_Abort(hspi->hdmatx))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
}
}
/* Abort the SPI DMA rx Stream/Channel */
if (hspi->hdmarx != NULL)
{
if (HAL_OK != HAL_DMA_Abort(hspi->hdmarx))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
errorcode = HAL_ERROR;
}
}
/* Disable the SPI DMA Tx & Rx requests */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
hspi->State = HAL_SPI_STATE_READY;
return errorcode;
}
/**
* @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->CR2;
uint32_t itflag = hspi->Instance->SR;
/* SPI in mode Receiver ----------------------------------------------------*/
if ((SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) == RESET) &&
(SPI_CHECK_FLAG(itflag, SPI_FLAG_RXNE) != RESET) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_RXNE) != RESET))
{
hspi->RxISR(hspi);
return;
}
/* SPI in mode Transmitter -------------------------------------------------*/
if ((SPI_CHECK_FLAG(itflag, SPI_FLAG_TXE) != RESET) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_TXE) != RESET))
{
hspi->TxISR(hspi);
return;
}
/* SPI in Error Treatment --------------------------------------------------*/
if (((SPI_CHECK_FLAG(itflag, SPI_FLAG_MODF) != RESET) || (SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) != RESET)
|| (SPI_CHECK_FLAG(itflag, SPI_FLAG_FRE) != RESET)) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_ERR) != RESET))
{
/* SPI Overrun error interrupt occurred ----------------------------------*/
if (SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) != RESET)
{
if (hspi->State != HAL_SPI_STATE_BUSY_TX)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR);
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
else
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
return;
}
}
/* SPI Mode Fault error interrupt occurred -------------------------------*/
if (SPI_CHECK_FLAG(itflag, SPI_FLAG_MODF) != RESET)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF);
__HAL_SPI_CLEAR_MODFFLAG(hspi);
}
/* SPI Frame error interrupt occurred ------------------------------------*/
if (SPI_CHECK_FLAG(itflag, SPI_FLAG_FRE) != RESET)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FRE);
__HAL_SPI_CLEAR_FREFLAG(hspi);
}
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
/* Disable all interrupts */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE | SPI_IT_TXE | SPI_IT_ERR);
hspi->State = HAL_SPI_STATE_READY;
/* Disable the SPI DMA requests if enabled */
if ((HAL_IS_BIT_SET(itsource, SPI_CR2_TXDMAEN)) || (HAL_IS_BIT_SET(itsource, SPI_CR2_RXDMAEN)))
{
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXDMAEN | SPI_CR2_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
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
uint32_t tickstart;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* DMA Normal Mode */
if ((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC)
{
/* Disable ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR);
/* Disable Tx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN);
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
}
/* Clear overrun flag in 2 Lines communication mode because received data is not read */
if (hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
hspi->TxXferCount = 0U;
hspi->State = HAL_SPI_STATE_READY;
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
return;
}
}
/* Call user Tx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->TxCpltCallback(hspi);
#else
HAL_SPI_TxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
/**
* @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); /* Derogation MISRAC2012-Rule-11.5 */
uint32_t tickstart;
#if (USE_SPI_CRC != 0U)
__IO uint32_t tmpreg = 0U;
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
#endif /* USE_SPI_CRC */
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* DMA Normal Mode */
if ((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC)
{
/* Disable ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR);
#if (USE_SPI_CRC != 0U)
/* CRC handling */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Wait until RXNE flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
}
/* Read CRC */
if (hspi->Init.DataSize > SPI_DATASIZE_8BIT)
{
/* Read 16bit CRC */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
}
else
{
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
if (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)
{
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
}
/* Read 8bit CRC again in case of 16bit CRC in 8bit Data mode */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
}
}
}
#endif /* USE_SPI_CRC */
/* Check if we are in Master RX 2 line mode */
if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
{
/* Disable Rx/Tx DMA Request (done by default to handle the case master rx direction 2 lines) */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
}
else
{
/* Normal case */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN);
}
/* Check the end of the transaction */
if (SPI_EndRxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_FLAG;
}
hspi->RxXferCount = 0U;
hspi->State = HAL_SPI_STATE_READY;
#if (USE_SPI_CRC != 0U)
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
#endif /* USE_SPI_CRC */
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
return;
}
}
/* Call user Rx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->RxCpltCallback(hspi);
#else
HAL_SPI_RxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
/**
* @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); /* Derogation MISRAC2012-Rule-11.5 */
uint32_t tickstart;
#if (USE_SPI_CRC != 0U)
__IO uint32_t tmpreg = 0U;
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
#endif /* USE_SPI_CRC */
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* DMA Normal Mode */
if ((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC)
{
/* Disable ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR);
#if (USE_SPI_CRC != 0U)
/* CRC handling */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
if ((hspi->Init.DataSize == SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_8BIT))
{
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_QUARTER_FULL, SPI_DEFAULT_TIMEOUT,
tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
}
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
}
else
{
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_HALF_FULL, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
/* Error on the CRC reception */
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
}
/* Read CRC to Flush DR and RXNE flag */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
}
}
#endif /* USE_SPI_CRC */
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
}
/* Disable Rx/Tx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
hspi->TxXferCount = 0U;
hspi->RxXferCount = 0U;
hspi->State = HAL_SPI_STATE_READY;
#if (USE_SPI_CRC != 0U)
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR))
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
#endif /* USE_SPI_CRC */
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
return;
}
}
/* Call user TxRx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->TxRxCpltCallback(hspi);
#else
HAL_SPI_TxRxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
/**
* @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); /* Derogation MISRAC2012-Rule-11.5 */
/* Call user Tx half complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
/* Call user Rx half complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
/* Call user TxRx half complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
/* Stop the disable DMA transfer on SPI side */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN);
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA);
hspi->State = HAL_SPI_STATE_READY;
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
hspi->RxXferCount = 0U;
hspi->TxXferCount = 0U;
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
hspi->hdmatx->XferAbortCallback = NULL;
/* Disable Tx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN);
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable SPI Peripheral */
__HAL_SPI_DISABLE(hspi);
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Check if an Abort process is still ongoing */
if (hspi->hdmarx != NULL)
{
if (hspi->hdmarx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA Stream/Channel are aborted, call user Abort Complete callback */
hspi->RxXferCount = 0U;
hspi->TxXferCount = 0U;
/* Check no error during Abort procedure */
if (hspi->ErrorCode != HAL_SPI_ERROR_ABORT)
{
/* Reset errorCode */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
}
/* Clear the Error flags in the SR register */
__HAL_SPI_CLEAR_OVRFLAG(hspi);
__HAL_SPI_CLEAR_FREFLAG(hspi);
/* Restore hspi->State to Ready */
hspi->State = HAL_SPI_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
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); /* Derogation MISRAC2012-Rule-11.5 */
/* Disable SPI Peripheral */
__HAL_SPI_DISABLE(hspi);
hspi->hdmarx->XferAbortCallback = NULL;
/* Disable Rx DMA Request */
CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN);
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Check if an Abort process is still ongoing */
if (hspi->hdmatx != NULL)
{
if (hspi->hdmatx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA Stream/Channel are aborted, call user Abort Complete callback */
hspi->RxXferCount = 0U;
hspi->TxXferCount = 0U;
/* Check no error during Abort procedure */
if (hspi->ErrorCode != HAL_SPI_ERROR_ABORT)
{
/* Reset errorCode */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
}
/* Clear the Error flags in the SR register */
__HAL_SPI_CLEAR_OVRFLAG(hspi);
__HAL_SPI_CLEAR_FREFLAG(hspi);
/* Restore hspi->State to Ready */
hspi->State = HAL_SPI_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->AbortCpltCallback(hspi);
#else
HAL_SPI_AbortCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
/**
* @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi)
{
/* Receive data in packing mode */
if (hspi->RxXferCount > 1U)
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)(hspi->Instance->DR);
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount -= 2U;
if (hspi->RxXferCount == 1U)
{
/* Set RX Fifo threshold according the reception data length: 8bit */
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
}
}
/* Receive data in 8 Bit mode */
else
{
*hspi->pRxBuffPtr = *((__IO uint8_t *)&hspi->Instance->DR);
hspi->pRxBuffPtr++;
hspi->RxXferCount--;
}
/* Check end of the reception */
if (hspi->RxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD);
hspi->RxISR = SPI_2linesRxISR_8BITCRC;
return;
}
#endif /* USE_SPI_CRC */
/* Disable RXNE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
if (hspi->TxXferCount == 0U)
{
SPI_CloseRxTx_ISR(hspi);
}
}
}
#if (USE_SPI_CRC != 0U)
/**
* @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi)
{
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC to flush Data Register */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
hspi->CRCSize--;
/* Check end of the reception */
if (hspi->CRCSize == 0U)
{
/* Disable RXNE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
if (hspi->TxXferCount == 0U)
{
SPI_CloseRxTx_ISR(hspi);
}
}
}
#endif /* USE_SPI_CRC */
/**
* @brief Tx 8-bit handler for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi)
{
/* Transmit data in packing Bit mode */
if (hspi->TxXferCount >= 2U)
{
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount -= 2U;
}
/* Transmit data in 8 Bit mode */
else
{
*(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr++;
hspi->TxXferCount--;
}
/* Check the end of the transmission */
if (hspi->TxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Set CRC Next Bit to send CRC */
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
/* Disable TXE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE);
return;
}
#endif /* USE_SPI_CRC */
/* Disable TXE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE);
if (hspi->RxXferCount == 0U)
{
SPI_CloseRxTx_ISR(hspi);
}
}
}
/**
* @brief Rx 16-bit handler for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi)
{
/* Receive data in 16 Bit mode */
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)(hspi->Instance->DR);
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount--;
if (hspi->RxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->RxISR = SPI_2linesRxISR_16BITCRC;
return;
}
#endif /* USE_SPI_CRC */
/* Disable RXNE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE);
if (hspi->TxXferCount == 0U)
{
SPI_CloseRxTx_ISR(hspi);
}
}
}
#if (USE_SPI_CRC != 0U)
/**
* @brief Manage the CRC 16-bit receive for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi)
{
__IO uint32_t tmpreg = 0U;
/* Read 16bit CRC to flush Data Register */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
/* Disable RXNE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE);
SPI_CloseRxTx_ISR(hspi);
}
#endif /* USE_SPI_CRC */
/**
* @brief Tx 16-bit handler for Transmit and Receive in Interrupt mode.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi)
{
/* Transmit data in 16 Bit mode */
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
/* Enable CRC Transmission */
if (hspi->TxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Set CRC Next Bit to send CRC */
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
/* Disable TXE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE);
return;
}
#endif /* USE_SPI_CRC */
/* Disable TXE interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE);
if (hspi->RxXferCount == 0U)
{
SPI_CloseRxTx_ISR(hspi);
}
}
}
#if (USE_SPI_CRC != 0U)
/**
* @brief Manage the CRC 8-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_8BITCRC(struct __SPI_HandleTypeDef *hspi)
{
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Read 8bit CRC to flush Data Register */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
hspi->CRCSize--;
if (hspi->CRCSize == 0U)
{
SPI_CloseRx_ISR(hspi);
}
}
#endif /* USE_SPI_CRC */
/**
* @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(struct __SPI_HandleTypeDef *hspi)
{
*hspi->pRxBuffPtr = (*(__IO uint8_t *)&hspi->Instance->DR);
hspi->pRxBuffPtr++;
hspi->RxXferCount--;
#if (USE_SPI_CRC != 0U)
/* Enable CRC Transmission */
if ((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
if (hspi->RxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->RxISR = SPI_RxISR_8BITCRC;
return;
}
#endif /* USE_SPI_CRC */
SPI_CloseRx_ISR(hspi);
}
}
#if (USE_SPI_CRC != 0U)
/**
* @brief Manage the CRC 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_16BITCRC(struct __SPI_HandleTypeDef *hspi)
{
__IO uint32_t tmpreg = 0U;
/* Read 16bit CRC to flush Data Register */
tmpreg = READ_REG(hspi->Instance->DR);
/* To avoid GCC warning */
UNUSED(tmpreg);
/* Disable RXNE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
SPI_CloseRx_ISR(hspi);
}
#endif /* USE_SPI_CRC */
/**
* @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(struct __SPI_HandleTypeDef *hspi)
{
*((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)(hspi->Instance->DR);
hspi->pRxBuffPtr += sizeof(uint16_t);
hspi->RxXferCount--;
#if (USE_SPI_CRC != 0U)
/* Enable CRC Transmission */
if ((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
if (hspi->RxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->RxISR = SPI_RxISR_16BITCRC;
return;
}
#endif /* USE_SPI_CRC */
SPI_CloseRx_ISR(hspi);
}
}
/**
* @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(struct __SPI_HandleTypeDef *hspi)
{
*(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr);
hspi->pTxBuffPtr++;
hspi->TxXferCount--;
if (hspi->TxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Enable CRC Transmission */
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
SPI_CloseTx_ISR(hspi);
}
}
/**
* @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(struct __SPI_HandleTypeDef *hspi)
{
/* Transmit data in 16 Bit mode */
hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr);
hspi->pTxBuffPtr += sizeof(uint16_t);
hspi->TxXferCount--;
if (hspi->TxXferCount == 0U)
{
#if (USE_SPI_CRC != 0U)
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Enable CRC Transmission */
SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT);
}
#endif /* USE_SPI_CRC */
SPI_CloseTx_ISR(hspi);
}
}
/**
* @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 State flag state to check
* @param Timeout Timeout duration
* @param Tickstart tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus State,
uint32_t Timeout, uint32_t Tickstart)
{
__IO uint32_t count;
uint32_t tmp_timeout;
uint32_t tmp_tickstart;
/* Adjust Timeout value in case of end of transfer */
tmp_timeout = Timeout - (HAL_GetTick() - Tickstart);
tmp_tickstart = HAL_GetTick();
/* Calculate Timeout based on a software loop to avoid blocking issue if Systick is disabled */
count = tmp_timeout * ((SystemCoreClock * 32U) >> 20U);
while ((__HAL_SPI_GET_FLAG(hspi, Flag) ? SET : RESET) != State)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tmp_tickstart) >= tmp_timeout) || (tmp_timeout == 0U))
{
/* Disable the SPI and reset the CRC: the CRC value should be cleared
on both master and slave sides in order to resynchronize the master
and slave for their respective CRC calculation */
/* Disable TXE, RXNE and ERR interrupts for the interrupt process */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE)
|| (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_TIMEOUT;
}
/* If Systick is disabled or not incremented, deactivate timeout to go in disable loop procedure */
if (count == 0U)
{
tmp_timeout = 0U;
}
count--;
}
}
return HAL_OK;
}
/**
* @brief Handle SPI FIFO Communication Timeout.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param Fifo Fifo to check
* @param State Fifo state to check
* @param Timeout Timeout duration
* @param Tickstart tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Fifo, uint32_t State,
uint32_t Timeout, uint32_t Tickstart)
{
__IO uint32_t count;
uint32_t tmp_timeout;
uint32_t tmp_tickstart;
__IO uint8_t *ptmpreg8;
__IO uint8_t tmpreg8 = 0;
/* Adjust Timeout value in case of end of transfer */
tmp_timeout = Timeout - (HAL_GetTick() - Tickstart);
tmp_tickstart = HAL_GetTick();
/* Initialize the 8bit temporary pointer */
ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DR;
/* Calculate Timeout based on a software loop to avoid blocking issue if Systick is disabled */
count = tmp_timeout * ((SystemCoreClock * 35U) >> 20U);
while ((hspi->Instance->SR & Fifo) != State)
{
if ((Fifo == SPI_SR_FRLVL) && (State == SPI_FRLVL_EMPTY))
{
/* Flush Data Register by a blank read */
tmpreg8 = *ptmpreg8;
/* To avoid GCC warning */
UNUSED(tmpreg8);
}
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tmp_tickstart) >= tmp_timeout) || (tmp_timeout == 0U))
{
/* Disable the SPI and reset the CRC: the CRC value should be cleared
on both master and slave sides in order to resynchronize the master
and slave for their respective CRC calculation */
/* Disable TXE, RXNE and ERR interrupts for the interrupt process */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE)
|| (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
/* Reset CRC Calculation */
if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_TIMEOUT;
}
/* If Systick is disabled or not incremented, deactivate timeout to go in disable loop procedure */
if (count == 0U)
{
tmp_timeout = 0U;
}
count--;
}
}
return HAL_OK;
}
/**
* @brief Handle the check of the RX transaction complete.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param Timeout Timeout duration
* @param Tickstart tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart)
{
if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE)
|| (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
return HAL_TIMEOUT;
}
if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE)
|| (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, Timeout, Tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @brief Handle the check of the RXTX or TX transaction complete.
* @param hspi SPI handle
* @param Timeout Timeout duration
* @param Tickstart tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart)
{
/* Control if the TX fifo is empty */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FTLVL, SPI_FTLVL_EMPTY, Timeout, Tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
return HAL_TIMEOUT;
}
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
return HAL_TIMEOUT;
}
/* Control if the RX fifo is empty */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, Timeout, Tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
return HAL_TIMEOUT;
}
return HAL_OK;
}
/**
* @brief Handle the end of the RXTX transaction.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi)
{
uint32_t tickstart;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
/* Disable ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR);
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
}
#if (USE_SPI_CRC != 0U)
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
hspi->State = HAL_SPI_STATE_READY;
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
else
{
#endif /* USE_SPI_CRC */
if (hspi->ErrorCode == HAL_SPI_ERROR_NONE)
{
if (hspi->State == HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_READY;
/* Call user Rx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->RxCpltCallback(hspi);
#else
HAL_SPI_RxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
else
{
hspi->State = HAL_SPI_STATE_READY;
/* Call user TxRx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->TxRxCpltCallback(hspi);
#else
HAL_SPI_TxRxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
}
else
{
hspi->State = HAL_SPI_STATE_READY;
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
#if (USE_SPI_CRC != 0U)
}
#endif /* USE_SPI_CRC */
}
/**
* @brief Handle the end of the RX transaction.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi)
{
/* Disable RXNE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
/* Check the end of the transaction */
if (SPI_EndRxTransaction(hspi, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
}
hspi->State = HAL_SPI_STATE_READY;
#if (USE_SPI_CRC != 0U)
/* Check if CRC error occurred */
if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC);
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
else
{
#endif /* USE_SPI_CRC */
if (hspi->ErrorCode == HAL_SPI_ERROR_NONE)
{
/* Call user Rx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->RxCpltCallback(hspi);
#else
HAL_SPI_RxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
else
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
#if (USE_SPI_CRC != 0U)
}
#endif /* USE_SPI_CRC */
}
/**
* @brief Handle the end of the TX transaction.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi)
{
uint32_t tickstart;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* Disable TXE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR));
/* Check the end of the transaction */
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG);
}
/* Clear overrun flag in 2 Lines communication mode because received is not read */
if (hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
hspi->State = HAL_SPI_STATE_READY;
if (hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
/* Call user error callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->ErrorCallback(hspi);
#else
HAL_SPI_ErrorCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
else
{
/* Call user Rx complete callback */
#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U)
hspi->TxCpltCallback(hspi);
#else
HAL_SPI_TxCpltCallback(hspi);
#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */
}
}
/**
* @brief Handle abort a Rx transaction.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi)
{
__IO uint32_t count;
/* Disable SPI Peripheral */
__HAL_SPI_DISABLE(hspi);
count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U);
/* Disable RXNEIE interrupt */
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_RXNEIE));
/* Check RXNEIE is disabled */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE));
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
hspi->State = HAL_SPI_STATE_ABORT;
}
/**
* @brief Handle abort a Tx or Rx/Tx transaction.
* @param hspi pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi)
{
__IO uint32_t count;
count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U);
/* Disable TXEIE interrupt */
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXEIE));
/* Check TXEIE is disabled */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXEIE));
if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Disable SPI Peripheral */
__HAL_SPI_DISABLE(hspi);
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Check case of Full-Duplex Mode and disable directly RXNEIE interrupt */
if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE))
{
/* Disable RXNEIE interrupt */
CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_RXNEIE));
/* Check RXNEIE is disabled */
do
{
if (count == 0U)
{
SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT);
break;
}
count--;
} while (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE));
/* Control the BSY flag */
if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
/* Empty the FRLVL fifo */
if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, SPI_DEFAULT_TIMEOUT, HAL_GetTick()) != HAL_OK)
{
hspi->ErrorCode = HAL_SPI_ERROR_ABORT;
}
}
hspi->State = HAL_SPI_STATE_ABORT;
}
/**
* @}
*/
#endif /* HAL_SPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 141,002 |
C
| 30.778905 | 133 | 0.60236 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_comp.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_comp.c
* @author MCD Application Team
* @brief COMP HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the COMP peripheral:
* + Initialization and de-initialization functions
* + Peripheral control functions
* + Peripheral state functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
================================================================================
##### COMP Peripheral features #####
================================================================================
[..]
The STM32G4xx device family integrates seven analog comparators instances:
COMP1, COMP2, COMP3, COMP4, COMP5, COMP6 and COMP7.
(#) Comparators input minus (inverting input) and input plus (non inverting input)
can be set to internal references or to GPIO pins
(refer to GPIO list in reference manual).
(#) Comparators output level is available using HAL_COMP_GetOutputLevel()
and can be redirected to other peripherals: GPIO pins (in mode
alternate functions for comparator), timers.
(refer to GPIO list in reference manual).
(#) The comparators have interrupt capability through the EXTI controller
with wake-up from sleep and stop modes.
From the corresponding IRQ handler, the right interrupt source can be retrieved
using macro __HAL_COMP_COMPx_EXTI_GET_FLAG().
##### How to use this driver #####
================================================================================
[..]
This driver provides functions to configure and program the comparator instances
of STM32G4xx devices.
To use the comparator, perform the following steps:
(#) Initialize the COMP low level resources by implementing the HAL_COMP_MspInit():
(++) Configure the GPIO connected to comparator inputs plus and minus in analog mode
using HAL_GPIO_Init().
(++) If needed, configure the GPIO connected to comparator output in alternate function mode
using HAL_GPIO_Init().
(++) If required enable the COMP interrupt by configuring and enabling EXTI line in Interrupt mode and
selecting the desired sensitivity level using HAL_GPIO_Init() function. After that enable the comparator
interrupt vector using HAL_NVIC_EnableIRQ() function.
(#) Configure the comparator using HAL_COMP_Init() function:
(++) Select the input minus (inverting input)
(++) Select the input plus (non-inverting input)
(++) Select the hysteresis
(++) Select the blanking source
(++) Select the output polarity
-@@- HAL_COMP_Init() calls internally __HAL_RCC_SYSCFG_CLK_ENABLE()
to enable internal control clock of the comparators.
However, this is a legacy strategy. In future STM32 families,
COMP clock enable must be implemented by user in "HAL_COMP_MspInit()".
Therefore, for compatibility anticipation, it is recommended to
implement __HAL_RCC_SYSCFG_CLK_ENABLE() in "HAL_COMP_MspInit()".
(#) Reconfiguration on-the-fly of comparator can be done by calling again
function HAL_COMP_Init() with new input structure parameters values.
(#) Enable the comparator using HAL_COMP_Start() function.
(#) Use HAL_COMP_TriggerCallback() or HAL_COMP_GetOutputLevel() functions
to manage comparator outputs (events and output level).
(#) Disable the comparator using HAL_COMP_Stop() function.
(#) De-initialize the comparator using HAL_COMP_DeInit() function.
(#) For safety purpose, comparator configuration can be locked using HAL_COMP_Lock() function.
The only way to unlock the comparator is a device hardware reset.
*** Callback registration ***
=============================================
[..]
The compilation flag USE_HAL_COMP_REGISTER_CALLBACKS, when set to 1,
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_COMP_RegisterCallback()
to register an interrupt callback.
[..]
Function HAL_COMP_RegisterCallback() allows to register following callbacks:
(+) TriggerCallback : callback for COMP trigger.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_COMP_UnRegisterCallback to reset a callback to the default
weak function.
[..]
HAL_COMP_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) TriggerCallback : callback for COMP trigger.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
[..]
By default, after the HAL_COMP_Init() and when the state is HAL_COMP_STATE_RESET
all callbacks are set to the corresponding weak functions:
example HAL_COMP_TriggerCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the HAL_COMP_Init()/ HAL_COMP_DeInit() only when
these callbacks are null (not registered beforehand).
[..]
If MspInit or MspDeInit are not null, the HAL_COMP_Init()/ HAL_COMP_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in HAL_COMP_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in HAL_COMP_STATE_READY or HAL_COMP_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_COMP_RegisterCallback() before calling HAL_COMP_DeInit()
or HAL_COMP_Init() function.
[..]
When the compilation flag USE_HAL_COMP_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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_COMP_MODULE_ENABLED
/** @defgroup COMP COMP
* @brief COMP HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup COMP_Private_Constants
* @{
*/
/* Delay for COMP startup time. */
/* Note: Delay required to reach propagation delay specification. */
/* Literal set to maximum value (refer to device datasheet, */
/* parameter "tSTART"). */
/* Unit: us */
#define COMP_DELAY_STARTUP_US (5UL) /*!< Delay for COMP startup time */
/* Delay for COMP voltage scaler stabilization time. */
/* Literal set to maximum value (refer to device datasheet, */
/* parameter "tSTART_SCALER"). */
/* Unit: us */
#define COMP_DELAY_VOLTAGE_SCALER_STAB_US (200UL) /*!< Delay for COMP voltage scaler stabilization time */
#define COMP_OUTPUT_LEVEL_BITOFFSET_POS (30UL)
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup COMP_Exported_Functions COMP Exported Functions
* @{
*/
/** @defgroup COMP_Exported_Functions_Group1 Initialization/de-initialization functions
* @brief Initialization and de-initialization functions.
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions to initialize and de-initialize comparators
@endverbatim
* @{
*/
/**
* @brief Initialize the COMP according to the specified
* parameters in the COMP_InitTypeDef and initialize the associated handle.
* @note If the selected comparator is locked, initialization can't be performed.
* To unlock the configuration, perform a system reset.
* @param hcomp COMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp)
{
uint32_t tmp_csr;
uint32_t exti_line;
uint32_t comp_voltage_scaler_initialized; /* Value "0" if comparator voltage scaler is not initialized */
__IO uint32_t wait_loop_index = 0UL;
HAL_StatusTypeDef status = HAL_OK;
/* Check the COMP handle allocation and lock status */
if(hcomp == NULL)
{
status = HAL_ERROR;
}
else if(__HAL_COMP_IS_LOCKED(hcomp))
{
status = HAL_ERROR;
}
else
{
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
assert_param(IS_COMP_INPUT_PLUS(hcomp->Instance, hcomp->Init.InputPlus));
assert_param(IS_COMP_INPUT_MINUS(hcomp->Instance, hcomp->Init.InputMinus));
assert_param(IS_COMP_OUTPUTPOL(hcomp->Init.OutputPol));
assert_param(IS_COMP_HYSTERESIS(hcomp->Init.Hysteresis));
assert_param(IS_COMP_BLANKINGSRC_INSTANCE(hcomp->Instance, hcomp->Init.BlankingSrce));
assert_param(IS_COMP_TRIGGERMODE(hcomp->Init.TriggerMode));
if(hcomp->State == HAL_COMP_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcomp->Lock = HAL_UNLOCKED;
/* Set COMP error code to none */
COMP_CLEAR_ERRORCODE(hcomp);
#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
/* Init the COMP Callback settings */
hcomp->TriggerCallback = HAL_COMP_TriggerCallback; /* Legacy weak callback */
if (hcomp->MspInitCallback == NULL)
{
hcomp->MspInitCallback = HAL_COMP_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware */
/* Note: Internal control clock of the comparators must */
/* be enabled in "HAL_COMP_MspInit()" */
/* using "__HAL_RCC_SYSCFG_CLK_ENABLE()". */
hcomp->MspInitCallback(hcomp);
#else
/* Init the low level hardware */
/* Note: Internal control clock of the comparators must */
/* be enabled in "HAL_COMP_MspInit()" */
/* using "__HAL_RCC_SYSCFG_CLK_ENABLE()". */
HAL_COMP_MspInit(hcomp);
#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
}
/* Memorize voltage scaler state before initialization */
comp_voltage_scaler_initialized = READ_BIT(hcomp->Instance->CSR, COMP_CSR_SCALEN);
/* Set COMP parameters */
tmp_csr = ( hcomp->Init.InputMinus
| hcomp->Init.InputPlus
| hcomp->Init.BlankingSrce
| hcomp->Init.Hysteresis
| hcomp->Init.OutputPol
);
/* Set parameters in COMP register */
/* Note: Update all bits except read-only, lock and enable bits */
MODIFY_REG(hcomp->Instance->CSR,
COMP_CSR_INMSEL | COMP_CSR_INPSEL |
COMP_CSR_POLARITY | COMP_CSR_HYST |
COMP_CSR_BLANKING | COMP_CSR_BRGEN | COMP_CSR_SCALEN,
tmp_csr
);
/* Delay for COMP scaler bridge voltage stabilization */
/* Apply the delay if voltage scaler bridge is required and not already enabled */
if ((READ_BIT(hcomp->Instance->CSR, COMP_CSR_SCALEN) != 0UL) &&
(comp_voltage_scaler_initialized == 0UL) )
{
/* Wait loop initialization and execution */
/* Note: Variable divided by 2 to compensate partially */
/* CPU processing cycles, scaling in us split to not */
/* exceed 32 bits register capacity and handle low frequency. */
wait_loop_index = ((COMP_DELAY_VOLTAGE_SCALER_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
while(wait_loop_index != 0UL)
{
wait_loop_index--;
}
}
/* Get the EXTI line corresponding to the selected COMP instance */
exti_line = COMP_GET_EXTI_LINE(hcomp->Instance);
/* Manage EXTI settings */
if((hcomp->Init.TriggerMode & (COMP_EXTI_IT | COMP_EXTI_EVENT)) != 0UL)
{
/* Configure EXTI rising edge */
if((hcomp->Init.TriggerMode & COMP_EXTI_RISING) != 0UL)
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_EnableRisingTrig_32_63(exti_line);
}
else
{
LL_EXTI_EnableRisingTrig_0_31(exti_line);
}
#else
LL_EXTI_EnableRisingTrig_0_31(exti_line);
#endif /* COMP7 */
}
else
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableRisingTrig_32_63(exti_line);
}
else
{
LL_EXTI_DisableRisingTrig_0_31(exti_line);
}
#else
LL_EXTI_DisableRisingTrig_0_31(exti_line);
#endif /* COMP7 */
}
/* Configure EXTI falling edge */
if((hcomp->Init.TriggerMode & COMP_EXTI_FALLING) != 0UL)
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_EnableFallingTrig_32_63(exti_line);
}
else
{
LL_EXTI_EnableFallingTrig_0_31(exti_line);
}
#else
LL_EXTI_EnableFallingTrig_0_31(exti_line);
#endif /* COMP7 */
}
else
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableFallingTrig_32_63(exti_line);
}
else
{
LL_EXTI_DisableFallingTrig_0_31(exti_line);
}
#else
LL_EXTI_DisableFallingTrig_0_31(exti_line);
#endif /* COMP7 */
}
/* Clear COMP EXTI pending bit (if any) */
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_ClearFlag_32_63(exti_line);
}
else
{
LL_EXTI_ClearFlag_0_31(exti_line);
}
#else
LL_EXTI_ClearFlag_0_31(exti_line);
#endif /* COMP7 */
/* Configure EXTI event mode */
if((hcomp->Init.TriggerMode & COMP_EXTI_EVENT) != 0UL)
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_EnableEvent_32_63(exti_line);
}
else
{
LL_EXTI_EnableEvent_0_31(exti_line);
}
#else
LL_EXTI_EnableEvent_0_31(exti_line);
#endif /* COMP7 */
}
else
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableEvent_32_63(exti_line);
}
else
{
LL_EXTI_DisableEvent_0_31(exti_line);
}
#else
LL_EXTI_DisableEvent_0_31(exti_line);
#endif /* COMP7 */
}
/* Configure EXTI interrupt mode */
if((hcomp->Init.TriggerMode & COMP_EXTI_IT) != 0UL)
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_EnableIT_32_63(exti_line);
}
else
{
LL_EXTI_EnableIT_0_31(exti_line);
}
#else
LL_EXTI_EnableIT_0_31(exti_line);
#endif /* COMP7 */
}
else
{
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableIT_32_63(exti_line);
}
else
{
LL_EXTI_DisableIT_0_31(exti_line);
}
#else
LL_EXTI_DisableIT_0_31(exti_line);
#endif /* COMP7 */
}
}
else
{
/* Disable EXTI event mode */
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableEvent_32_63(exti_line);
}
else
{
LL_EXTI_DisableEvent_0_31(exti_line);
}
#else
LL_EXTI_DisableEvent_0_31(exti_line);
#endif /* COMP7 */
/* Disable EXTI interrupt mode */
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
LL_EXTI_DisableIT_32_63(exti_line);
}
else
{
LL_EXTI_DisableIT_0_31(exti_line);
}
#else
LL_EXTI_DisableIT_0_31(exti_line);
#endif /* COMP7 */
}
/* Set HAL COMP handle state */
/* Note: Transition from state reset to state ready, */
/* otherwise (coming from state ready or busy) no state update. */
if (hcomp->State == HAL_COMP_STATE_RESET)
{
hcomp->State = HAL_COMP_STATE_READY;
}
}
return status;
}
/**
* @brief DeInitialize the COMP peripheral.
* @note Deinitialization cannot be performed if the COMP configuration is locked.
* To unlock the configuration, perform a system reset.
* @param hcomp COMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_DeInit(COMP_HandleTypeDef *hcomp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the COMP handle allocation and lock status */
if(hcomp == NULL)
{
status = HAL_ERROR;
}
else if(__HAL_COMP_IS_LOCKED(hcomp))
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
/* Set COMP_CSR register to reset value */
WRITE_REG(hcomp->Instance->CSR, 0x00000000UL);
#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
if (hcomp->MspDeInitCallback == NULL)
{
hcomp->MspDeInitCallback = HAL_COMP_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: GPIO, RCC clock, NVIC */
hcomp->MspDeInitCallback(hcomp);
#else
/* DeInit the low level hardware: GPIO, RCC clock, NVIC */
HAL_COMP_MspDeInit(hcomp);
#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
/* Set HAL COMP handle state */
hcomp->State = HAL_COMP_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hcomp);
}
return status;
}
/**
* @brief Initialize the COMP MSP.
* @param hcomp COMP handle
* @retval None
*/
__weak void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcomp);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_COMP_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize the COMP MSP.
* @param hcomp COMP handle
* @retval None
*/
__weak void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcomp);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_COMP_MspDeInit could be implemented in the user file
*/
}
#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User COMP Callback
* To be used instead of the weak predefined callback
* @param hcomp Pointer to a COMP_HandleTypeDef structure that contains
* the configuration information for the specified COMP.
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_COMP_TRIGGER_CB_ID Trigger callback ID
* @arg @ref HAL_COMP_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_COMP_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_RegisterCallback(COMP_HandleTypeDef *hcomp, HAL_COMP_CallbackIDTypeDef CallbackID, pCOMP_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (HAL_COMP_STATE_READY == hcomp->State)
{
switch (CallbackID)
{
case HAL_COMP_TRIGGER_CB_ID :
hcomp->TriggerCallback = pCallback;
break;
case HAL_COMP_MSPINIT_CB_ID :
hcomp->MspInitCallback = pCallback;
break;
case HAL_COMP_MSPDEINIT_CB_ID :
hcomp->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_COMP_STATE_RESET == hcomp->State)
{
switch (CallbackID)
{
case HAL_COMP_MSPINIT_CB_ID :
hcomp->MspInitCallback = pCallback;
break;
case HAL_COMP_MSPDEINIT_CB_ID :
hcomp->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Unregister a COMP Callback
* COMP callback is redirected to the weak predefined callback
* @param hcomp Pointer to a COMP_HandleTypeDef structure that contains
* the configuration information for the specified COMP.
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_COMP_TRIGGER_CB_ID Trigger callback ID
* @arg @ref HAL_COMP_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_COMP_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_UnRegisterCallback(COMP_HandleTypeDef *hcomp, HAL_COMP_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
if (HAL_COMP_STATE_READY == hcomp->State)
{
switch (CallbackID)
{
case HAL_COMP_TRIGGER_CB_ID :
hcomp->TriggerCallback = HAL_COMP_TriggerCallback; /* Legacy weak callback */
break;
case HAL_COMP_MSPINIT_CB_ID :
hcomp->MspInitCallback = HAL_COMP_MspInit; /* Legacy weak MspInit */
break;
case HAL_COMP_MSPDEINIT_CB_ID :
hcomp->MspDeInitCallback = HAL_COMP_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_COMP_STATE_RESET == hcomp->State)
{
switch (CallbackID)
{
case HAL_COMP_MSPINIT_CB_ID :
hcomp->MspInitCallback = HAL_COMP_MspInit; /* Legacy weak MspInit */
break;
case HAL_COMP_MSPDEINIT_CB_ID :
hcomp->MspDeInitCallback = HAL_COMP_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcomp->ErrorCode |= HAL_COMP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup COMP_Exported_Functions_Group2 Start-Stop operation functions
* @brief Start-Stop operation functions.
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Start a comparator instance.
(+) Stop a comparator instance.
@endverbatim
* @{
*/
/**
* @brief Start the comparator.
* @param hcomp COMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp)
{
__IO uint32_t wait_loop_index = 0UL;
HAL_StatusTypeDef status = HAL_OK;
/* Check the COMP handle allocation and lock status */
if(hcomp == NULL)
{
status = HAL_ERROR;
}
else if(__HAL_COMP_IS_LOCKED(hcomp))
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
if(hcomp->State == HAL_COMP_STATE_READY)
{
/* Enable the selected comparator */
SET_BIT(hcomp->Instance->CSR, COMP_CSR_EN);
/* Set HAL COMP handle state */
hcomp->State = HAL_COMP_STATE_BUSY;
/* Delay for COMP startup time */
/* Wait loop initialization and execution */
/* Note: Variable divided by 2 to compensate partially */
/* CPU processing cycles. */
/* Note: In case of system low frequency (below 1Mhz), short delay */
/* of startup time (few us) is within CPU processing cycles */
/* of following instructions. */
wait_loop_index = (COMP_DELAY_STARTUP_US * (SystemCoreClock / (1000000UL * 2UL)));
while(wait_loop_index != 0UL)
{
wait_loop_index--;
}
}
else
{
status = HAL_ERROR;
}
}
return status;
}
/**
* @brief Stop the comparator.
* @param hcomp COMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the COMP handle allocation and lock status */
if(hcomp == NULL)
{
status = HAL_ERROR;
}
else if(__HAL_COMP_IS_LOCKED(hcomp))
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
/* Check compliant states: HAL_COMP_STATE_READY or HAL_COMP_STATE_BUSY */
/* (all states except HAL_COMP_STATE_RESET and except locked status. */
if(hcomp->State != HAL_COMP_STATE_RESET)
{
/* Disable the selected comparator */
CLEAR_BIT(hcomp->Instance->CSR, COMP_CSR_EN);
/* Set HAL COMP handle state */
hcomp->State = HAL_COMP_STATE_READY;
}
else
{
status = HAL_ERROR;
}
}
return status;
}
/**
* @brief Comparator IRQ handler.
* @param hcomp COMP handle
* @retval None
*/
void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp)
{
/* Get the EXTI line corresponding to the selected COMP instance */
uint32_t exti_line = COMP_GET_EXTI_LINE(hcomp->Instance);
uint32_t tmp_comp_exti_flag_set = 0UL;
/* Check COMP EXTI flag */
#if defined(COMP7)
if((hcomp->Instance == COMP6) || (hcomp->Instance == COMP7))
{
if(LL_EXTI_IsActiveFlag_32_63(exti_line) != 0UL)
{
tmp_comp_exti_flag_set = 2UL;
}
}
else
{
if(LL_EXTI_IsActiveFlag_0_31(exti_line) != 0UL)
{
tmp_comp_exti_flag_set = 1UL;
}
}
#else
if(LL_EXTI_IsActiveFlag_0_31(exti_line) != 0UL)
{
tmp_comp_exti_flag_set = 1UL;
}
#endif /* COMP7 */
if(tmp_comp_exti_flag_set != 0UL)
{
/* Clear COMP EXTI line pending bit */
#if defined(COMP7)
if(tmp_comp_exti_flag_set == 2UL)
{
LL_EXTI_ClearFlag_32_63(exti_line);
}
else
{
LL_EXTI_ClearFlag_0_31(exti_line);
}
#else
LL_EXTI_ClearFlag_0_31(exti_line);
#endif /* COMP7 */
/* COMP trigger user callback */
#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
hcomp->TriggerCallback(hcomp);
#else
HAL_COMP_TriggerCallback(hcomp);
#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
}
}
/**
* @}
*/
/** @defgroup COMP_Exported_Functions_Group3 Peripheral Control functions
* @brief Management functions.
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the comparators.
@endverbatim
* @{
*/
/**
* @brief Lock the selected comparator configuration.
* @note A system reset is required to unlock the comparator configuration.
* @note Locking the comparator from reset state is possible
* if __HAL_RCC_SYSCFG_CLK_ENABLE() is being called before.
* @param hcomp COMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the COMP handle allocation and lock status */
if(hcomp == NULL)
{
status = HAL_ERROR;
}
else if(__HAL_COMP_IS_LOCKED(hcomp))
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
/* Set HAL COMP handle state */
switch(hcomp->State)
{
case HAL_COMP_STATE_RESET:
hcomp->State = HAL_COMP_STATE_RESET_LOCKED;
break;
case HAL_COMP_STATE_READY:
hcomp->State = HAL_COMP_STATE_READY_LOCKED;
break;
default: /* HAL_COMP_STATE_BUSY */
hcomp->State = HAL_COMP_STATE_BUSY_LOCKED;
break;
}
}
if(status == HAL_OK)
{
/* Set the lock bit corresponding to selected comparator */
__HAL_COMP_LOCK(hcomp);
}
return status;
}
/**
* @brief Return the output level (high or low) of the selected comparator.
* On this STM32 series, comparator 'value' is taken before
* polarity and blanking are applied, thus:
* - Comparator output is low when the input plus is at a lower
* voltage than the input minus
* - Comparator output is high when the input plus is at a higher
* voltage than the input minus
* @param hcomp COMP handle
* @retval Returns the selected comparator output level:
* @arg COMP_OUTPUT_LEVEL_LOW
* @arg COMP_OUTPUT_LEVEL_HIGH
*
*/
uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp)
{
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
return (uint32_t)(READ_BIT(hcomp->Instance->CSR, COMP_CSR_VALUE)
>> COMP_OUTPUT_LEVEL_BITOFFSET_POS);
}
/**
* @brief Comparator trigger callback.
* @param hcomp COMP handle
* @retval None
*/
__weak void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcomp);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_COMP_TriggerCallback should be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup COMP_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions.
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Return the COMP handle state.
* @param hcomp COMP handle
* @retval HAL state
*/
HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp)
{
/* Check the COMP handle allocation */
if(hcomp == NULL)
{
return HAL_COMP_STATE_RESET;
}
/* Check the parameter */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
/* Return HAL COMP handle state */
return hcomp->State;
}
/**
* @brief Return the COMP error code.
* @param hcomp COMP handle
* @retval COMP error code
*/
uint32_t HAL_COMP_GetError(COMP_HandleTypeDef *hcomp)
{
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance));
return hcomp->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_COMP_MODULE_ENABLED */
/**
* @}
*/
| 33,451 |
C
| 29.300725 | 142 | 0.578936 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_ucpd.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_ucpd.c
* @author MCD Application Team
* @brief UCPD LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_ucpd.h"
#include "stm32g4xx_ll_bus.h"
#include "stm32g4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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 */
| 4,789 |
C
| 27.17647 | 107 | 0.555231 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_adc.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_adc.c
* @author MCD Application Team
* @brief This file provides firmware functions to manage the following
* functionalities of the Analog to Digital Converter (ADC)
* peripheral:
* + Initialization and de-initialization functions
* + Peripheral Control functions
* + Peripheral State functions
* Other functions (extended functions) are available in file
* "stm32g4xx_hal_adc_ex.c".
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
==============================================================================
##### ADC peripheral features #####
==============================================================================
[..]
(+) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
(+) Interrupt generation at the end of regular conversion and in case of
analog watchdog or overrun events.
(+) Single and continuous conversion modes.
(+) Scan mode for conversion of several channels sequentially.
(+) Data alignment with in-built data coherency.
(+) Programmable sampling time (channel wise)
(+) External trigger (timer or EXTI) with configurable polarity
(+) DMA request generation for transfer of conversions data of regular group.
(+) Configurable delay between conversions in Dual interleaved mode.
(+) ADC channels selectable single/differential input.
(+) ADC offset shared on 4 offset instances.
(+) ADC gain compensation
(+) ADC calibration
(+) ADC conversion of regular group.
(+) ADC supply requirements: 1.62 V to 3.6 V.
(+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
Vdda or to an external voltage reference).
##### How to use this driver #####
==============================================================================
[..]
*** Configuration of top level parameters related to ADC ***
============================================================
[..]
(#) Enable the ADC interface
(++) As prerequisite, ADC clock must be configured at RCC top level.
(++) Two clock settings are mandatory:
(+++) ADC clock (core clock, also possibly conversion clock).
(+++) ADC clock (conversions clock).
Two possible clock sources: synchronous clock derived from AHB clock
or asynchronous clock derived from system clock or PLL (output divider P)
running up to 75MHz.
(+++) Example:
Into HAL_ADC_MspInit() (recommended code location) or with
other device clock parameters configuration:
(+++) __HAL_RCC_ADC_CLK_ENABLE(); (mandatory)
RCC_ADCCLKSOURCE_PLL enable: (optional: if asynchronous clock selected)
(+++) RCC_PeriphClkInitTypeDef RCC_PeriphClkInit;
(+++) PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
(+++) PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_PLL;
(+++) HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
(++) ADC clock source and clock prescaler are configured at ADC level with
parameter "ClockPrescaler" using function HAL_ADC_Init().
(#) ADC pins configuration
(++) Enable the clock for the ADC GPIOs
using macro __HAL_RCC_GPIOx_CLK_ENABLE()
(++) Configure these ADC pins in analog mode
using function HAL_GPIO_Init()
(#) Optionally, in case of usage of ADC with interruptions:
(++) Configure the NVIC for ADC
using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
(++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
into the function of corresponding ADC interruption vector
ADCx_IRQHandler().
(#) Optionally, in case of usage of DMA:
(++) Configure the DMA (DMA channel, mode normal or circular, ...)
using function HAL_DMA_Init().
(++) Configure the NVIC for DMA
using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
(++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
into the function of corresponding DMA interruption vector
DMAx_Channelx_IRQHandler().
*** Configuration of ADC, group regular, channels parameters ***
================================================================
[..]
(#) Configure the ADC parameters (resolution, data alignment, ...)
and regular group parameters (conversion trigger, sequencer, ...)
using function HAL_ADC_Init().
(#) Configure the channels for regular group parameters (channel number,
channel rank into sequencer, ..., into regular group)
using function HAL_ADC_ConfigChannel().
(#) Optionally, configure the analog watchdog parameters (channels
monitored, thresholds, ...)
using function HAL_ADC_AnalogWDGConfig().
*** Execution of ADC conversions ***
====================================
[..]
(#) Optionally, perform an automatic ADC calibration to improve the
conversion accuracy
using function HAL_ADCEx_Calibration_Start().
(#) ADC driver can be used among three modes: polling, interruption,
transfer by DMA.
(++) ADC conversion by polling:
(+++) Activate the ADC peripheral and start conversions
using function HAL_ADC_Start()
(+++) Wait for ADC conversion completion
using function HAL_ADC_PollForConversion()
(+++) Retrieve conversion results
using function HAL_ADC_GetValue()
(+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop()
(++) ADC conversion by interruption:
(+++) Activate the ADC peripheral and start conversions
using function HAL_ADC_Start_IT()
(+++) Wait for ADC conversion completion by call of function
HAL_ADC_ConvCpltCallback()
(this function must be implemented in user program)
(+++) Retrieve conversion results
using function HAL_ADC_GetValue()
(+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop_IT()
(++) ADC conversion with transfer by DMA:
(+++) Activate the ADC peripheral and start conversions
using function HAL_ADC_Start_DMA()
(+++) Wait for ADC conversion completion by call of function
HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
(these functions must be implemented in user program)
(+++) Conversion results are automatically transferred by DMA into
destination variable address.
(+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop_DMA()
[..]
(@) Callback functions must be implemented in user program:
(+@) HAL_ADC_ErrorCallback()
(+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
(+@) HAL_ADC_ConvCpltCallback()
(+@) HAL_ADC_ConvHalfCpltCallback
*** Deinitialization of ADC ***
============================================================
[..]
(#) Disable the ADC interface
(++) ADC clock can be hard reset and disabled at RCC top level.
(++) Hard reset of ADC peripherals
using macro __ADCx_FORCE_RESET(), __ADCx_RELEASE_RESET().
(++) ADC clock disable
using the equivalent macro/functions as configuration step.
(+++) Example:
Into HAL_ADC_MspDeInit() (recommended code location) or with
other device clock parameters configuration:
(+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14;
(+++) RCC_OscInitStructure.HSI14State = RCC_HSI14_OFF; (if not used for system clock)
(+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
(#) ADC pins configuration
(++) Disable the clock for the ADC GPIOs
using macro __HAL_RCC_GPIOx_CLK_DISABLE()
(#) Optionally, in case of usage of ADC with interruptions:
(++) Disable the NVIC for ADC
using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
(#) Optionally, in case of usage of DMA:
(++) Deinitialize the DMA
using function HAL_DMA_Init().
(++) Disable the NVIC for DMA
using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
[..]
*** Callback registration ***
=============================================
[..]
The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_ADC_RegisterCallback()
to register an interrupt callback.
[..]
Function HAL_ADC_RegisterCallback() allows to register following callbacks:
(+) ConvCpltCallback : ADC conversion complete callback
(+) ConvHalfCpltCallback : ADC conversion DMA half-transfer callback
(+) LevelOutOfWindowCallback : ADC analog watchdog 1 callback
(+) ErrorCallback : ADC error callback
(+) InjectedConvCpltCallback : ADC group injected conversion complete callback
(+) InjectedQueueOverflowCallback : ADC group injected context queue overflow callback
(+) LevelOutOfWindow2Callback : ADC analog watchdog 2 callback
(+) LevelOutOfWindow3Callback : ADC analog watchdog 3 callback
(+) EndOfSamplingCallback : ADC end of sampling callback
(+) MspInitCallback : ADC Msp Init callback
(+) MspDeInitCallback : ADC 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_ADC_UnRegisterCallback to reset a callback to the default
weak function.
[..]
HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) ConvCpltCallback : ADC conversion complete callback
(+) ConvHalfCpltCallback : ADC conversion DMA half-transfer callback
(+) LevelOutOfWindowCallback : ADC analog watchdog 1 callback
(+) ErrorCallback : ADC error callback
(+) InjectedConvCpltCallback : ADC group injected conversion complete callback
(+) InjectedQueueOverflowCallback : ADC group injected context queue overflow callback
(+) LevelOutOfWindow2Callback : ADC analog watchdog 2 callback
(+) LevelOutOfWindow3Callback : ADC analog watchdog 3 callback
(+) EndOfSamplingCallback : ADC end of sampling callback
(+) MspInitCallback : ADC Msp Init callback
(+) MspDeInitCallback : ADC Msp DeInit callback
[..]
By default, after the HAL_ADC_Init() and when the state is HAL_ADC_STATE_RESET
all callbacks are set to the corresponding weak functions:
examples HAL_ADC_ConvCpltCallback(), HAL_ADC_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the HAL_ADC_Init()/ HAL_ADC_DeInit() only when
these callbacks are null (not registered beforehand).
[..]
If MspInit or MspDeInit are not null, the HAL_ADC_Init()/ HAL_ADC_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in HAL_ADC_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in HAL_ADC_STATE_READY or HAL_ADC_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_ADC_RegisterCallback() before calling HAL_ADC_DeInit()
or HAL_ADC_Init() function.
[..]
When the compilation flag USE_HAL_ADC_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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup ADC ADC
* @brief ADC HAL module driver
* @{
*/
#ifdef HAL_ADC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ADC_Private_Constants ADC Private Constants
* @{
*/
#define ADC_CFGR_FIELDS_1 ((ADC_CFGR_RES | ADC_CFGR_ALIGN |\
ADC_CFGR_CONT | ADC_CFGR_OVRMOD |\
ADC_CFGR_DISCEN | ADC_CFGR_DISCNUM |\
ADC_CFGR_EXTEN | ADC_CFGR_EXTSEL)) /*!< ADC_CFGR fields of parameters that can be updated when no regular conversion is on-going */
/* Timeout values for ADC operations (enable settling time, */
/* disable settling time, ...). */
/* Values defined to be higher than worst cases: low clock frequency, */
/* maximum prescalers. */
#define ADC_ENABLE_TIMEOUT (2UL) /*!< ADC enable time-out value */
#define ADC_DISABLE_TIMEOUT (2UL) /*!< ADC disable time-out value */
/* Timeout to wait for current conversion on going to be completed. */
/* Timeout fixed to longest ADC conversion possible, for 1 channel: */
/* - maximum sampling time (640.5 adc_clk) */
/* - ADC resolution (Tsar 12 bits= 12.5 adc_clk) */
/* - System clock / ADC clock <= 4096 (hypothesis of maximum clock ratio) */
/* - ADC oversampling ratio 256 */
/* Calculation: 653 * 4096 * 256 CPU clock cycles max */
/* Unit: cycles of CPU clock. */
#define ADC_CONVERSION_TIME_MAX_CPU_CYCLES (653UL * 4096UL * 256UL) /*!< ADC conversion completion time-out value */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup ADC_Exported_Functions ADC Exported Functions
* @{
*/
/** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief ADC Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize and configure the ADC.
(+) De-initialize the ADC.
@endverbatim
* @{
*/
/**
* @brief Initialize the ADC peripheral and regular group according to
* parameters specified in structure "ADC_InitTypeDef".
* @note As prerequisite, ADC clock must be configured at RCC top level
* (refer to description of RCC configuration for ADC
* in header of this file).
* @note Possibility to update parameters on the fly:
* This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
* coming from ADC state reset. Following calls to this function can
* be used to reconfigure some parameters of ADC_InitTypeDef
* structure on the fly, without modifying MSP configuration. If ADC
* MSP has to be modified again, HAL_ADC_DeInit() must be called
* before HAL_ADC_Init().
* The setting of these parameters is conditioned to ADC state.
* For parameters constraints, see comments of structure
* "ADC_InitTypeDef".
* @note This function configures the ADC within 2 scopes: scope of entire
* ADC and scope of regular group. For parameters details, see comments
* of structure "ADC_InitTypeDef".
* @note Parameters related to common ADC registers (ADC clock mode) are set
* only if all ADCs are disabled.
* If this is not the case, these common parameters setting are
* bypassed without error reporting: it can be the intended behaviour in
* case of update of a parameter of ADC_InitTypeDef on the fly,
* without disabling the other ADCs.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
uint32_t tmpCFGR;
uint32_t tmp_adc_reg_is_conversion_on_going;
__IO uint32_t wait_loop_index = 0UL;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check ADC handle */
if (hadc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
assert_param(IS_ADC_GAIN_COMPENSATION(hadc->Init.GainCompensation));
assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
assert_param(IS_ADC_EXTTRIG(hadc, hadc->Init.ExternalTrigConv));
assert_param(IS_ADC_SAMPLINGMODE(hadc->Init.SamplingMode));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
{
assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
if (hadc->Init.DiscontinuousConvMode == ENABLE)
{
assert_param(IS_ADC_REGULAR_DISCONT_NUMBER(hadc->Init.NbrOfDiscConversion));
}
}
/* DISCEN and CONT bits cannot be set at the same time */
assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == ENABLE)));
/* Actions performed only if ADC is coming from state reset: */
/* - Initialization of ADC MSP */
if (hadc->State == HAL_ADC_STATE_RESET)
{
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
/* Init the ADC Callback settings */
hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback; /* Legacy weak callback */
hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback; /* Legacy weak callback */
hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback; /* Legacy weak callback */
hadc->ErrorCallback = HAL_ADC_ErrorCallback; /* Legacy weak callback */
hadc->InjectedConvCpltCallback = HAL_ADCEx_InjectedConvCpltCallback; /* Legacy weak callback */
hadc->InjectedQueueOverflowCallback = HAL_ADCEx_InjectedQueueOverflowCallback; /* Legacy weak callback */
hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback; /* Legacy weak callback */
hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback; /* Legacy weak callback */
hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback; /* Legacy weak callback */
if (hadc->MspInitCallback == NULL)
{
hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware */
hadc->MspInitCallback(hadc);
#else
/* Init the low level hardware */
HAL_ADC_MspInit(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
/* Initialize Lock */
hadc->Lock = HAL_UNLOCKED;
}
/* - Exit from deep-power-down mode and ADC voltage regulator enable */
if (LL_ADC_IsDeepPowerDownEnabled(hadc->Instance) != 0UL)
{
/* Disable ADC deep power down mode */
LL_ADC_DisableDeepPowerDown(hadc->Instance);
/* System was in deep power down mode, calibration must
be relaunched or a previously saved calibration factor
re-applied once the ADC voltage regulator is enabled */
}
if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
{
/* Enable ADC internal voltage regulator */
LL_ADC_EnableInternalRegulator(hadc->Instance);
/* Note: Variable divided by 2 to compensate partially */
/* CPU processing cycles, scaling in us split to not */
/* exceed 32 bits register capacity and handle low frequency. */
wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
while (wait_loop_index != 0UL)
{
wait_loop_index--;
}
}
/* Verification that ADC voltage regulator is correctly enabled, whether */
/* or not ADC is coming from state reset (if any potential problem of */
/* clocking, voltage regulator would not be enabled). */
if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
tmp_hal_status = HAL_ERROR;
}
/* Configuration of ADC parameters if previous preliminary actions are */
/* correctly completed and if there is no conversion on going on regular */
/* group (ADC may already be enabled at this point if HAL_ADC_Init() is */
/* called to update a parameter on the fly). */
tmp_adc_reg_is_conversion_on_going = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
if (((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
&& (tmp_adc_reg_is_conversion_on_going == 0UL)
)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY,
HAL_ADC_STATE_BUSY_INTERNAL);
/* Configuration of common ADC parameters */
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated only when ADC is disabled: */
/* - clock configuration */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
{
/* Reset configuration of ADC common register CCR: */
/* */
/* - ADC clock mode and ACC prescaler (CKMODE and PRESC bits)are set */
/* according to adc->Init.ClockPrescaler. It selects the clock */
/* source and sets the clock division factor. */
/* */
/* Some parameters of this register are not reset, since they are set */
/* by other functions and must be kept in case of usage of this */
/* function on the fly (update of a parameter of ADC_InitTypeDef */
/* without needing to reconfigure all other ADC groups/channels */
/* parameters): */
/* - when multimode feature is available, multimode-related */
/* parameters: MDMA, DMACFG, DELAY, DUAL (set by API */
/* HAL_ADCEx_MultiModeConfigChannel() ) */
/* - internal measurement paths: Vbat, temperature sensor, Vref */
/* (set into HAL_ADC_ConfigChannel() or */
/* HAL_ADCEx_InjectedConfigChannel() ) */
LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(hadc->Instance), hadc->Init.ClockPrescaler);
}
}
/* Configuration of ADC: */
/* - resolution Init.Resolution */
/* - data alignment Init.DataAlign */
/* - external trigger to start conversion Init.ExternalTrigConv */
/* - external trigger polarity Init.ExternalTrigConvEdge */
/* - continuous conversion mode Init.ContinuousConvMode */
/* - overrun Init.Overrun */
/* - discontinuous mode Init.DiscontinuousConvMode */
/* - discontinuous mode channel count Init.NbrOfDiscConversion */
tmpCFGR = (ADC_CFGR_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode) |
hadc->Init.Overrun |
hadc->Init.DataAlign |
hadc->Init.Resolution |
ADC_CFGR_REG_DISCONTINUOUS((uint32_t)hadc->Init.DiscontinuousConvMode));
if (hadc->Init.DiscontinuousConvMode == ENABLE)
{
tmpCFGR |= ADC_CFGR_DISCONTINUOUS_NUM(hadc->Init.NbrOfDiscConversion);
}
/* Enable external trigger if trigger selection is different of software */
/* start. */
/* Note: This configuration keeps the hardware feature of parameter */
/* ExternalTrigConvEdge "trigger edge none" equivalent to */
/* software start. */
if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
{
tmpCFGR |= ((hadc->Init.ExternalTrigConv & ADC_CFGR_EXTSEL)
| hadc->Init.ExternalTrigConvEdge
);
}
/* Update Configuration Register CFGR */
MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_FIELDS_1, tmpCFGR);
/* Configuration of sampling mode */
MODIFY_REG(hadc->Instance->CFGR2, ADC_CFGR2_BULB | ADC_CFGR2_SMPTRIG, hadc->Init.SamplingMode);
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular and injected groups: */
/* - Gain Compensation Init.GainCompensation */
/* - DMA continuous request Init.DMAContinuousRequests */
/* - LowPowerAutoWait feature Init.LowPowerAutoWait */
/* - Oversampling parameters Init.Oversampling */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
tmpCFGR = (ADC_CFGR_DFSDM(hadc) |
ADC_CFGR_AUTOWAIT((uint32_t)hadc->Init.LowPowerAutoWait) |
ADC_CFGR_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests));
MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_FIELDS_2, tmpCFGR);
if (hadc->Init.GainCompensation != 0UL)
{
SET_BIT(hadc->Instance->CFGR2, ADC_CFGR2_GCOMP);
MODIFY_REG(hadc->Instance->GCOMP, ADC_GCOMP_GCOMPCOEFF, hadc->Init.GainCompensation);
}
else
{
CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_GCOMP);
MODIFY_REG(hadc->Instance->GCOMP, ADC_GCOMP_GCOMPCOEFF, 0UL);
}
if (hadc->Init.OversamplingMode == ENABLE)
{
assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversampling.Ratio));
assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversampling.RightBitShift));
assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversampling.TriggeredMode));
assert_param(IS_ADC_REGOVERSAMPLING_MODE(hadc->Init.Oversampling.OversamplingStopReset));
/* Configuration of Oversampler: */
/* - Oversampling Ratio */
/* - Right bit shift */
/* - Triggered mode */
/* - Oversampling mode (continued/resumed) */
MODIFY_REG(hadc->Instance->CFGR2,
ADC_CFGR2_OVSR |
ADC_CFGR2_OVSS |
ADC_CFGR2_TROVS |
ADC_CFGR2_ROVSM,
ADC_CFGR2_ROVSE |
hadc->Init.Oversampling.Ratio |
hadc->Init.Oversampling.RightBitShift |
hadc->Init.Oversampling.TriggeredMode |
hadc->Init.Oversampling.OversamplingStopReset
);
}
else
{
/* Disable ADC oversampling scope on ADC group regular */
CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSE);
}
}
/* Configuration of regular group sequencer: */
/* - if scan mode is disabled, regular channels sequence length is set to */
/* 0x00: 1 channel converted (channel on regular rank 1) */
/* Parameter "NbrOfConversion" is discarded. */
/* Note: Scan mode is not present by hardware on this device, but */
/* emulated by software for alignment over all STM32 devices. */
/* - if scan mode is enabled, regular channels sequence length is set to */
/* parameter "NbrOfConversion". */
if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
{
/* Set number of ranks in regular group sequencer */
MODIFY_REG(hadc->Instance->SQR1, ADC_SQR1_L, (hadc->Init.NbrOfConversion - (uint8_t)1));
}
else
{
CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L);
}
/* Initialize the ADC state */
/* Clear HAL_ADC_STATE_BUSY_INTERNAL bit, set HAL_ADC_STATE_READY bit */
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY);
}
else
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
tmp_hal_status = HAL_ERROR;
}
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Deinitialize the ADC peripheral registers to their default reset
* values, with deinitialization of the ADC MSP.
* @note For devices with several ADCs: reset of ADC common registers is done
* only if all ADCs sharing the same common group are disabled.
* (function "HAL_ADC_MspDeInit()" is also called under the same conditions:
* all ADC instances use the same core clock at RCC level, disabling
* the core clock reset all ADC instances).
* If this is not the case, reset of these common parameters reset is
* bypassed without error reporting: it can be the intended behavior in
* case of reset of a single ADC while the other ADCs sharing the same
* common group is still running.
* @note By default, HAL_ADC_DeInit() set ADC in mode deep power-down:
* this saves more power by reducing leakage currents
* and is particularly interesting before entering MCU low-power modes.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check ADC handle */
if (hadc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
/* Stop potential conversion on going */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
/* Flush register JSQR: reset the queue sequencer when injected */
/* queue sequencer is enabled and ADC disabled. */
/* The software and hardware triggers of the injected sequence are both */
/* internally disabled just after the completion of the last valid */
/* injected sequence. */
SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JQM);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Change ADC state */
hadc->State = HAL_ADC_STATE_READY;
}
}
/* Note: HAL ADC deInit is done independently of ADC conversion stop */
/* and disable return status. In case of status fail, attempt to */
/* perform deinitialization anyway and it is up user code in */
/* in HAL_ADC_MspDeInit() to reset the ADC peripheral using */
/* system RCC hard reset. */
/* ========== Reset ADC registers ========== */
/* Reset register IER */
__HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3 | ADC_IT_AWD2 | ADC_IT_AWD1 |
ADC_IT_JQOVF | ADC_IT_OVR |
ADC_IT_JEOS | ADC_IT_JEOC |
ADC_IT_EOS | ADC_IT_EOC |
ADC_IT_EOSMP | ADC_IT_RDY));
/* Reset register ISR */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3 | ADC_FLAG_AWD2 | ADC_FLAG_AWD1 |
ADC_FLAG_JQOVF | ADC_FLAG_OVR |
ADC_FLAG_JEOS | ADC_FLAG_JEOC |
ADC_FLAG_EOS | ADC_FLAG_EOC |
ADC_FLAG_EOSMP | ADC_FLAG_RDY));
/* Reset register CR */
/* Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART,
ADC_CR_ADCAL, ADC_CR_ADDIS and ADC_CR_ADEN are in access mode "read-set":
no direct reset applicable.
Update CR register to reset value where doable by software */
CLEAR_BIT(hadc->Instance->CR, ADC_CR_ADVREGEN | ADC_CR_ADCALDIF);
SET_BIT(hadc->Instance->CR, ADC_CR_DEEPPWD);
/* Reset register CFGR */
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_FIELDS);
SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS);
/* Reset register CFGR2 */
CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSM | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS |
ADC_CFGR2_OVSR | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE);
/* Reset register SMPR1 */
CLEAR_BIT(hadc->Instance->SMPR1, ADC_SMPR1_FIELDS);
/* Reset register SMPR2 */
CLEAR_BIT(hadc->Instance->SMPR2, ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16 |
ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13 |
ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10);
/* Reset register TR1 */
CLEAR_BIT(hadc->Instance->TR1, ADC_TR1_HT1 | ADC_TR1_LT1);
/* Reset register TR2 */
CLEAR_BIT(hadc->Instance->TR2, ADC_TR2_HT2 | ADC_TR2_LT2);
/* Reset register TR3 */
CLEAR_BIT(hadc->Instance->TR3, ADC_TR3_HT3 | ADC_TR3_LT3);
/* Reset register SQR1 */
CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 |
ADC_SQR1_SQ1 | ADC_SQR1_L);
/* Reset register SQR2 */
CLEAR_BIT(hadc->Instance->SQR2, ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 |
ADC_SQR2_SQ6 | ADC_SQR2_SQ5);
/* Reset register SQR3 */
CLEAR_BIT(hadc->Instance->SQR3, ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 |
ADC_SQR3_SQ11 | ADC_SQR3_SQ10);
/* Reset register SQR4 */
CLEAR_BIT(hadc->Instance->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15);
/* Register JSQR was reset when the ADC was disabled */
/* Reset register DR */
/* bits in access mode read only, no direct reset applicable*/
/* Reset register OFR1 */
CLEAR_BIT(hadc->Instance->OFR1, ADC_OFR1_OFFSET1_EN | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1);
/* Reset register OFR2 */
CLEAR_BIT(hadc->Instance->OFR2, ADC_OFR2_OFFSET2_EN | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2);
/* Reset register OFR3 */
CLEAR_BIT(hadc->Instance->OFR3, ADC_OFR3_OFFSET3_EN | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3);
/* Reset register OFR4 */
CLEAR_BIT(hadc->Instance->OFR4, ADC_OFR4_OFFSET4_EN | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4);
/* Reset registers JDR1, JDR2, JDR3, JDR4 */
/* bits in access mode read only, no direct reset applicable*/
/* Reset register AWD2CR */
CLEAR_BIT(hadc->Instance->AWD2CR, ADC_AWD2CR_AWD2CH);
/* Reset register AWD3CR */
CLEAR_BIT(hadc->Instance->AWD3CR, ADC_AWD3CR_AWD3CH);
/* Reset register DIFSEL */
CLEAR_BIT(hadc->Instance->DIFSEL, ADC_DIFSEL_DIFSEL);
/* Reset register CALFACT */
CLEAR_BIT(hadc->Instance->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S);
/* ========== Reset common ADC registers ========== */
/* Software is allowed to change common parameters only when all the other
ADCs are disabled. */
if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
{
/* Reset configuration of ADC common register CCR:
- clock mode: CKMODE, PRESCEN
- multimode related parameters (when this feature is available): MDMA,
DMACFG, DELAY, DUAL (set by HAL_ADCEx_MultiModeConfigChannel() API)
- internal measurement paths: Vbat, temperature sensor, Vref (set into
HAL_ADC_ConfigChannel() or HAL_ADCEx_InjectedConfigChannel() )
*/
ADC_CLEAR_COMMON_CONTROL_REGISTER(hadc);
/* ========== Hard reset ADC peripheral ========== */
/* Performs a global reset of the entire ADC peripherals instances */
/* sharing the same common ADC instance: ADC state is forced to */
/* a similar state as after device power-on. */
/* Note: A possible implementation is to add RCC bus reset of ADC */
/* (for example, using macro */
/* __HAL_RCC_ADC..._FORCE_RESET()/..._RELEASE_RESET()/..._CLK_DISABLE()) */
/* in function "void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)": */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
if (hadc->MspDeInitCallback == NULL)
{
hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware */
hadc->MspDeInitCallback(hadc);
#else
/* DeInit the low level hardware */
HAL_ADC_MspDeInit(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
/* Reset injected channel configuration parameters */
hadc->InjectionConfig.ContextQueue = 0;
hadc->InjectionConfig.ChannelCount = 0;
/* Set ADC state */
hadc->State = HAL_ADC_STATE_RESET;
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Initialize the ADC MSP.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_MspInit must be implemented in the user file.
*/
}
/**
* @brief DeInitialize the ADC MSP.
* @param hadc ADC handle
* @note All ADC instances use the same core clock at RCC level, disabling
* the core clock reset all ADC instances).
* @retval None
*/
__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_MspDeInit must be implemented in the user file.
*/
}
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User ADC Callback
* To be used instead of the weak predefined callback
* @param hadc Pointer to a ADC_HandleTypeDef structure that contains
* the configuration information for the specified ADC.
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID ADC conversion complete callback ID
* @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID ADC conversion DMA half-transfer callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID ADC analog watchdog 1 callback ID
* @arg @ref HAL_ADC_ERROR_CB_ID ADC error callback ID
* @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID ADC group injected conversion complete callback ID
* @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID ADC group injected context queue overflow callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID ADC analog watchdog 2 callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID ADC analog watchdog 3 callback ID
* @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID ADC end of sampling callback ID
* @arg @ref HAL_ADC_MSPINIT_CB_ID ADC Msp Init callback ID
* @arg @ref HAL_ADC_MSPDEINIT_CB_ID ADC Msp DeInit callback ID
* @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID,
pADC_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
{
switch (CallbackID)
{
case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
hadc->ConvCpltCallback = pCallback;
break;
case HAL_ADC_CONVERSION_HALF_CB_ID :
hadc->ConvHalfCpltCallback = pCallback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
hadc->LevelOutOfWindowCallback = pCallback;
break;
case HAL_ADC_ERROR_CB_ID :
hadc->ErrorCallback = pCallback;
break;
case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
hadc->InjectedConvCpltCallback = pCallback;
break;
case HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID :
hadc->InjectedQueueOverflowCallback = pCallback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
hadc->LevelOutOfWindow2Callback = pCallback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
hadc->LevelOutOfWindow3Callback = pCallback;
break;
case HAL_ADC_END_OF_SAMPLING_CB_ID :
hadc->EndOfSamplingCallback = pCallback;
break;
case HAL_ADC_MSPINIT_CB_ID :
hadc->MspInitCallback = pCallback;
break;
case HAL_ADC_MSPDEINIT_CB_ID :
hadc->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_ADC_STATE_RESET == hadc->State)
{
switch (CallbackID)
{
case HAL_ADC_MSPINIT_CB_ID :
hadc->MspInitCallback = pCallback;
break;
case HAL_ADC_MSPDEINIT_CB_ID :
hadc->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Unregister a ADC Callback
* ADC callback is redirected to the weak predefined callback
* @param hadc Pointer to a ADC_HandleTypeDef structure that contains
* the configuration information for the specified ADC.
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID ADC conversion complete callback ID
* @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID ADC conversion DMA half-transfer callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID ADC analog watchdog 1 callback ID
* @arg @ref HAL_ADC_ERROR_CB_ID ADC error callback ID
* @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID ADC group injected conversion complete callback ID
* @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID ADC group injected context queue overflow callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID ADC analog watchdog 2 callback ID
* @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID ADC analog watchdog 3 callback ID
* @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID ADC end of sampling callback ID
* @arg @ref HAL_ADC_MSPINIT_CB_ID ADC Msp Init callback ID
* @arg @ref HAL_ADC_MSPDEINIT_CB_ID ADC Msp DeInit callback ID
* @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
{
switch (CallbackID)
{
case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
break;
case HAL_ADC_CONVERSION_HALF_CB_ID :
hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
break;
case HAL_ADC_ERROR_CB_ID :
hadc->ErrorCallback = HAL_ADC_ErrorCallback;
break;
case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
hadc->InjectedConvCpltCallback = HAL_ADCEx_InjectedConvCpltCallback;
break;
case HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID :
hadc->InjectedQueueOverflowCallback = HAL_ADCEx_InjectedQueueOverflowCallback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback;
break;
case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback;
break;
case HAL_ADC_END_OF_SAMPLING_CB_ID :
hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback;
break;
case HAL_ADC_MSPINIT_CB_ID :
hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit */
break;
case HAL_ADC_MSPDEINIT_CB_ID :
hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_ADC_STATE_RESET == hadc->State)
{
switch (CallbackID)
{
case HAL_ADC_MSPINIT_CB_ID :
hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit */
break;
case HAL_ADC_MSPDEINIT_CB_ID :
hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
* @brief ADC IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Start conversion of regular group.
(+) Stop conversion of regular group.
(+) Poll for conversion complete on regular group.
(+) Poll for conversion event.
(+) Get result of regular channel conversion.
(+) Start conversion of regular group and enable interruptions.
(+) Stop conversion of regular group and disable interruptions.
(+) Handle ADC interrupt request
(+) Start conversion of regular group and enable DMA transfer.
(+) Stop conversion of regular group and disable ADC DMA transfer.
@endverbatim
* @{
*/
/**
* @brief Enable ADC, start conversion of regular group.
* @note Interruptions enabled in this function: None.
* @note Case of multimode enabled (when multimode feature is available):
* if ADC is Slave, ADC is enabled but conversion is not started,
* if ADC is master, ADC is enabled and multimode conversion is started.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
#if defined(ADC_MULTIMODE_SUPPORT)
const ADC_TypeDef *tmpADC_Master;
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Perform ADC enable and conversion start if no conversion is on going */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Process locked */
__HAL_LOCK(hadc);
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
/* Start conversion if ADC is effectively enabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
HAL_ADC_STATE_REG_BUSY);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
- if ADC instance is master or if multimode feature is not available
- if multimode setting is disabled (ADC instance slave in independent mode) */
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
)
{
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#endif
/* Set ADC error code */
/* Check if a conversion is on going on ADC group injected */
if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
{
/* Reset ADC error code fields related to regular conversions only */
CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
}
else
{
/* Reset all ADC error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
/* Clear ADC group regular conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Case of multimode enabled (when multimode feature is available): */
/* - if ADC is slave and dual regular conversions are enabled, ADC is */
/* enabled only (conversion is not started), */
/* - if ADC is master, ADC is enabled and conversion is started. */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
{
/* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
}
else
{
/* ADC instance is a multimode slave instance with multimode regular conversions enabled */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
/* if Master ADC JAUTO bit is set, update Slave State in setting
HAL_ADC_STATE_INJ_BUSY bit and in resetting HAL_ADC_STATE_INJ_EOC bit */
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
if (READ_BIT(tmpADC_Master->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
}
#else
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
#endif
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
}
else
{
tmp_hal_status = HAL_BUSY;
}
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Stop ADC conversion of regular group (and injected channels in
* case of auto_injection mode), disable ADC peripheral.
* @note: ADC peripheral disable is forcing stop of potential
* conversion on injected group. If injected group is under use, it
* should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential conversion on going, on ADC groups regular and injected */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* 2. Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Wait for regular group conversion to be completed.
* @note ADC conversion flags EOS (end of sequence) and EOC (end of
* conversion) are cleared by this function, with an exception:
* if low power feature "LowPowerAutoWait" is enabled, flags are
* not cleared to not interfere with this feature until data register
* is read using function HAL_ADC_GetValue().
* @note This function cannot be used in a particular setup: ADC configured
* in DMA mode and polling for end of each conversion (ADC init
* parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
* In this case, DMA resets the flag EOC and polling cannot be
* performed on each conversion. Nevertheless, polling can still
* be performed on the complete sequence (ADC init
* parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
* @param hadc ADC handle
* @param Timeout Timeout value in millisecond.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t tmp_Flag_End;
uint32_t tmp_cfgr;
#if defined(ADC_MULTIMODE_SUPPORT)
const ADC_TypeDef *tmpADC_Master;
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* If end of conversion selected to end of sequence conversions */
if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
{
tmp_Flag_End = ADC_FLAG_EOS;
}
/* If end of conversion selected to end of unitary conversion */
else /* ADC_EOC_SINGLE_CONV */
{
/* Verification that ADC configuration is compliant with polling for */
/* each conversion: */
/* Particular case is ADC configured in DMA mode and ADC sequencer with */
/* several ranks and polling for end of each conversion. */
/* For code simplicity sake, this particular case is generalized to */
/* ADC configured in DMA mode and and polling for end of each conversion. */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
{
/* Check ADC DMA mode in independent mode on ADC group regular */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN) != 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
return HAL_ERROR;
}
else
{
tmp_Flag_End = (ADC_FLAG_EOC);
}
}
else
{
/* Check ADC DMA mode in multimode on ADC group regular */
if (LL_ADC_GetMultiDMATransfer(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DMA_EACH_ADC)
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
return HAL_ERROR;
}
else
{
tmp_Flag_End = (ADC_FLAG_EOC);
}
}
#else
/* Check ADC DMA mode */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN) != 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
return HAL_ERROR;
}
else
{
tmp_Flag_End = (ADC_FLAG_EOC);
}
#endif
}
/* Get tick count */
tickstart = HAL_GetTick();
/* Wait until End of unitary conversion or sequence conversions flag is raised */
while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
{
/* Check if timeout is disabled (set to infinite wait) */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
{
/* New check to avoid false timeout detection in case of preemption */
if ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
{
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_TIMEOUT;
}
}
}
}
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going. */
if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
&& (hadc->Init.ContinuousConvMode == DISABLE)
)
{
/* Check whether end of sequence is reached */
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
{
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
}
/* Get relevant register CFGR in ADC instance of ADC master or slave */
/* in function of multimode state (for devices with multimode */
/* available). */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
{
/* Retrieve handle ADC CFGR register */
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
}
else
{
/* Retrieve Master ADC CFGR register */
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
}
#else
/* Retrieve handle ADC CFGR register */
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
#endif
/* Clear polled flag */
if (tmp_Flag_End == ADC_FLAG_EOS)
{
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOS);
}
else
{
/* Clear end of conversion EOC flag of regular group if low power feature */
/* "LowPowerAutoWait " is disabled, to not interfere with this feature */
/* until data register is read using function HAL_ADC_GetValue(). */
if (READ_BIT(tmp_cfgr, ADC_CFGR_AUTDLY) == 0UL)
{
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Poll for ADC event.
* @param hadc ADC handle
* @param EventType the ADC event type.
* This parameter can be one of the following values:
* @arg @ref ADC_EOSMP_EVENT ADC End of Sampling event
* @arg @ref ADC_AWD1_EVENT ADC Analog watchdog 1 event (main analog watchdog, present on all STM32 devices)
* @arg @ref ADC_AWD2_EVENT ADC Analog watchdog 2 event (additional analog watchdog, not present on all STM32 families)
* @arg @ref ADC_AWD3_EVENT ADC Analog watchdog 3 event (additional analog watchdog, not present on all STM32 families)
* @arg @ref ADC_OVR_EVENT ADC Overrun event
* @arg @ref ADC_JQOVF_EVENT ADC Injected context queue overflow event
* @param Timeout Timeout value in millisecond.
* @note The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
* Indeed, the latter is reset only if hadc->Init.Overrun field is set
* to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
* by a new converted data as soon as OVR is cleared.
* To reset OVR flag once the preserved data is retrieved, the user can resort
* to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout)
{
uint32_t tickstart;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_EVENT_TYPE(EventType));
/* Get tick count */
tickstart = HAL_GetTick();
/* Check selected event flag */
while (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
{
/* Check if timeout is disabled (set to infinite wait) */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
{
/* New check to avoid false timeout detection in case of preemption */
if (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
{
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_TIMEOUT;
}
}
}
}
switch (EventType)
{
/* End Of Sampling event */
case ADC_EOSMP_EVENT:
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
/* Clear the End Of Sampling flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
break;
/* Analog watchdog (level out of window) event */
/* Note: In case of several analog watchdog enabled, if needed to know */
/* which one triggered and on which ADCx, test ADC state of analog watchdog */
/* flags HAL_ADC_STATE_AWD1/2/3 using function "HAL_ADC_GetState()". */
/* For example: */
/* " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) " */
/* " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD2) != 0UL) " */
/* " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD3) != 0UL) " */
/* Check analog watchdog 1 flag */
case ADC_AWD_EVENT:
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
break;
/* Check analog watchdog 2 flag */
case ADC_AWD2_EVENT:
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
break;
/* Check analog watchdog 3 flag */
case ADC_AWD3_EVENT:
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
break;
/* Injected context queue overflow event */
case ADC_JQOVF_EVENT:
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF);
/* Set ADC error code to Injected context queue overflow */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
/* Clear ADC Injected context queue overflow flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JQOVF);
break;
/* Overrun event */
default: /* Case ADC_OVR_EVENT */
/* If overrun is set to overwrite previous data, overrun event is not */
/* considered as an error. */
/* (cf ref manual "Managing conversions without using the DMA and without */
/* overrun ") */
if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
/* Set ADC error code to overrun */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
}
else
{
/* Clear ADC Overrun flag only if Overrun is set to ADC_OVR_DATA_OVERWRITTEN
otherwise, data register is potentially overwritten by new converted data as soon
as OVR is cleared. */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
}
break;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Enable ADC, start conversion of regular group with interruption.
* @note Interruptions enabled in this function according to initialization
* setting : EOC (end of conversion), EOS (end of sequence),
* OVR overrun.
* Each of these interruptions has its dedicated callback function.
* @note Case of multimode enabled (when multimode feature is available):
* HAL_ADC_Start_IT() must be called for ADC Slave first, then for
* ADC Master.
* For ADC Slave, ADC is enabled only (conversion is not started).
* For ADC Master, ADC is enabled and multimode conversion is started.
* @note To guarantee a proper reset of all interruptions once all the needed
* conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
* a correct stop of the IT-based conversions.
* @note By default, HAL_ADC_Start_IT() does not enable the End Of Sampling
* interruption. If required (e.g. in case of oversampling with trigger
* mode), the user must:
* 1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
* 2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
* before calling HAL_ADC_Start_IT().
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
#if defined(ADC_MULTIMODE_SUPPORT)
const ADC_TypeDef *tmpADC_Master;
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Perform ADC enable and conversion start if no conversion is on going */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Process locked */
__HAL_LOCK(hadc);
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
/* Start conversion if ADC is effectively enabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
HAL_ADC_STATE_REG_BUSY);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
- if ADC instance is master or if multimode feature is not available
- if multimode setting is disabled (ADC instance slave in independent mode) */
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
)
{
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#endif
/* Set ADC error code */
/* Check if a conversion is on going on ADC group injected */
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
{
/* Reset ADC error code fields related to regular conversions only */
CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
}
else
{
/* Reset all ADC error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
/* Clear ADC group regular conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* Disable all interruptions before enabling the desired ones */
__HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
/* Enable ADC end of conversion interrupt */
switch (hadc->Init.EOCSelection)
{
case ADC_EOC_SEQ_CONV:
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS);
break;
/* case ADC_EOC_SINGLE_CONV */
default:
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
break;
}
/* Enable ADC overrun interrupt */
/* If hadc->Init.Overrun is set to ADC_OVR_DATA_PRESERVED, only then is
ADC_IT_OVR enabled; otherwise data overwrite is considered as normal
behavior and no CPU time is lost for a non-processed interruption */
if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
{
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
}
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Case of multimode enabled (when multimode feature is available): */
/* - if ADC is slave and dual regular conversions are enabled, ADC is */
/* enabled only (conversion is not started), */
/* - if ADC is master, ADC is enabled and conversion is started. */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
{
/* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
/* Enable as well injected interruptions in case
HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
allows to start regular and injected conversions when JAUTO is
set with a single call to HAL_ADC_Start_IT() */
switch (hadc->Init.EOCSelection)
{
case ADC_EOC_SEQ_CONV:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
break;
/* case ADC_EOC_SINGLE_CONV */
default:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
break;
}
}
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
}
else
{
/* ADC instance is a multimode slave instance with multimode regular conversions enabled */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
/* if Master ADC JAUTO bit is set, Slave injected interruptions
are enabled nevertheless (for same reason as above) */
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
if (READ_BIT(tmpADC_Master->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
/* First, update Slave State in setting HAL_ADC_STATE_INJ_BUSY bit
and in resetting HAL_ADC_STATE_INJ_EOC bit */
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
/* Next, set Slave injected interruptions */
switch (hadc->Init.EOCSelection)
{
case ADC_EOC_SEQ_CONV:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
break;
/* case ADC_EOC_SINGLE_CONV */
default:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
break;
}
}
}
#else
/* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
{
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
/* Enable as well injected interruptions in case
HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
allows to start regular and injected conversions when JAUTO is
set with a single call to HAL_ADC_Start_IT() */
switch (hadc->Init.EOCSelection)
{
case ADC_EOC_SEQ_CONV:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
break;
/* case ADC_EOC_SINGLE_CONV */
default:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
break;
}
}
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
#endif
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
}
else
{
tmp_hal_status = HAL_BUSY;
}
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Stop ADC conversion of regular group (and injected group in
* case of auto_injection mode), disable interrution of
* end-of-conversion, disable ADC peripheral.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential conversion on going, on ADC groups regular and injected */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* Disable ADC end of conversion interrupt for regular group */
/* Disable ADC overrun interrupt */
__HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
/* 2. Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Enable ADC, start conversion of regular group and transfer result through DMA.
* @note Interruptions enabled in this function:
* overrun (if applicable), DMA half transfer, DMA transfer complete.
* Each of these interruptions has its dedicated callback function.
* @note Case of multimode enabled (when multimode feature is available): HAL_ADC_Start_DMA()
* is designed for single-ADC mode only. For multimode, the dedicated
* HAL_ADCEx_MultiModeStart_DMA() function must be used.
* @param hadc ADC handle
* @param pData Destination Buffer address.
* @param Length Number of data to be transferred from ADC peripheral to memory
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length)
{
HAL_StatusTypeDef tmp_hal_status;
#if defined(ADC_MULTIMODE_SUPPORT)
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Perform ADC enable and conversion start if no conversion is on going */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Process locked */
__HAL_LOCK(hadc);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Ensure that multimode regular conversions are not enabled. */
/* Otherwise, dedicated API HAL_ADCEx_MultiModeStart_DMA() must be used. */
if ((ADC_IS_INDEPENDENT(hadc) != RESET)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
#endif /* ADC_MULTIMODE_SUPPORT */
{
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
/* Start conversion if ADC is effectively enabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
HAL_ADC_STATE_REG_BUSY);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
- if ADC instance is master or if multimode feature is not available
- if multimode setting is disabled (ADC instance slave in independent mode) */
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
)
{
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#endif
/* Check if a conversion is on going on ADC group injected */
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
{
/* Reset ADC error code fields related to regular conversions only */
CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
}
else
{
/* Reset all ADC error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
/* Set the DMA transfer complete callback */
hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
/* Set the DMA half transfer complete callback */
hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
/* Set the DMA error callback */
hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
/* Manage ADC and DMA start: ADC overrun interruption, DMA start, */
/* ADC start (in case of SW start): */
/* Clear regular group conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC */
/* operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* With DMA, overrun event is always considered as an error even if
hadc->Init.Overrun is set to ADC_OVR_DATA_OVERWRITTEN. Therefore,
ADC_IT_OVR is enabled. */
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
/* Enable ADC DMA mode */
SET_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN);
/* Start the DMA channel */
tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
}
#if defined(ADC_MULTIMODE_SUPPORT)
else
{
tmp_hal_status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
#endif
}
else
{
tmp_hal_status = HAL_BUSY;
}
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Stop ADC conversion of regular group (and injected group in
* case of auto_injection mode), disable ADC DMA transfer, disable
* ADC peripheral.
* @note: ADC peripheral disable is forcing stop of potential
* conversion on ADC group injected. If ADC group injected is under use, it
* should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
* @note Case of multimode enabled (when multimode feature is available):
* HAL_ADC_Stop_DMA() function is dedicated to single-ADC mode only.
* For multimode, the dedicated HAL_ADCEx_MultiModeStop_DMA() API must be used.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential ADC group regular conversion on going */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* Disable ADC DMA (ADC DMA configuration of continuous requests is kept) */
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN);
/* Disable the DMA channel (in case of DMA in circular mode or stop */
/* while DMA transfer is on going) */
if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
{
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
/* Check if DMA channel effectively disabled */
if (tmp_hal_status != HAL_OK)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
}
}
/* Disable ADC overrun interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
/* 2. Disable the ADC peripheral */
/* Update "tmp_hal_status" only if DMA channel disabling passed, */
/* to keep in memory a potential failing status. */
if (tmp_hal_status == HAL_OK)
{
tmp_hal_status = ADC_Disable(hadc);
}
else
{
(void)ADC_Disable(hadc);
}
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Get ADC regular group conversion result.
* @note Reading register DR automatically clears ADC flag EOC
* (ADC group regular end of unitary conversion).
* @note This function does not clear ADC flag EOS
* (ADC group regular end of sequence conversion).
* Occurrence of flag EOS rising:
* - If sequencer is composed of 1 rank, flag EOS is equivalent
* to flag EOC.
* - If sequencer is composed of several ranks, during the scan
* sequence flag EOC only is raised, at the end of the scan sequence
* both flags EOC and EOS are raised.
* To clear this flag, either use function:
* in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
* model polling: @ref HAL_ADC_PollForConversion()
* or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
* @param hadc ADC handle
* @retval ADC group regular conversion data
*/
uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef *hadc)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Note: EOC flag is not cleared here by software because automatically */
/* cleared by hardware when reading register DR. */
/* Return ADC converted value */
return hadc->Instance->DR;
}
/**
* @brief Start ADC conversion sampling phase of regular group
* @note: This function should only be called to start sampling when
* - @ref ADC_SAMPLING_MODE_TRIGGER_CONTROLED sampling
* mode has been selected
* - @ref ADC_SOFTWARE_START has been selected as trigger source
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_StartSampling(ADC_HandleTypeDef *hadc)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Start sampling */
SET_BIT(hadc->Instance->CFGR2, ADC_CFGR2_SWTRIG);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop ADC conversion sampling phase of regular group and start conversion
* @note: This function should only be called to stop sampling when
* - @ref ADC_SAMPLING_MODE_TRIGGER_CONTROLED sampling
* mode has been selected
* - @ref ADC_SOFTWARE_START has been selected as trigger source
* - after sampling has been started using @ref HAL_ADC_StartSampling.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADC_StopSampling(ADC_HandleTypeDef *hadc)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Start sampling */
CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_SWTRIG);
/* Return function status */
return HAL_OK;
}
/**
* @brief Handle ADC interrupt request.
* @param hadc ADC handle
* @retval None
*/
void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc)
{
uint32_t overrun_error = 0UL; /* flag set if overrun occurrence has to be considered as an error */
uint32_t tmp_isr = hadc->Instance->ISR;
uint32_t tmp_ier = hadc->Instance->IER;
uint32_t tmp_adc_inj_is_trigger_source_sw_start;
uint32_t tmp_adc_reg_is_trigger_source_sw_start;
uint32_t tmp_cfgr;
#if defined(ADC_MULTIMODE_SUPPORT)
const ADC_TypeDef *tmpADC_Master;
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
/* ========== Check End of Sampling flag for ADC group regular ========== */
if (((tmp_isr & ADC_FLAG_EOSMP) == ADC_FLAG_EOSMP) && ((tmp_ier & ADC_IT_EOSMP) == ADC_IT_EOSMP))
{
/* Update state machine on end of sampling status if not in error state */
if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
}
/* End Of Sampling callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->EndOfSamplingCallback(hadc);
#else
HAL_ADCEx_EndOfSamplingCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear regular group conversion flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
}
/* ====== Check ADC group regular end of unitary conversion sequence conversions ===== */
if ((((tmp_isr & ADC_FLAG_EOC) == ADC_FLAG_EOC) && ((tmp_ier & ADC_IT_EOC) == ADC_IT_EOC)) ||
(((tmp_isr & ADC_FLAG_EOS) == ADC_FLAG_EOS) && ((tmp_ier & ADC_IT_EOS) == ADC_IT_EOS)))
{
/* Update state machine on conversion status if not in error state */
if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
}
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going */
/* to disable interruption. */
if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
{
/* Get relevant register CFGR in ADC instance of ADC master or slave */
/* in function of multimode state (for devices with multimode */
/* available). */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
)
{
/* check CONT bit directly in handle ADC CFGR register */
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
}
else
{
/* else need to check Master ADC CONT bit */
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
}
#else
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
#endif
/* Carry on if continuous mode is disabled */
if (READ_BIT(tmp_cfgr, ADC_CFGR_CONT) != ADC_CFGR_CONT)
{
/* If End of Sequence is reached, disable interrupts */
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
{
/* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit */
/* ADSTART==0 (no conversion on going) */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Disable ADC end of sequence conversion interrupt */
/* Note: Overrun interrupt was enabled with EOC interrupt in */
/* HAL_Start_IT(), but is not disabled here because can be used */
/* by overrun IRQ process below. */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
else
{
/* Change ADC state to error state */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
}
}
}
}
/* Conversion complete callback */
/* Note: Into callback function "HAL_ADC_ConvCpltCallback()", */
/* to determine if conversion has been triggered from EOC or EOS, */
/* possibility to use: */
/* " if ( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) " */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ConvCpltCallback(hadc);
#else
HAL_ADC_ConvCpltCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear regular group conversion flag */
/* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of */
/* conversion flags clear induces the release of the preserved data.*/
/* Therefore, if the preserved data value is needed, it must be */
/* read preliminarily into HAL_ADC_ConvCpltCallback(). */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
}
/* ====== Check ADC group injected end of unitary conversion sequence conversions ===== */
if ((((tmp_isr & ADC_FLAG_JEOC) == ADC_FLAG_JEOC) && ((tmp_ier & ADC_IT_JEOC) == ADC_IT_JEOC)) ||
(((tmp_isr & ADC_FLAG_JEOS) == ADC_FLAG_JEOS) && ((tmp_ier & ADC_IT_JEOS) == ADC_IT_JEOS)))
{
/* Update state machine on conversion status if not in error state */
if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
}
/* Retrieve ADC configuration */
tmp_adc_inj_is_trigger_source_sw_start = LL_ADC_INJ_IsTriggerSourceSWStart(hadc->Instance);
tmp_adc_reg_is_trigger_source_sw_start = LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance);
/* Get relevant register CFGR in ADC instance of ADC master or slave */
/* in function of multimode state (for devices with multimode */
/* available). */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
)
{
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
}
else
{
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
}
#else
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
#endif
/* Disable interruption if no further conversion upcoming by injected */
/* external trigger or by automatic injected conversion with regular */
/* group having no further conversion upcoming (same conditions as */
/* regular group interruption disabling above), */
/* and if injected scan sequence is completed. */
if (tmp_adc_inj_is_trigger_source_sw_start != 0UL)
{
if ((READ_BIT(tmp_cfgr, ADC_CFGR_JAUTO) == 0UL) ||
((tmp_adc_reg_is_trigger_source_sw_start != 0UL) &&
(READ_BIT(tmp_cfgr, ADC_CFGR_CONT) == 0UL)))
{
/* If End of Sequence is reached, disable interrupts */
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS))
{
/* Particular case if injected contexts queue is enabled: */
/* when the last context has been fully processed, JSQR is reset */
/* by the hardware. Even if no injected conversion is planned to come */
/* (queue empty, triggers are ignored), it can start again */
/* immediately after setting a new context (JADSTART is still set). */
/* Therefore, state of HAL ADC injected group is kept to busy. */
if (READ_BIT(tmp_cfgr, ADC_CFGR_JQM) == 0UL)
{
/* Allowed to modify bits ADC_IT_JEOC/ADC_IT_JEOS only if bit */
/* JADSTART==0 (no conversion on going) */
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Disable ADC end of sequence conversion interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC | ADC_IT_JEOS);
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
if ((hadc->State & HAL_ADC_STATE_REG_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
else
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
}
}
}
}
}
/* Injected Conversion complete callback */
/* Note: HAL_ADCEx_InjectedConvCpltCallback can resort to
if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOS)) or
if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOC)) to determine whether
interruption has been triggered by end of conversion or end of
sequence. */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->InjectedConvCpltCallback(hadc);
#else
HAL_ADCEx_InjectedConvCpltCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear injected group conversion flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC | ADC_FLAG_JEOS);
}
/* ========== Check Analog watchdog 1 flag ========== */
if (((tmp_isr & ADC_FLAG_AWD1) == ADC_FLAG_AWD1) && ((tmp_ier & ADC_IT_AWD1) == ADC_IT_AWD1))
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
/* Level out of window 1 callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->LevelOutOfWindowCallback(hadc);
#else
HAL_ADC_LevelOutOfWindowCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
}
/* ========== Check analog watchdog 2 flag ========== */
if (((tmp_isr & ADC_FLAG_AWD2) == ADC_FLAG_AWD2) && ((tmp_ier & ADC_IT_AWD2) == ADC_IT_AWD2))
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
/* Level out of window 2 callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->LevelOutOfWindow2Callback(hadc);
#else
HAL_ADCEx_LevelOutOfWindow2Callback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
}
/* ========== Check analog watchdog 3 flag ========== */
if (((tmp_isr & ADC_FLAG_AWD3) == ADC_FLAG_AWD3) && ((tmp_ier & ADC_IT_AWD3) == ADC_IT_AWD3))
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
/* Level out of window 3 callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->LevelOutOfWindow3Callback(hadc);
#else
HAL_ADCEx_LevelOutOfWindow3Callback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
}
/* ========== Check Overrun flag ========== */
if (((tmp_isr & ADC_FLAG_OVR) == ADC_FLAG_OVR) && ((tmp_ier & ADC_IT_OVR) == ADC_IT_OVR))
{
/* If overrun is set to overwrite previous data (default setting), */
/* overrun event is not considered as an error. */
/* (cf ref manual "Managing conversions without using the DMA and without */
/* overrun ") */
/* Exception for usage with DMA overrun event always considered as an */
/* error. */
if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
{
overrun_error = 1UL;
}
else
{
/* Check DMA configuration */
#if defined(ADC_MULTIMODE_SUPPORT)
if (tmp_multimode_config != LL_ADC_MULTI_INDEPENDENT)
{
/* Multimode (when feature is available) is enabled,
Common Control Register MDMA bits must be checked. */
if (LL_ADC_GetMultiDMATransfer(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DMA_EACH_ADC)
{
overrun_error = 1UL;
}
}
else
#endif
{
/* Multimode not set or feature not available or ADC independent */
if ((hadc->Instance->CFGR & ADC_CFGR_DMAEN) != 0UL)
{
overrun_error = 1UL;
}
}
}
if (overrun_error == 1UL)
{
/* Change ADC state to error state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
/* Set ADC error code to overrun */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
/* Error callback */
/* Note: In case of overrun, ADC conversion data is preserved until */
/* flag OVR is reset. */
/* Therefore, old ADC conversion data can be retrieved in */
/* function "HAL_ADC_ErrorCallback()". */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ErrorCallback(hadc);
#else
HAL_ADC_ErrorCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
/* Clear ADC overrun flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
}
/* ========== Check Injected context queue overflow flag ========== */
if (((tmp_isr & ADC_FLAG_JQOVF) == ADC_FLAG_JQOVF) && ((tmp_ier & ADC_IT_JQOVF) == ADC_IT_JQOVF))
{
/* Change ADC state to overrun state */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF);
/* Set ADC error code to Injected context queue overflow */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
/* Clear the Injected context queue overflow flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JQOVF);
/* Injected context queue overflow callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->InjectedQueueOverflowCallback(hadc);
#else
HAL_ADCEx_InjectedQueueOverflowCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
}
/**
* @brief Conversion complete callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_ConvCpltCallback must be implemented in the user file.
*/
}
/**
* @brief Conversion DMA half-transfer callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
*/
}
/**
* @brief Analog watchdog 1 callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
*/
}
/**
* @brief ADC error callback in non-blocking mode
* (ADC conversion with interruption or transfer by DMA).
* @note In case of error due to overrun when using ADC with DMA transfer
* (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
* - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
* - If needed, restart a new ADC conversion using function
* "HAL_ADC_Start_DMA()"
* (this function is also clearing overrun flag)
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_ErrorCallback must be implemented in the user file.
*/
}
/**
* @}
*/
/** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure channels on regular group
(+) Configure the analog watchdog
@endverbatim
* @{
*/
/**
* @brief Configure a channel to be assigned to ADC group regular.
* @note In case of usage of internal measurement channels:
* Vbat/VrefInt/TempSensor.
* These internal paths can be disabled using function
* HAL_ADC_DeInit().
* @note Possibility to update parameters on the fly:
* This function initializes channel into ADC group regular,
* following calls to this function can be used to reconfigure
* some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
* without resetting the ADC.
* The setting of these parameters is conditioned to ADC state:
* Refer to comments of structure "ADC_ChannelConfTypeDef".
* @param hadc ADC handle
* @param sConfig Structure of ADC channel assigned to ADC group regular.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
uint32_t tmpOffsetShifted;
uint32_t tmp_config_internal_channel;
__IO uint32_t wait_loop_index = 0UL;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime));
assert_param(IS_ADC_SINGLE_DIFFERENTIAL(sConfig->SingleDiff));
assert_param(IS_ADC_OFFSET_NUMBER(sConfig->OffsetNumber));
assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), sConfig->Offset));
/* if ROVSE is set, the value of the OFFSETy_EN bit in ADCx_OFRy register is
ignored (considered as reset) */
assert_param(!((sConfig->OffsetNumber != ADC_OFFSET_NONE) && (hadc->Init.OversamplingMode == ENABLE)));
/* Verification of channel number */
if (sConfig->SingleDiff != ADC_DIFFERENTIAL_ENDED)
{
assert_param(IS_ADC_CHANNEL(hadc, sConfig->Channel));
}
else
{
assert_param(IS_ADC_DIFF_CHANNEL(hadc, sConfig->Channel));
}
/* Process locked */
__HAL_LOCK(hadc);
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular group: */
/* - Channel number */
/* - Channel rank */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* Set ADC group regular sequence: channel on the selected scan sequence rank */
LL_ADC_REG_SetSequencerRanks(hadc->Instance, sConfig->Rank, sConfig->Channel);
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular group: */
/* - Channel sampling time */
/* - Channel offset */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
/* Manage specific case of sampling time 3.5 cycles replacing 2.5 cyles */
if (sConfig->SamplingTime == ADC_SAMPLETIME_3CYCLES_5)
{
/* Set sampling time of the selected ADC channel */
LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfig->Channel, LL_ADC_SAMPLINGTIME_2CYCLES_5);
/* Set ADC sampling time common configuration */
LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_3C5_REPL_2C5);
}
else
{
/* Set sampling time of the selected ADC channel */
LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfig->Channel, sConfig->SamplingTime);
/* Set ADC sampling time common configuration */
LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_DEFAULT);
}
/* Configure the offset: offset enable/disable, channel, offset value */
/* Shift the offset with respect to the selected ADC resolution. */
/* Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 */
tmpOffsetShifted = ADC_OFFSET_SHIFT_RESOLUTION(hadc, (uint32_t)sConfig->Offset);
if (sConfig->OffsetNumber != ADC_OFFSET_NONE)
{
/* Set ADC selected offset number */
LL_ADC_SetOffset(hadc->Instance, sConfig->OffsetNumber, sConfig->Channel, tmpOffsetShifted);
assert_param(IS_ADC_OFFSET_SIGN(sConfig->OffsetSign));
assert_param(IS_FUNCTIONAL_STATE(sConfig->OffsetSaturation));
/* Set ADC selected offset sign & saturation */
LL_ADC_SetOffsetSign(hadc->Instance, sConfig->OffsetNumber, sConfig->OffsetSign);
LL_ADC_SetOffsetSaturation(hadc->Instance, sConfig->OffsetNumber, (sConfig->OffsetSaturation == ENABLE) ? LL_ADC_OFFSET_SATURATION_ENABLE : LL_ADC_OFFSET_SATURATION_DISABLE);
}
else
{
/* Scan each offset register to check if the selected channel is targeted. */
/* If this is the case, the corresponding offset number is disabled. */
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_1))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfig->Channel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_1, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_2))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfig->Channel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_2, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_3))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfig->Channel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_3, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_4))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfig->Channel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_4, LL_ADC_OFFSET_DISABLE);
}
}
}
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated only when ADC is disabled: */
/* - Single or differential mode */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
/* Set mode single-ended or differential input of the selected ADC channel */
LL_ADC_SetChannelSingleDiff(hadc->Instance, sConfig->Channel, sConfig->SingleDiff);
/* Configuration of differential mode */
if (sConfig->SingleDiff == ADC_DIFFERENTIAL_ENDED)
{
/* Set sampling time of the selected ADC channel */
/* Note: ADC channel number masked with value "0x1F" to ensure shift value within 32 bits range */
LL_ADC_SetChannelSamplingTime(hadc->Instance,
(uint32_t)(__LL_ADC_DECIMAL_NB_TO_CHANNEL((__LL_ADC_CHANNEL_TO_DECIMAL_NB((uint32_t)sConfig->Channel) + 1UL) & 0x1FUL)),
sConfig->SamplingTime);
}
}
/* Management of internal measurement channels: Vbat/VrefInt/TempSensor. */
/* If internal channel selected, enable dedicated internal buffers and */
/* paths. */
/* Note: these internal measurement paths can be disabled using */
/* HAL_ADC_DeInit(). */
if (__LL_ADC_IS_CHANNEL_INTERNAL(sConfig->Channel))
{
tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
/* If the requested internal measurement path has already been enabled, */
/* bypass the configuration processing. */
if (((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR_ADC1) || (sConfig->Channel == ADC_CHANNEL_TEMPSENSOR_ADC5))
&& ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL))
{
if (ADC_TEMPERATURE_SENSOR_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel);
/* Delay for temperature sensor stabilization time */
/* Wait loop initialization and execution */
/* Note: Variable divided by 2 to compensate partially */
/* CPU processing cycles, scaling in us split to not */
/* exceed 32 bits register capacity and handle low frequency. */
wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
while (wait_loop_index != 0UL)
{
wait_loop_index--;
}
}
}
else if ((sConfig->Channel == ADC_CHANNEL_VBAT) && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VBAT) == 0UL))
{
if (ADC_BATTERY_VOLTAGE_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_VBAT | tmp_config_internal_channel);
}
}
else if ((sConfig->Channel == ADC_CHANNEL_VREFINT)
&& ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
{
if (ADC_VREFINT_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel);
}
}
else
{
/* nothing to do */
}
}
}
/* If a conversion is on going on regular group, no update on regular */
/* channel could be done on neither of the channel configuration structure */
/* parameters. */
else
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
tmp_hal_status = HAL_ERROR;
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Configure the analog watchdog.
* @note Possibility to update parameters on the fly:
* This function initializes the selected analog watchdog, successive
* calls to this function can be used to reconfigure some parameters
* of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
* the ADC.
* The setting of these parameters is conditioned to ADC state.
* For parameters constraints, see comments of structure
* "ADC_AnalogWDGConfTypeDef".
* @note On this STM32 series, analog watchdog thresholds can be modified
* while ADC conversion is on going.
* In this case, some constraints must be taken into account:
* the programmed threshold values are effective from the next
* ADC EOC (end of unitary conversion).
* Considering that registers write delay may happen due to
* bus activity, this might cause an uncertainty on the
* effective timing of the new programmed threshold values.
* @param hadc ADC handle
* @param AnalogWDGConfig Structure of ADC analog watchdog configuration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDGConfTypeDef *AnalogWDGConfig)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
uint32_t tmpAWDHighThresholdShifted;
uint32_t tmpAWDLowThresholdShifted;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_ANALOG_WATCHDOG_NUMBER(AnalogWDGConfig->WatchdogNumber));
assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(AnalogWDGConfig->WatchdogMode));
assert_param(IS_ADC_ANALOG_WATCHDOG_FILTERING_MODE(AnalogWDGConfig->FilteringConfig));
assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) ||
(AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) ||
(AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC))
{
assert_param(IS_ADC_CHANNEL(hadc, AnalogWDGConfig->Channel));
}
/* Verify thresholds range */
if (hadc->Init.OversamplingMode == ENABLE)
{
/* Case of oversampling enabled: depending on ratio and shift configuration,
analog watchdog thresholds can be higher than ADC resolution.
Verify if thresholds are within maximum thresholds range. */
assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, AnalogWDGConfig->HighThreshold));
assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, AnalogWDGConfig->LowThreshold));
}
else
{
/* Verify if thresholds are within the selected ADC resolution */
assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->HighThreshold));
assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->LowThreshold));
}
/* Process locked */
__HAL_LOCK(hadc);
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on ADC groups regular and injected: */
/* - Analog watchdog channels */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
/* Analog watchdog configuration */
if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
{
/* Configuration of analog watchdog: */
/* - Set the analog watchdog enable mode: one or overall group of */
/* channels, on groups regular and-or injected. */
switch (AnalogWDGConfig->WatchdogMode)
{
case ADC_ANALOGWATCHDOG_SINGLE_REG:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel,
LL_ADC_GROUP_REGULAR));
break;
case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel,
LL_ADC_GROUP_INJECTED));
break;
case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel,
LL_ADC_GROUP_REGULAR_INJECTED));
break;
case ADC_ANALOGWATCHDOG_ALL_REG:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG);
break;
case ADC_ANALOGWATCHDOG_ALL_INJEC:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_INJ);
break;
case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG_INJ);
break;
default: /* ADC_ANALOGWATCHDOG_NONE */
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
break;
}
/* Set the filtering configuration */
MODIFY_REG(hadc->Instance->TR1,
ADC_TR1_AWDFILT,
AnalogWDGConfig->FilteringConfig);
/* Update state, clear previous result related to AWD1 */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD1);
/* Clear flag ADC analog watchdog */
/* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready */
/* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent() */
/* (in case left enabled by previous ADC operations). */
LL_ADC_ClearFlag_AWD1(hadc->Instance);
/* Configure ADC analog watchdog interrupt */
if (AnalogWDGConfig->ITMode == ENABLE)
{
LL_ADC_EnableIT_AWD1(hadc->Instance);
}
else
{
LL_ADC_DisableIT_AWD1(hadc->Instance);
}
}
/* Case of ADC_ANALOGWATCHDOG_2 or ADC_ANALOGWATCHDOG_3 */
else
{
switch (AnalogWDGConfig->WatchdogMode)
{
case ADC_ANALOGWATCHDOG_SINGLE_REG:
case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
/* Update AWD by bitfield to keep the possibility to monitor */
/* several channels by successive calls of this function. */
if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
{
SET_BIT(hadc->Instance->AWD2CR, (1UL << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(AnalogWDGConfig->Channel) & 0x1FUL)));
}
else
{
SET_BIT(hadc->Instance->AWD3CR, (1UL << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(AnalogWDGConfig->Channel) & 0x1FUL)));
}
break;
case ADC_ANALOGWATCHDOG_ALL_REG:
case ADC_ANALOGWATCHDOG_ALL_INJEC:
case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, AnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_ALL_CHANNELS_REG_INJ);
break;
default: /* ADC_ANALOGWATCHDOG_NONE */
LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, AnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_DISABLE);
break;
}
if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
{
/* Update state, clear previous result related to AWD2 */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD2);
/* Clear flag ADC analog watchdog */
/* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready */
/* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent() */
/* (in case left enabled by previous ADC operations). */
LL_ADC_ClearFlag_AWD2(hadc->Instance);
/* Configure ADC analog watchdog interrupt */
if (AnalogWDGConfig->ITMode == ENABLE)
{
LL_ADC_EnableIT_AWD2(hadc->Instance);
}
else
{
LL_ADC_DisableIT_AWD2(hadc->Instance);
}
}
/* (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_3) */
else
{
/* Update state, clear previous result related to AWD3 */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD3);
/* Clear flag ADC analog watchdog */
/* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready */
/* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent() */
/* (in case left enabled by previous ADC operations). */
LL_ADC_ClearFlag_AWD3(hadc->Instance);
/* Configure ADC analog watchdog interrupt */
if (AnalogWDGConfig->ITMode == ENABLE)
{
LL_ADC_EnableIT_AWD3(hadc->Instance);
}
else
{
LL_ADC_DisableIT_AWD3(hadc->Instance);
}
}
}
}
/* Analog watchdog thresholds configuration */
if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
{
/* Shift the offset with respect to the selected ADC resolution: */
/* Thresholds have to be left-aligned on bit 11, the LSB (right bits) */
/* are set to 0. */
tmpAWDHighThresholdShifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->HighThreshold);
tmpAWDLowThresholdShifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->LowThreshold);
}
/* Case of ADC_ANALOGWATCHDOG_2 and ADC_ANALOGWATCHDOG_3 */
else
{
/* Shift the offset with respect to the selected ADC resolution: */
/* Thresholds have to be left-aligned on bit 7, the LSB (right bits) */
/* are set to 0. */
tmpAWDHighThresholdShifted = ADC_AWD23THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->HighThreshold);
tmpAWDLowThresholdShifted = ADC_AWD23THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->LowThreshold);
}
/* Set ADC analog watchdog thresholds value of both thresholds high and low */
LL_ADC_ConfigAnalogWDThresholds(hadc->Instance, AnalogWDGConfig->WatchdogNumber, tmpAWDHighThresholdShifted,
tmpAWDLowThresholdShifted);
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @}
*/
/** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
* @brief ADC Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral state and errors functions #####
===============================================================================
[..]
This subsection provides functions to get in run-time the status of the
peripheral.
(+) Check the ADC state
(+) Check the ADC error code
@endverbatim
* @{
*/
/**
* @brief Return the ADC handle state.
* @note ADC state machine is managed by bitfields, ADC status must be
* compared with states bits.
* For example:
* " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_REG_BUSY) != 0UL) "
* " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "
* @param hadc ADC handle
* @retval ADC handle state (bitfield on 32 bits)
*/
uint32_t HAL_ADC_GetState(ADC_HandleTypeDef *hadc)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Return ADC handle state */
return hadc->State;
}
/**
* @brief Return the ADC error code.
* @param hadc ADC handle
* @retval ADC error code (bitfield on 32 bits)
*/
uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
return hadc->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup ADC_Private_Functions ADC Private Functions
* @{
*/
/**
* @brief Stop ADC conversion.
* @param hadc ADC handle
* @param ConversionGroup ADC group regular and/or injected.
* This parameter can be one of the following values:
* @arg @ref ADC_REGULAR_GROUP ADC regular conversion type.
* @arg @ref ADC_INJECTED_GROUP ADC injected conversion type.
* @arg @ref ADC_REGULAR_INJECTED_GROUP ADC regular and injected conversion type.
* @retval HAL status.
*/
HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef *hadc, uint32_t ConversionGroup)
{
uint32_t tickstart;
uint32_t Conversion_Timeout_CPU_cycles = 0UL;
uint32_t conversion_group_reassigned = ConversionGroup;
uint32_t tmp_ADC_CR_ADSTART_JADSTART;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_CONVERSION_GROUP(ConversionGroup));
/* Verification if ADC is not already stopped (on regular and injected */
/* groups) to bypass this function if not needed. */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((tmp_adc_is_conversion_on_going_regular != 0UL)
|| (tmp_adc_is_conversion_on_going_injected != 0UL)
)
{
/* Particular case of continuous auto-injection mode combined with */
/* auto-delay mode. */
/* In auto-injection mode, regular group stop ADC_CR_ADSTP is used (not */
/* injected group stop ADC_CR_JADSTP). */
/* Procedure to be followed: Wait until JEOS=1, clear JEOS, set ADSTP=1 */
/* (see reference manual). */
if (((hadc->Instance->CFGR & ADC_CFGR_JAUTO) != 0UL)
&& (hadc->Init.ContinuousConvMode == ENABLE)
&& (hadc->Init.LowPowerAutoWait == ENABLE)
)
{
/* Use stop of regular group */
conversion_group_reassigned = ADC_REGULAR_GROUP;
/* Wait until JEOS=1 (maximum Timeout: 4 injected conversions) */
while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS) == 0UL)
{
if (Conversion_Timeout_CPU_cycles >= (ADC_CONVERSION_TIME_MAX_CPU_CYCLES * 4UL))
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
Conversion_Timeout_CPU_cycles ++;
}
/* Clear JEOS */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOS);
}
/* Stop potential conversion on going on ADC group regular */
if (conversion_group_reassigned != ADC_INJECTED_GROUP)
{
/* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
{
if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
{
/* Stop ADC group regular conversion */
LL_ADC_REG_StopConversion(hadc->Instance);
}
}
}
/* Stop potential conversion on going on ADC group injected */
if (conversion_group_reassigned != ADC_REGULAR_GROUP)
{
/* Software is allowed to set JADSTP only when JADSTART=1 and ADDIS=0 */
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL)
{
if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
{
/* Stop ADC group injected conversion */
LL_ADC_INJ_StopConversion(hadc->Instance);
}
}
}
/* Selection of start and stop bits with respect to the regular or injected group */
switch (conversion_group_reassigned)
{
case ADC_REGULAR_INJECTED_GROUP:
tmp_ADC_CR_ADSTART_JADSTART = (ADC_CR_ADSTART | ADC_CR_JADSTART);
break;
case ADC_INJECTED_GROUP:
tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_JADSTART;
break;
/* Case ADC_REGULAR_GROUP only*/
default:
tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_ADSTART;
break;
}
/* Wait for conversion effectively stopped */
tickstart = HAL_GetTick();
while ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
{
if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
if ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
}
}
}
/* Return HAL status */
return HAL_OK;
}
/**
* @brief Enable the selected ADC.
* @note Prerequisite condition to use this function: ADC must be disabled
* and voltage regulator must be enabled (done into HAL_ADC_Init()).
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc)
{
uint32_t tickstart;
/* ADC enable and wait for ADC ready (in case of ADC is disabled or */
/* enabling phase not yet completed: flag ADC ready not yet set). */
/* Timeout implemented to not be stuck if ADC cannot be enabled (possible */
/* causes: ADC clock not running, ...). */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
/* Check if conditions to enable the ADC are fulfilled */
if ((hadc->Instance->CR & (ADC_CR_ADCAL | ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART
| ADC_CR_ADDIS | ADC_CR_ADEN)) != 0UL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
/* Enable the ADC peripheral */
LL_ADC_Enable(hadc->Instance);
/* Wait for ADC effectively enabled */
tickstart = HAL_GetTick();
while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
{
/* If ADEN bit is set less than 4 ADC clock cycles after the ADCAL bit
has been cleared (after a calibration), ADEN bit is reset by the
calibration logic.
The workaround is to continue setting ADEN until ADRDY is becomes 1.
Additionally, ADC_ENABLE_TIMEOUT is defined to encompass this
4 ADC clock cycle duration */
/* Note: Test of ADC enabled required due to hardware constraint to */
/* not enable ADC if already enabled. */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
LL_ADC_Enable(hadc->Instance);
}
if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
}
}
}
/* Return HAL status */
return HAL_OK;
}
/**
* @brief Disable the selected ADC.
* @note Prerequisite condition to use this function: ADC conversions must be
* stopped.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef *hadc)
{
uint32_t tickstart;
const uint32_t tmp_adc_is_disable_on_going = LL_ADC_IsDisableOngoing(hadc->Instance);
/* Verification if ADC is not already disabled: */
/* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already */
/* disabled. */
if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
&& (tmp_adc_is_disable_on_going == 0UL)
)
{
/* Check if conditions to disable the ADC are fulfilled */
if ((hadc->Instance->CR & (ADC_CR_JADSTART | ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN)
{
/* Disable the ADC peripheral */
LL_ADC_Disable(hadc->Instance);
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOSMP | ADC_FLAG_RDY));
}
else
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
/* Wait for ADC effectively disabled */
/* Get tick count */
tickstart = HAL_GetTick();
while ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
{
if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
if ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Set ADC error code to ADC peripheral internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
return HAL_ERROR;
}
}
}
}
/* Return HAL status */
return HAL_OK;
}
/**
* @brief DMA transfer complete callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
{
/* Retrieve ADC handle corresponding to current DMA handle */
ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Update state machine on conversion status if not in error state */
if ((hadc->State & (HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) == 0UL)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going */
/* to disable interruption. */
/* Is it the end of the regular sequence ? */
if ((hadc->Instance->ISR & ADC_FLAG_EOS) != 0UL)
{
/* Are conversions software-triggered ? */
if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
{
/* Is CONT bit set ? */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_CONT) == 0UL)
{
/* CONT bit is not set, no more conversions expected */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
}
}
else
{
/* DMA End of Transfer interrupt was triggered but conversions sequence
is not over. If DMACFG is set to 0, conversions are stopped. */
if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMACFG) == 0UL)
{
/* DMACFG bit is not set, conversions are stopped. */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
}
/* Conversion complete callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ConvCpltCallback(hadc);
#else
HAL_ADC_ConvCpltCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
else /* DMA and-or internal error occurred */
{
if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
{
/* Call HAL ADC Error Callback function */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ErrorCallback(hadc);
#else
HAL_ADC_ErrorCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
else
{
/* Call ADC DMA error callback */
hadc->DMA_Handle->XferErrorCallback(hdma);
}
}
}
/**
* @brief DMA half transfer complete callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
{
/* Retrieve ADC handle corresponding to current DMA handle */
ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Half conversion callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ConvHalfCpltCallback(hadc);
#else
HAL_ADC_ConvHalfCpltCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
/**
* @brief DMA error callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void ADC_DMAError(DMA_HandleTypeDef *hdma)
{
/* Retrieve ADC handle corresponding to current DMA handle */
ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
/* Set ADC error code to DMA error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
/* Error callback */
#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
hadc->ErrorCallback(hadc);
#else
HAL_ADC_ErrorCallback(hadc);
#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
}
/**
* @}
*/
#endif /* HAL_ADC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 145,837 |
C
| 38.597611 | 182 | 0.596988 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_pcd.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_pcd.c
* @author MCD Application Team
* @brief PCD HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral Control functions
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The PCD HAL driver can be used as follows:
(#) Declare a PCD_HandleTypeDef handle structure, for example:
PCD_HandleTypeDef hpcd;
(#) Fill parameters of Init structure in HCD handle
(#) Call HAL_PCD_Init() API to initialize the PCD peripheral (Core, Device core, ...)
(#) Initialize the PCD low level resources through the HAL_PCD_MspInit() API:
(##) Enable the PCD/USB Low Level interface clock using
(+++) __HAL_RCC_USB_CLK_ENABLE(); For USB Device only FS peripheral
(##) Initialize the related GPIO clocks
(##) Configure PCD pin-out
(##) Configure PCD NVIC interrupt
(#)Associate the Upper USB device stack to the HAL PCD Driver:
(##) hpcd.pData = pdev;
(#)Enable PCD transmission and reception:
(##) HAL_PCD_Start();
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup PCD PCD
* @brief PCD HAL module driver
* @{
*/
#ifdef HAL_PCD_MODULE_ENABLED
#if defined (USB)
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup PCD_Private_Macros PCD Private Macros
* @{
*/
#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b))
/**
* @}
*/
/* Private functions prototypes ----------------------------------------------*/
/** @defgroup PCD_Private_Functions PCD Private Functions
* @{
*/
static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd);
#if (USE_USB_DOUBLE_BUFFER == 1U)
static HAL_StatusTypeDef HAL_PCD_EP_DB_Transmit(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep, uint16_t wEPVal);
static uint16_t HAL_PCD_EP_DB_Receive(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep, uint16_t wEPVal);
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PCD_Exported_Functions PCD Exported Functions
* @{
*/
/** @defgroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
@endverbatim
* @{
*/
/**
* @brief Initializes the PCD according to the specified
* parameters in the PCD_InitTypeDef and initialize the associated handle.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd)
{
uint8_t i;
/* Check the PCD handle allocation */
if (hpcd == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance));
if (hpcd->State == HAL_PCD_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hpcd->Lock = HAL_UNLOCKED;
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->SOFCallback = HAL_PCD_SOFCallback;
hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback;
hpcd->ResetCallback = HAL_PCD_ResetCallback;
hpcd->SuspendCallback = HAL_PCD_SuspendCallback;
hpcd->ResumeCallback = HAL_PCD_ResumeCallback;
hpcd->ConnectCallback = HAL_PCD_ConnectCallback;
hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback;
hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback;
hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback;
hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback;
hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback;
hpcd->LPMCallback = HAL_PCDEx_LPM_Callback;
hpcd->BCDCallback = HAL_PCDEx_BCD_Callback;
if (hpcd->MspInitCallback == NULL)
{
hpcd->MspInitCallback = HAL_PCD_MspInit;
}
/* Init the low level hardware */
hpcd->MspInitCallback(hpcd);
#else
/* Init the low level hardware : GPIO, CLOCK, NVIC... */
HAL_PCD_MspInit(hpcd);
#endif /* (USE_HAL_PCD_REGISTER_CALLBACKS) */
}
hpcd->State = HAL_PCD_STATE_BUSY;
/* Disable the Interrupts */
__HAL_PCD_DISABLE(hpcd);
/* Init endpoints structures */
for (i = 0U; i < hpcd->Init.dev_endpoints; i++)
{
/* Init ep structure */
hpcd->IN_ep[i].is_in = 1U;
hpcd->IN_ep[i].num = i;
hpcd->IN_ep[i].tx_fifo_num = i;
/* Control until ep is activated */
hpcd->IN_ep[i].type = EP_TYPE_CTRL;
hpcd->IN_ep[i].maxpacket = 0U;
hpcd->IN_ep[i].xfer_buff = 0U;
hpcd->IN_ep[i].xfer_len = 0U;
}
for (i = 0U; i < hpcd->Init.dev_endpoints; i++)
{
hpcd->OUT_ep[i].is_in = 0U;
hpcd->OUT_ep[i].num = i;
/* Control until ep is activated */
hpcd->OUT_ep[i].type = EP_TYPE_CTRL;
hpcd->OUT_ep[i].maxpacket = 0U;
hpcd->OUT_ep[i].xfer_buff = 0U;
hpcd->OUT_ep[i].xfer_len = 0U;
}
/* Init Device */
(void)USB_DevInit(hpcd->Instance, hpcd->Init);
hpcd->USB_Address = 0U;
hpcd->State = HAL_PCD_STATE_READY;
/* Activate LPM */
if (hpcd->Init.lpm_enable == 1U)
{
(void)HAL_PCDEx_ActivateLPM(hpcd);
}
return HAL_OK;
}
/**
* @brief DeInitializes the PCD peripheral.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd)
{
/* Check the PCD handle allocation */
if (hpcd == NULL)
{
return HAL_ERROR;
}
hpcd->State = HAL_PCD_STATE_BUSY;
/* Stop Device */
if (USB_StopDevice(hpcd->Instance) != HAL_OK)
{
return HAL_ERROR;
}
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
if (hpcd->MspDeInitCallback == NULL)
{
hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware */
hpcd->MspDeInitCallback(hpcd);
#else
/* DeInit the low level hardware: CLOCK, NVIC.*/
HAL_PCD_MspDeInit(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
hpcd->State = HAL_PCD_STATE_RESET;
return HAL_OK;
}
/**
* @brief Initializes the PCD MSP.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitializes PCD MSP.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_MspDeInit could be implemented in the user file
*/
}
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
/**
* @brief Register a User USB PCD Callback
* To be used instead of the weak predefined callback
* @param hpcd USB PCD handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID
* @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID
* @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID
* @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID
* @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID
* @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID
* @arg @ref HAL_PCD_DISCONNECT_CB_ID OTG PCD Disconnect callback ID
* @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID
* @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd,
HAL_PCD_CallbackIDTypeDef CallbackID,
pPCD_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
switch (CallbackID)
{
case HAL_PCD_SOF_CB_ID :
hpcd->SOFCallback = pCallback;
break;
case HAL_PCD_SETUPSTAGE_CB_ID :
hpcd->SetupStageCallback = pCallback;
break;
case HAL_PCD_RESET_CB_ID :
hpcd->ResetCallback = pCallback;
break;
case HAL_PCD_SUSPEND_CB_ID :
hpcd->SuspendCallback = pCallback;
break;
case HAL_PCD_RESUME_CB_ID :
hpcd->ResumeCallback = pCallback;
break;
case HAL_PCD_CONNECT_CB_ID :
hpcd->ConnectCallback = pCallback;
break;
case HAL_PCD_DISCONNECT_CB_ID :
hpcd->DisconnectCallback = pCallback;
break;
case HAL_PCD_MSPINIT_CB_ID :
hpcd->MspInitCallback = pCallback;
break;
case HAL_PCD_MSPDEINIT_CB_ID :
hpcd->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hpcd->State == HAL_PCD_STATE_RESET)
{
switch (CallbackID)
{
case HAL_PCD_MSPINIT_CB_ID :
hpcd->MspInitCallback = pCallback;
break;
case HAL_PCD_MSPDEINIT_CB_ID :
hpcd->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister an USB PCD Callback
* USB PCD callabck is redirected to the weak predefined callback
* @param hpcd USB PCD handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID
* @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID
* @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID
* @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID
* @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID
* @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID
* @arg @ref HAL_PCD_DISCONNECT_CB_ID OTG PCD Disconnect callback ID
* @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID
* @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
/* Setup Legacy weak Callbacks */
if (hpcd->State == HAL_PCD_STATE_READY)
{
switch (CallbackID)
{
case HAL_PCD_SOF_CB_ID :
hpcd->SOFCallback = HAL_PCD_SOFCallback;
break;
case HAL_PCD_SETUPSTAGE_CB_ID :
hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback;
break;
case HAL_PCD_RESET_CB_ID :
hpcd->ResetCallback = HAL_PCD_ResetCallback;
break;
case HAL_PCD_SUSPEND_CB_ID :
hpcd->SuspendCallback = HAL_PCD_SuspendCallback;
break;
case HAL_PCD_RESUME_CB_ID :
hpcd->ResumeCallback = HAL_PCD_ResumeCallback;
break;
case HAL_PCD_CONNECT_CB_ID :
hpcd->ConnectCallback = HAL_PCD_ConnectCallback;
break;
case HAL_PCD_DISCONNECT_CB_ID :
hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback;
break;
case HAL_PCD_MSPINIT_CB_ID :
hpcd->MspInitCallback = HAL_PCD_MspInit;
break;
case HAL_PCD_MSPDEINIT_CB_ID :
hpcd->MspDeInitCallback = HAL_PCD_MspDeInit;
break;
default :
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hpcd->State == HAL_PCD_STATE_RESET)
{
switch (CallbackID)
{
case HAL_PCD_MSPINIT_CB_ID :
hpcd->MspInitCallback = HAL_PCD_MspInit;
break;
case HAL_PCD_MSPDEINIT_CB_ID :
hpcd->MspDeInitCallback = HAL_PCD_MspDeInit;
break;
default :
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD Data OUT Stage Callback
* To be used instead of the weak HAL_PCD_DataOutStageCallback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD Data OUT Stage Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd,
pPCD_DataOutStageCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->DataOutStageCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD Data OUT Stage Callback
* USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataOutStageCallback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; /* Legacy weak DataOutStageCallback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD Data IN Stage Callback
* To be used instead of the weak HAL_PCD_DataInStageCallback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD Data IN Stage Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd,
pPCD_DataInStageCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->DataInStageCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD Data IN Stage Callback
* USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataInStageCallback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; /* Legacy weak DataInStageCallback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD Iso OUT incomplete Callback
* To be used instead of the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD Iso OUT incomplete Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd,
pPCD_IsoOutIncpltCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->ISOOUTIncompleteCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD Iso OUT incomplete Callback
* USB PCD Iso OUT incomplete Callback is redirected
* to the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; /* Legacy weak ISOOUTIncompleteCallback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD Iso IN incomplete Callback
* To be used instead of the weak HAL_PCD_ISOINIncompleteCallback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD Iso IN incomplete Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd,
pPCD_IsoInIncpltCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->ISOINIncompleteCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD Iso IN incomplete Callback
* USB PCD Iso IN incomplete Callback is redirected
* to the weak HAL_PCD_ISOINIncompleteCallback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; /* Legacy weak ISOINIncompleteCallback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD BCD Callback
* To be used instead of the weak HAL_PCDEx_BCD_Callback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD BCD Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->BCDCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD BCD Callback
* USB BCD Callback is redirected to the weak HAL_PCDEx_BCD_Callback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; /* Legacy weak HAL_PCDEx_BCD_Callback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Register USB PCD LPM Callback
* To be used instead of the weak HAL_PCDEx_LPM_Callback() predefined callback
* @param hpcd PCD handle
* @param pCallback pointer to the USB PCD LPM Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->LPMCallback = pCallback;
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
/**
* @brief Unregister the USB PCD LPM Callback
* USB LPM Callback is redirected to the weak HAL_PCDEx_LPM_Callback() predefined callback
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hpcd);
if (hpcd->State == HAL_PCD_STATE_READY)
{
hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; /* Legacy weak HAL_PCDEx_LPM_Callback */
}
else
{
/* Update the error code */
hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hpcd);
return status;
}
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup PCD_Exported_Functions_Group2 Input and Output operation functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the PCD data
transfers.
@endverbatim
* @{
*/
/**
* @brief Start the USB device
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd)
{
__HAL_LOCK(hpcd);
__HAL_PCD_ENABLE(hpcd);
(void)USB_DevConnect(hpcd->Instance);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Stop the USB device.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd)
{
__HAL_LOCK(hpcd);
__HAL_PCD_DISABLE(hpcd);
(void)USB_DevDisconnect(hpcd->Instance);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief This function handles PCD interrupt request.
* @param hpcd PCD handle
* @retval HAL status
*/
void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd)
{
uint32_t wIstr = USB_ReadInterrupts(hpcd->Instance);
if ((wIstr & USB_ISTR_CTR) == USB_ISTR_CTR)
{
/* servicing of the endpoint correct transfer interrupt */
/* clear of the CTR flag into the sub */
(void)PCD_EP_ISR_Handler(hpcd);
return;
}
if ((wIstr & USB_ISTR_RESET) == USB_ISTR_RESET)
{
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET);
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->ResetCallback(hpcd);
#else
HAL_PCD_ResetCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
(void)HAL_PCD_SetAddress(hpcd, 0U);
return;
}
if ((wIstr & USB_ISTR_PMAOVR) == USB_ISTR_PMAOVR)
{
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_PMAOVR);
return;
}
if ((wIstr & USB_ISTR_ERR) == USB_ISTR_ERR)
{
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ERR);
return;
}
if ((wIstr & USB_ISTR_WKUP) == USB_ISTR_WKUP)
{
hpcd->Instance->CNTR &= (uint16_t) ~(USB_CNTR_LPMODE);
hpcd->Instance->CNTR &= (uint16_t) ~(USB_CNTR_FSUSP);
if (hpcd->LPM_State == LPM_L1)
{
hpcd->LPM_State = LPM_L0;
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->LPMCallback(hpcd, PCD_LPM_L0_ACTIVE);
#else
HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L0_ACTIVE);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->ResumeCallback(hpcd);
#else
HAL_PCD_ResumeCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP);
return;
}
if ((wIstr & USB_ISTR_SUSP) == USB_ISTR_SUSP)
{
/* Force low-power mode in the macrocell */
hpcd->Instance->CNTR |= (uint16_t)USB_CNTR_FSUSP;
/* clear of the ISTR bit must be done after setting of CNTR_FSUSP */
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP);
hpcd->Instance->CNTR |= (uint16_t)USB_CNTR_LPMODE;
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->SuspendCallback(hpcd);
#else
HAL_PCD_SuspendCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
return;
}
/* Handle LPM Interrupt */
if ((wIstr & USB_ISTR_L1REQ) == USB_ISTR_L1REQ)
{
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_L1REQ);
if (hpcd->LPM_State == LPM_L0)
{
/* Force suspend and low-power mode before going to L1 state*/
hpcd->Instance->CNTR |= (uint16_t)USB_CNTR_LPMODE;
hpcd->Instance->CNTR |= (uint16_t)USB_CNTR_FSUSP;
hpcd->LPM_State = LPM_L1;
hpcd->BESL = ((uint32_t)hpcd->Instance->LPMCSR & USB_LPMCSR_BESL) >> 2;
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->LPMCallback(hpcd, PCD_LPM_L1_ACTIVE);
#else
HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L1_ACTIVE);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->SuspendCallback(hpcd);
#else
HAL_PCD_SuspendCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
return;
}
if ((wIstr & USB_ISTR_SOF) == USB_ISTR_SOF)
{
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SOF);
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->SOFCallback(hpcd);
#else
HAL_PCD_SOFCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
return;
}
if ((wIstr & USB_ISTR_ESOF) == USB_ISTR_ESOF)
{
/* clear ESOF flag in ISTR */
__HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ESOF);
return;
}
}
/**
* @brief Data OUT stage callback.
* @param hpcd PCD handle
* @param epnum endpoint number
* @retval None
*/
__weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(epnum);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_DataOutStageCallback could be implemented in the user file
*/
}
/**
* @brief Data IN stage callback
* @param hpcd PCD handle
* @param epnum endpoint number
* @retval None
*/
__weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(epnum);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_DataInStageCallback could be implemented in the user file
*/
}
/**
* @brief Setup stage callback
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_SetupStageCallback could be implemented in the user file
*/
}
/**
* @brief USB Start Of Frame callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_SOFCallback could be implemented in the user file
*/
}
/**
* @brief USB Reset callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_ResetCallback could be implemented in the user file
*/
}
/**
* @brief Suspend event callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_SuspendCallback could be implemented in the user file
*/
}
/**
* @brief Resume event callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_ResumeCallback could be implemented in the user file
*/
}
/**
* @brief Incomplete ISO OUT callback.
* @param hpcd PCD handle
* @param epnum endpoint number
* @retval None
*/
__weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(epnum);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file
*/
}
/**
* @brief Incomplete ISO IN callback.
* @param hpcd PCD handle
* @param epnum endpoint number
* @retval None
*/
__weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(epnum);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file
*/
}
/**
* @brief Connection event callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_ConnectCallback could be implemented in the user file
*/
}
/**
* @brief Disconnection event callback.
* @param hpcd PCD handle
* @retval None
*/
__weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCD_DisconnectCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup PCD_Exported_Functions_Group3 Peripheral Control functions
* @brief management functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the PCD data
transfers.
@endverbatim
* @{
*/
/**
* @brief Connect the USB device
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd)
{
__HAL_LOCK(hpcd);
(void)USB_DevConnect(hpcd->Instance);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Disconnect the USB device.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd)
{
__HAL_LOCK(hpcd);
(void)USB_DevDisconnect(hpcd->Instance);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Set the USB Device address.
* @param hpcd PCD handle
* @param address new device address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address)
{
__HAL_LOCK(hpcd);
hpcd->USB_Address = address;
(void)USB_SetDevAddress(hpcd->Instance, address);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Open and configure an endpoint.
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @param ep_mps endpoint max packet size
* @param ep_type endpoint type
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr,
uint16_t ep_mps, uint8_t ep_type)
{
HAL_StatusTypeDef ret = HAL_OK;
PCD_EPTypeDef *ep;
if ((ep_addr & 0x80U) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 1U;
}
else
{
ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 0U;
}
ep->num = ep_addr & EP_ADDR_MSK;
ep->maxpacket = ep_mps;
ep->type = ep_type;
if (ep->is_in != 0U)
{
/* Assign a Tx FIFO */
ep->tx_fifo_num = ep->num;
}
/* Set initial data PID. */
if (ep_type == EP_TYPE_BULK)
{
ep->data_pid_start = 0U;
}
__HAL_LOCK(hpcd);
(void)USB_ActivateEndpoint(hpcd->Instance, ep);
__HAL_UNLOCK(hpcd);
return ret;
}
/**
* @brief Deactivate an endpoint.
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
{
PCD_EPTypeDef *ep;
if ((ep_addr & 0x80U) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 1U;
}
else
{
ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 0U;
}
ep->num = ep_addr & EP_ADDR_MSK;
__HAL_LOCK(hpcd);
(void)USB_DeactivateEndpoint(hpcd->Instance, ep);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Receive an amount of data.
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @param pBuf pointer to the reception buffer
* @param len amount of data to be received
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len)
{
PCD_EPTypeDef *ep;
ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK];
/*setup and start the Xfer */
ep->xfer_buff = pBuf;
ep->xfer_len = len;
ep->xfer_count = 0U;
ep->is_in = 0U;
ep->num = ep_addr & EP_ADDR_MSK;
if ((ep_addr & EP_ADDR_MSK) == 0U)
{
(void)USB_EP0StartXfer(hpcd->Instance, ep);
}
else
{
(void)USB_EPStartXfer(hpcd->Instance, ep);
}
return HAL_OK;
}
/**
* @brief Get Received Data Size
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @retval Data Size
*/
uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
{
return hpcd->OUT_ep[ep_addr & EP_ADDR_MSK].xfer_count;
}
/**
* @brief Send an amount of data
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @param pBuf pointer to the transmission buffer
* @param len amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len)
{
PCD_EPTypeDef *ep;
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
/*setup and start the Xfer */
ep->xfer_buff = pBuf;
ep->xfer_len = len;
ep->xfer_fill_db = 1U;
ep->xfer_len_db = len;
ep->xfer_count = 0U;
ep->is_in = 1U;
ep->num = ep_addr & EP_ADDR_MSK;
if ((ep_addr & EP_ADDR_MSK) == 0U)
{
(void)USB_EP0StartXfer(hpcd->Instance, ep);
}
else
{
(void)USB_EPStartXfer(hpcd->Instance, ep);
}
return HAL_OK;
}
/**
* @brief Set a STALL condition over an endpoint
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
{
PCD_EPTypeDef *ep;
if (((uint32_t)ep_addr & EP_ADDR_MSK) > hpcd->Init.dev_endpoints)
{
return HAL_ERROR;
}
if ((0x80U & ep_addr) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 1U;
}
else
{
ep = &hpcd->OUT_ep[ep_addr];
ep->is_in = 0U;
}
ep->is_stall = 1U;
ep->num = ep_addr & EP_ADDR_MSK;
__HAL_LOCK(hpcd);
(void)USB_EPSetStall(hpcd->Instance, ep);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Clear a STALL condition over in an endpoint
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
{
PCD_EPTypeDef *ep;
if (((uint32_t)ep_addr & 0x0FU) > hpcd->Init.dev_endpoints)
{
return HAL_ERROR;
}
if ((0x80U & ep_addr) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 1U;
}
else
{
ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK];
ep->is_in = 0U;
}
ep->is_stall = 0U;
ep->num = ep_addr & EP_ADDR_MSK;
__HAL_LOCK(hpcd);
(void)USB_EPClearStall(hpcd->Instance, ep);
__HAL_UNLOCK(hpcd);
return HAL_OK;
}
/**
* @brief Flush an endpoint
* @param hpcd PCD handle
* @param ep_addr endpoint address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(ep_addr);
return HAL_OK;
}
/**
* @brief Activate remote wakeup signalling
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd)
{
return (USB_ActivateRemoteWakeup(hpcd->Instance));
}
/**
* @brief De-activate remote wakeup signalling.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd)
{
return (USB_DeActivateRemoteWakeup(hpcd->Instance));
}
/**
* @}
*/
/** @defgroup PCD_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the PCD handle state.
* @param hpcd PCD handle
* @retval HAL state
*/
PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd)
{
return hpcd->State;
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup PCD_Private_Functions
* @{
*/
/**
* @brief This function handles PCD Endpoint interrupt request.
* @param hpcd PCD handle
* @retval HAL status
*/
static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd)
{
PCD_EPTypeDef *ep;
uint16_t count;
uint16_t wIstr;
uint16_t wEPVal;
uint16_t TxPctSize;
uint8_t epindex;
/* stay in loop while pending interrupts */
while ((hpcd->Instance->ISTR & USB_ISTR_CTR) != 0U)
{
wIstr = hpcd->Instance->ISTR;
/* extract highest priority endpoint number */
epindex = (uint8_t)(wIstr & USB_ISTR_EP_ID);
if (epindex == 0U)
{
/* Decode and service control endpoint interrupt */
/* DIR bit = origin of the interrupt */
if ((wIstr & USB_ISTR_DIR) == 0U)
{
/* DIR = 0 */
/* DIR = 0 => IN int */
/* DIR = 0 implies that (EP_CTR_TX = 1) always */
PCD_CLEAR_TX_EP_CTR(hpcd->Instance, PCD_ENDP0);
ep = &hpcd->IN_ep[0];
ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num);
ep->xfer_buff += ep->xfer_count;
/* TX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataInStageCallback(hpcd, 0U);
#else
HAL_PCD_DataInStageCallback(hpcd, 0U);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
if ((hpcd->USB_Address > 0U) && (ep->xfer_len == 0U))
{
hpcd->Instance->DADDR = ((uint16_t)hpcd->USB_Address | USB_DADDR_EF);
hpcd->USB_Address = 0U;
}
}
else
{
/* DIR = 1 */
/* DIR = 1 & CTR_RX => SETUP or OUT int */
/* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */
ep = &hpcd->OUT_ep[0];
wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0);
if ((wEPVal & USB_EP_SETUP) != 0U)
{
/* Get SETUP Packet */
ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num);
USB_ReadPMA(hpcd->Instance, (uint8_t *)hpcd->Setup,
ep->pmaadress, (uint16_t)ep->xfer_count);
/* SETUP bit kept frozen while CTR_RX = 1 */
PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0);
/* Process SETUP Packet*/
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->SetupStageCallback(hpcd);
#else
HAL_PCD_SetupStageCallback(hpcd);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else if ((wEPVal & USB_EP_CTR_RX) != 0U)
{
PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0);
/* Get Control Data OUT Packet */
ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num);
if ((ep->xfer_count != 0U) && (ep->xfer_buff != 0U))
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff,
ep->pmaadress, (uint16_t)ep->xfer_count);
ep->xfer_buff += ep->xfer_count;
/* Process Control Data OUT Packet */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataOutStageCallback(hpcd, 0U);
#else
HAL_PCD_DataOutStageCallback(hpcd, 0U);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
if ((PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0) & USB_EP_SETUP) == 0U)
{
PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket);
PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID);
}
}
}
}
else
{
/* Decode and service non control endpoints interrupt */
/* process related endpoint register */
wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, epindex);
if ((wEPVal & USB_EP_CTR_RX) != 0U)
{
/* clear int flag */
PCD_CLEAR_RX_EP_CTR(hpcd->Instance, epindex);
ep = &hpcd->OUT_ep[epindex];
/* OUT Single Buffering */
if (ep->doublebuffer == 0U)
{
count = (uint16_t)PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num);
if (count != 0U)
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else
{
/* manage double buffer bulk out */
if (ep->type == EP_TYPE_BULK)
{
count = HAL_PCD_EP_DB_Receive(hpcd, ep, wEPVal);
}
else /* manage double buffer iso out */
{
/* free EP OUT Buffer */
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U);
if ((PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_RX) != 0U)
{
/* read from endpoint BUF0Addr buffer */
count = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num);
if (count != 0U)
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count);
}
}
else
{
/* read from endpoint BUF1Addr buffer */
count = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num);
if (count != 0U)
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count);
}
}
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/* multi-packet on the NON control OUT endpoint */
ep->xfer_count += count;
ep->xfer_buff += count;
if ((ep->xfer_len == 0U) || (count < ep->maxpacket))
{
/* RX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataOutStageCallback(hpcd, ep->num);
#else
HAL_PCD_DataOutStageCallback(hpcd, ep->num);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
(void) USB_EPStartXfer(hpcd->Instance, ep);
}
}
if ((wEPVal & USB_EP_CTR_TX) != 0U)
{
ep = &hpcd->IN_ep[epindex];
/* clear int flag */
PCD_CLEAR_TX_EP_CTR(hpcd->Instance, epindex);
if (ep->type != EP_TYPE_BULK)
{
ep->xfer_len = 0U;
#if (USE_USB_DOUBLE_BUFFER == 1U)
if (ep->doublebuffer != 0U)
{
if ((wEPVal & USB_EP_DTOG_TX) != 0U)
{
PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
}
else
{
PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
}
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/* TX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataInStageCallback(hpcd, ep->num);
#else
HAL_PCD_DataInStageCallback(hpcd, ep->num);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
/* Manage Bulk Single Buffer Transaction */
if ((wEPVal & USB_EP_KIND) == 0U)
{
/* multi-packet on the NON control IN endpoint */
TxPctSize = (uint16_t)PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num);
if (ep->xfer_len > TxPctSize)
{
ep->xfer_len -= TxPctSize;
}
else
{
ep->xfer_len = 0U;
}
/* Zero Length Packet? */
if (ep->xfer_len == 0U)
{
/* TX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataInStageCallback(hpcd, ep->num);
#else
HAL_PCD_DataInStageCallback(hpcd, ep->num);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
/* Transfer is not yet Done */
ep->xfer_buff += TxPctSize;
ep->xfer_count += TxPctSize;
(void)USB_EPStartXfer(hpcd->Instance, ep);
}
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/* Double Buffer bulk IN (bulk transfer Len > Ep_Mps) */
else
{
(void)HAL_PCD_EP_DB_Transmit(hpcd, ep, wEPVal);
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
}
}
}
}
return HAL_OK;
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
/**
* @brief Manage double buffer bulk out transaction from ISR
* @param hpcd PCD handle
* @param ep current endpoint handle
* @param wEPVal Last snapshot of EPRx register value taken in ISR
* @retval HAL status
*/
static uint16_t HAL_PCD_EP_DB_Receive(PCD_HandleTypeDef *hpcd,
PCD_EPTypeDef *ep, uint16_t wEPVal)
{
uint16_t count;
/* Manage Buffer0 OUT */
if ((wEPVal & USB_EP_DTOG_RX) != 0U)
{
/* Get count of received Data on buffer0 */
count = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num);
if (ep->xfer_len >= count)
{
ep->xfer_len -= count;
}
else
{
ep->xfer_len = 0U;
}
if (ep->xfer_len == 0U)
{
/* set NAK to OUT endpoint since double buffer is enabled */
PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_NAK);
}
/* Check if Buffer1 is in blocked state which requires to toggle */
if ((wEPVal & USB_EP_DTOG_TX) != 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U);
}
if (count != 0U)
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count);
}
}
/* Manage Buffer 1 DTOG_RX=0 */
else
{
/* Get count of received data */
count = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num);
if (ep->xfer_len >= count)
{
ep->xfer_len -= count;
}
else
{
ep->xfer_len = 0U;
}
if (ep->xfer_len == 0U)
{
/* set NAK on the current endpoint */
PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_NAK);
}
/*Need to FreeUser Buffer*/
if ((wEPVal & USB_EP_DTOG_TX) == 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U);
}
if (count != 0U)
{
USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count);
}
}
return count;
}
/**
* @brief Manage double buffer bulk IN transaction from ISR
* @param hpcd PCD handle
* @param ep current endpoint handle
* @param wEPVal Last snapshot of EPRx register value taken in ISR
* @retval HAL status
*/
static HAL_StatusTypeDef HAL_PCD_EP_DB_Transmit(PCD_HandleTypeDef *hpcd,
PCD_EPTypeDef *ep, uint16_t wEPVal)
{
uint32_t len;
uint16_t TxPctSize;
/* Data Buffer0 ACK received */
if ((wEPVal & USB_EP_DTOG_TX) != 0U)
{
/* multi-packet on the NON control IN endpoint */
TxPctSize = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num);
if (ep->xfer_len > TxPctSize)
{
ep->xfer_len -= TxPctSize;
}
else
{
ep->xfer_len = 0U;
}
/* Transfer is completed */
if (ep->xfer_len == 0U)
{
PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
/* TX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataInStageCallback(hpcd, ep->num);
#else
HAL_PCD_DataInStageCallback(hpcd, ep->num);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
if ((wEPVal & USB_EP_DTOG_RX) != 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U);
}
}
else /* Transfer is not yet Done */
{
/* need to Free USB Buff */
if ((wEPVal & USB_EP_DTOG_RX) != 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U);
}
/* Still there is data to Fill in the next Buffer */
if (ep->xfer_fill_db == 1U)
{
ep->xfer_buff += TxPctSize;
ep->xfer_count += TxPctSize;
/* Calculate the len of the new buffer to fill */
if (ep->xfer_len_db >= ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len_db -= len;
}
else if (ep->xfer_len_db == 0U)
{
len = TxPctSize;
ep->xfer_fill_db = 0U;
}
else
{
ep->xfer_fill_db = 0U;
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
}
/* Write remaining Data to Buffer */
/* Set the Double buffer counter for pma buffer1 */
PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, len);
/* Copy user buffer to USB PMA */
USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, (uint16_t)len);
}
}
}
else /* Data Buffer1 ACK received */
{
/* multi-packet on the NON control IN endpoint */
TxPctSize = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num);
if (ep->xfer_len >= TxPctSize)
{
ep->xfer_len -= TxPctSize;
}
else
{
ep->xfer_len = 0U;
}
/* Transfer is completed */
if (ep->xfer_len == 0U)
{
PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U);
/* TX COMPLETE */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->DataInStageCallback(hpcd, ep->num);
#else
HAL_PCD_DataInStageCallback(hpcd, ep->num);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
/* need to Free USB Buff */
if ((wEPVal & USB_EP_DTOG_RX) == 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U);
}
}
else /* Transfer is not yet Done */
{
/* need to Free USB Buff */
if ((wEPVal & USB_EP_DTOG_RX) == 0U)
{
PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U);
}
/* Still there is data to Fill in the next Buffer */
if (ep->xfer_fill_db == 1U)
{
ep->xfer_buff += TxPctSize;
ep->xfer_count += TxPctSize;
/* Calculate the len of the new buffer to fill */
if (ep->xfer_len_db >= ep->maxpacket)
{
len = ep->maxpacket;
ep->xfer_len_db -= len;
}
else if (ep->xfer_len_db == 0U)
{
len = TxPctSize;
ep->xfer_fill_db = 0U;
}
else
{
len = ep->xfer_len_db;
ep->xfer_len_db = 0U;
ep->xfer_fill_db = 0;
}
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len);
/* Copy the user buffer to USB PMA */
USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, (uint16_t)len);
}
}
}
/*enable endpoint IN*/
PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID);
return HAL_OK;
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
/**
* @}
*/
#endif /* defined (USB) */
#endif /* HAL_PCD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 56,850 |
C
| 24.573999 | 120 | 0.587318 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_rcc.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_rcc.c
* @author MCD Application Team
* @brief RCC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
/** @addtogroup RCC_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RCC_LL_Private_Macros
* @{
*/
#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART3_CLKSOURCE))
#if defined(RCC_CCIPR_UART5SEL)
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_UART4_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_UART5_CLKSOURCE))
#elif defined(RCC_CCIPR_UART4SEL)
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_UART4_CLKSOURCE)
#endif /* RCC_CCIPR_UART5SEL*/
#define IS_LL_RCC_LPUART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPUART1_CLKSOURCE))
#if defined(RCC_CCIPR2_I2C4SEL)
#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))
#else
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE))
#endif /* RCC_CCIPR2_I2C4SEL */
#define IS_LL_RCC_LPTIM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPTIM1_CLKSOURCE))
#define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_SAI1_CLKSOURCE)
#define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2S_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))
#if defined(ADC345_COMMON)
#define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADC12_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_ADC345_CLKSOURCE))
#else
#define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADC12_CLKSOURCE))
#endif /* ADC345_COMMON */
#if defined(QUADSPI)
#define IS_LL_RCC_QUADSPI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_QUADSPI_CLKSOURCE))
#endif /* QUADSPI */
#if defined(FDCAN1)
#define IS_LL_RCC_FDCAN_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_FDCAN_CLKSOURCE))
#endif /* FDCAN1 */
/**
* @}
*/
/* 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_PLL_GetFreqDomain_SYS(void);
static uint32_t RCC_PLL_GetFreqDomain_ADC(void);
static uint32_t RCC_PLL_GetFreqDomain_48M(void);
/**
* @}
*/
/* 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:
* - HSI ON and used as system clock source
* - HSE and PLL OFF
* - AHB, APB1 and APB2 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 HSION bit and wait for HSI READY bit */
LL_RCC_HSI_Enable();
while (LL_RCC_HSI_IsReady() == 0U)
{}
/* Set HSITRIM bits to reset value*/
LL_RCC_HSI_SetCalibTrimming(0x40U);
/* Reset whole CFGR register but keep HSI as system clock source */
LL_RCC_WriteReg(CFGR, LL_RCC_SYS_CLKSOURCE_HSI);
while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSI) {};
/* Reset whole CR register but HSI in 2 steps in case HSEBYP is set */
LL_RCC_WriteReg(CR, RCC_CR_HSION);
LL_RCC_WriteReg(CR, RCC_CR_HSION);
/* Wait for PLL READY bit to be reset */
while (LL_RCC_PLL_IsReady() != 0U)
{}
/* Reset PLLCFGR register */
LL_RCC_WriteReg(PLLCFGR, 16U << RCC_PLLCFGR_PLLN_Pos);
/* Disable all interrupts */
LL_RCC_WriteReg(CIER, 0x00000000U);
/* Clear all interrupt flags */
vl_mask = RCC_CICR_LSIRDYC | RCC_CICR_LSERDYC | RCC_CICR_HSIRDYC | RCC_CICR_HSERDYC | RCC_CICR_PLLRDYC | \
RCC_CICR_HSI48RDYC | RCC_CICR_CSSC | RCC_CICR_LSECSSC;
LL_RCC_WriteReg(CICR, vl_mask);
/* Clear reset flags */
LL_RCC_ClearResetFlags();
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 HSI, function returns values based on HSI_VALUE(**)
* @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(***)
* @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(***)
* or HSI_VALUE(**) multiplied/divided by the PLL factors.
* @note (**) HSI_VALUE is a constant defined in 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 and/or PCLK2 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);
}
/**
* @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
*
* @retval USART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
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() != 0U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_LSE: /* USART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_PCLK2: /* USART1 Clock is PCLK2 */
default:
usart_frequency = RCC_GetPCLK2ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
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() != 0U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_LSE: /* USART2 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_PCLK1: /* USART2 Clock is PCLK1 */
default:
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
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() != 0U)
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_LSE: /* USART3 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_PCLK1: /* USART3 Clock is PCLK1 */
default:
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
}
return usart_frequency;
}
#if defined(RCC_CCIPR_UART4SEL)
/**
* @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 (*)
*
* (*) value not defined in all devices.
* @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() != 0U)
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_LSE: /* UART4 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_PCLK1: /* UART4 Clock is PCLK1 */
default:
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#if defined(RCC_CCIPR_UART5SEL)
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() != 0U)
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_LSE: /* UART5 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_PCLK1: /* UART5 Clock is PCLK1 */
default:
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#endif /* RCC_CCIPR_UART5SEL */
return uart_frequency;
}
#endif /* RCC_CCIPR_UART4SEL */
/**
* @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 (*)
*
* (*) value not defined in all devices.
* @retval I2C clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that HSI oscillator 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() != 0U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C1_CLKSOURCE_PCLK1: /* I2C1 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
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() != 0U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C2_CLKSOURCE_PCLK1: /* I2C2 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
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() != 0U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C3_CLKSOURCE_PCLK1: /* I2C3 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#if defined(RCC_CCIPR2_I2C4SEL)
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() != 0U)
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C4_CLKSOURCE_PCLK1: /* I2C4 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
}
#endif /*RCC_CCIPR2_I2C4SEL*/
}
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() != 0U)
{
lpuart_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_LSE: /* LPUART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
lpuart_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_PCLK1: /* LPUART1 Clock is PCLK1 */
default:
lpuart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
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
* @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() != 0U)
{
lptim_frequency = LSI_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_HSI: /* LPTIM1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady() != 0U)
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_LSE: /* LPTIM1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady() != 0U)
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_PCLK1: /* LPTIM1 Clock is PCLK1 */
default:
lptim_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
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
*
* @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_SYSCLK: /* System clock used as SAI1 clock source */
sai_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_SAI1_CLKSOURCE_PLL: /* PLL clock used as SAI1 clock source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
sai_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
case LL_RCC_SAI1_CLKSOURCE_PIN: /* SAI1 Clock is External clock */
sai_frequency = EXTERNAL_CLOCK_VALUE;
break;
case LL_RCC_SAI1_CLKSOURCE_HSI: /* HSI clock used as SAI1 clock source */
default:
if (LL_RCC_HSI_IsReady() != 0U)
{
sai_frequency = HSI_VALUE;
}
break;
}
}
return sai_frequency;
}
/**
* @brief Return I2Sx clock frequency
* @param I2SxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_I2S_CLKSOURCE
* @retval I2S clock frequency (in Hz)
* @arg @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
*/
uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource)
{
uint32_t i2s_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_I2S_CLKSOURCE(I2SxSource));
if (I2SxSource == LL_RCC_I2S_CLKSOURCE)
{
/* I2S CLK clock frequency */
switch (LL_RCC_GetI2SClockSource(I2SxSource))
{
case LL_RCC_I2S_CLKSOURCE_SYSCLK: /* I2S Clock is System Clock */
i2s_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2S_CLKSOURCE_PLL: /* I2S Clock is PLL"Q" */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
i2s_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
case LL_RCC_I2S_CLKSOURCE_PIN: /* I2S Clock is External clock */
i2s_frequency = EXTERNAL_CLOCK_VALUE;
break;
case LL_RCC_I2S_CLKSOURCE_HSI: /* I2S Clock is HSI */
default:
if (LL_RCC_HSI_IsReady() != 0U)
{
i2s_frequency = HSI_VALUE;
}
break;
}
}
return i2s_frequency;
}
#if defined(FDCAN1)
/**
* @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 is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
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() != 0U)
{
fdcan_frequency = HSE_VALUE;
}
break;
case LL_RCC_FDCAN_CLKSOURCE_PLL: /* PLL clock used as FDCAN kernel clock */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
fdcan_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
case LL_RCC_FDCAN_CLKSOURCE_PCLK1: /* PCLK1 clock used as FDCAN kernel clock */
fdcan_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
default:
fdcan_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return fdcan_frequency;
}
#endif /* FDCAN1 */
/**
* @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 (HSI48) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
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_PLL: /* PLL clock used as RNG clock source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
rng_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
case LL_RCC_RNG_CLKSOURCE_HSI48: /* HSI48 used as RNG clock source */
if (LL_RCC_HSI48_IsReady() != 0U)
{
rng_frequency = HSI48_VALUE;
}
break;
default:
rng_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
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 (HSI48) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource)
{
uint32_t usb_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_USB_CLKSOURCE(USBxSource));
/* USBCLK clock frequency */
switch (LL_RCC_GetUSBClockSource(USBxSource))
{
case LL_RCC_USB_CLKSOURCE_PLL: /* PLL clock used as USB clock source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
usb_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
case LL_RCC_USB_CLKSOURCE_HSI48: /* HSI48 used as USB clock source */
if (LL_RCC_HSI48_IsReady() != 0U)
{
usb_frequency = HSI48_VALUE;
}
break;
default:
usb_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return usb_frequency;
}
/**
* @brief Return ADCx clock frequency
* @param ADCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_ADC12_CLKSOURCE
* @arg @ref LL_RCC_ADC345_CLKSOURCE (*)
*
* (*) value not defined in all devices.
* @retval ADC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetADCClockFreq(uint32_t ADCxSource)
{
uint32_t adc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_ADC_CLKSOURCE(ADCxSource));
if (ADCxSource == LL_RCC_ADC12_CLKSOURCE)
{
/* ADC12CLK clock frequency */
switch (LL_RCC_GetADCClockSource(ADCxSource))
{
case LL_RCC_ADC12_CLKSOURCE_PLL: /* PLL clock used as ADC12 clock source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_ADC() != 0U)
{
adc_frequency = RCC_PLL_GetFreqDomain_ADC();
}
}
break;
case LL_RCC_ADC12_CLKSOURCE_SYSCLK: /* System clock used as ADC12 clock source */
adc_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADC12_CLKSOURCE_NONE: /* No clock used as ADC12 clock source */
default:
adc_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
}
#if defined(ADC345_COMMON)
else
{
/* ADC345CLK clock frequency */
switch (LL_RCC_GetADCClockSource(ADCxSource))
{
case LL_RCC_ADC345_CLKSOURCE_PLL: /* PLL clock used as ADC345 clock source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_ADC() != 0U)
{
adc_frequency = RCC_PLL_GetFreqDomain_ADC();
}
}
break;
case LL_RCC_ADC345_CLKSOURCE_SYSCLK: /* System clock used as ADC345 clock source */
adc_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADC345_CLKSOURCE_NONE: /* No clock used as ADC345 clock source */
default:
adc_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
}
#endif /* ADC345_COMMON */
return adc_frequency;
}
#if defined(QUADSPI)
/**
* @brief Return QUADSPI clock frequency
* @param QUADSPIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_QUADSPI_CLKSOURCE
* @retval QUADSPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that no clock is configured
*/
uint32_t LL_RCC_GetQUADSPIClockFreq(uint32_t QUADSPIxSource)
{
uint32_t quadspi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_QUADSPI_CLKSOURCE(QUADSPIxSource));
/* QUADSPI clock frequency */
switch (LL_RCC_GetQUADSPIClockSource(QUADSPIxSource))
{
case LL_RCC_QUADSPI_CLKSOURCE_SYSCLK: /* SYSCLK used as QUADSPI source */
quadspi_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_QUADSPI_CLKSOURCE_HSI: /* HSI clock used as QUADSPI source */
if (LL_RCC_HSI_IsReady() != 0U)
{
quadspi_frequency = HSI_VALUE;
}
break;
case LL_RCC_QUADSPI_CLKSOURCE_PLL: /* PLL clock used as QUADSPI source */
if (LL_RCC_PLL_IsReady() != 0U)
{
if (LL_RCC_PLL_IsEnabledDomain_48M() != 0U)
{
quadspi_frequency = RCC_PLL_GetFreqDomain_48M();
}
}
break;
default:
/* Nothing to do: quadspi frequency already initilalized to LL_RCC_PERIPH_FREQUENCY_NO */
break;
}
return quadspi_frequency;
}
#endif /* QUADSPI */
/**
* @}
*/
/**
* @}
*/
/** @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_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_PLL: /* PLL used as system clock source */
frequency = RCC_PLL_GetFreqDomain_SYS();
break;
default:
frequency = HSI_VALUE;
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 PLL clock frequency used for system domain
* @retval PLL clock frequency (in Hz)
*/
static uint32_t RCC_PLL_GetFreqDomain_SYS(void)
{
uint32_t pllinputfreq, pllsource;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = HSI_VALUE;
break;
}
return __LL_RCC_CALC_PLLCLK_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR());
}
/**
* @brief Return PLL clock frequency used for ADC domain
* @retval PLL clock frequency (in Hz)
*/
static uint32_t RCC_PLL_GetFreqDomain_ADC(void)
{
uint32_t pllinputfreq, pllsource;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN
ADC Domain clock = PLL_VCO / PLLP
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = HSI_VALUE;
break;
}
return __LL_RCC_CALC_PLLCLK_ADC_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetP());
}
/**
* @brief Return PLL clock frequency used for 48 MHz domain
* @retval PLL clock frequency (in Hz)
*/
static uint32_t RCC_PLL_GetFreqDomain_48M(void)
{
uint32_t pllinputfreq, pllsource;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN
48M Domain clock = PLL_VCO / PLLQ
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = HSI_VALUE;
break;
}
return __LL_RCC_CALC_PLLCLK_48M_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetQ());
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 35,700 |
C
| 29.435635 | 110 | 0.598067 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_spi_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup SPIEx SPIEx
* @brief SPI Extended HAL module driver
* @{
*/
#ifdef HAL_SPI_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/** @defgroup SPIEx_Private_Constants SPIEx Private Constants
* @{
*/
#define SPI_FIFO_SIZE 4UL
/**
* @}
*/
/* 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.
(#) Rx data flush function:
(++) HAL_SPIEx_FlushRxFifo()
@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)
{
__IO uint32_t tmpreg;
uint8_t count = 0U;
while ((hspi->Instance->SR & SPI_FLAG_FRLVL) != SPI_FRLVL_EMPTY)
{
count++;
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg); /* To avoid GCC warning */
if (count == SPI_FIFO_SIZE)
{
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_SPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 3,027 |
C
| 25.79646 | 80 | 0.453254 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_opamp.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_opamp.c
* @author MCD Application Team
* @brief OPAMP HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the operational amplifiers peripheral:
* + Initialization/de-initialization functions
* + I/O operation functions
* + Peripheral Control functions
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
================================================================================
##### OPAMP Peripheral Features #####
================================================================================
[..] The device integrates up to 6 operational amplifiers OPAMP1, OPAMP2,
OPAMP3, OPAMP4, OPAMP5 and OPAMP6:
(#) The OPAMP(s) provides several exclusive running modes.
(++) Standalone mode
(++) Programmable Gain Amplifier (PGA) mode (Resistor feedback output)
(++) Follower mode
(#) The OPAMP(s) provide(s) calibration capabilities.
(++) Calibration aims at correcting some offset for running mode.
(++) The OPAMP uses either factory calibration settings OR user defined
calibration (trimming) settings (i.e. trimming mode).
(++) The user defined settings can be figured out using self calibration
handled by HAL_OPAMP_SelfCalibrate, HAL_OPAMPEx_SelfCalibrateAll
(++) HAL_OPAMP_SelfCalibrate:
(++) Runs automatically the calibration in 2 steps.
(90% of VDDA for NMOS transistors, 10% of VDDA for PMOS transistors).
(As OPAMP is Rail-to-rail input/output, these 2 steps calibration is
appropriate and enough in most cases).
(++) Enables the user trimming mode
(++) Updates the init structure with trimming values with fresh calibration
results.
The user may store the calibration results for larger
(ex monitoring the trimming as a function of temperature
for instance)
(++) for STM32G4 devices having 6 OPAMPs
HAL_OPAMPEx_SelfCalibrateAll
runs calibration of 6 OPAMPs in parallel.
(#) For any running mode, an additional Timer-controlled Mux (multiplexer)
mode can be set on top.
(++) Timer-controlled Mux mode allows Automatic switching of inputs
configuration (inverting and non inverting).
(++) Hence on top of defaults (primary) inverting and non-inverting inputs,
the user shall select secondary inverting and non inverting inputs.
(++) TIM1 OC6, TIM8 OC6 and TIM20 OC6 provides the alternate switching
tempo between defaults (primary) and secondary inputs.
(++) These 3 timers (TIM1, TIM8 and TIM20) can be combined to design a more
complex switching scheme. So that any of the selected channel can initiate
the configuration switch.
(#) Running mode: Standalone mode
(++) Gain is set externally (gain depends on external loads).
(++) Follower mode also possible externally by connecting the inverting input to
the output.
(#) Running mode: Follower mode
(++) Inverting Input is not connected.
(#) Running mode: Programmable Gain Amplifier (PGA) mode
(Resistor feedback output)
(++) The OPAMP(s) output(s) can be internally connected to resistor feedback
output.
(++) The OPAMP inverting input can be "not" connected, signal to amplify is
connected to non inverting input and gain is positive (2,4,8,16,32 or 64)
(++) The OPAMP inverting input can be connected to VINM0:
If signal is applied to non inverting input, gain is positive (2,4,8,16,32 or 64).
If signal is applied to inverting input, gain is negative (-1,-3,-7,-15-,31 or -63).
In both cases, the other input can be used as bias.
##### How to use this driver #####
================================================================================
[..]
*** High speed / normal power mode ***
============================================
[..] To run in high speed mode:
(#) Configure the OPAMP using HAL_OPAMP_Init() function:
(++) Select OPAMP_POWERMODE_HIGHSPEED
(++) Otherwise select OPAMP_POWERMODE_NORMALSPEED
*** Calibration ***
============================================
[..] To run the OPAMP calibration self calibration:
(#) Start calibration using HAL_OPAMP_SelfCalibrate.
Store the calibration results.
*** Running mode ***
============================================
[..] To use the OPAMP, perform the following steps:
(#) Fill in the HAL_OPAMP_MspInit() to
(++) Configure the OPAMP input AND output in analog mode using
HAL_GPIO_Init() to map the OPAMP output to the GPIO pin.
(#) Registrate Callbacks
(++) The compilation define USE_HAL_OPAMP_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
(++) Use Functions HAL_OPAMP_RegisterCallback() to register a user callback,
it allows to register following callbacks:
(+++) MspInitCallback : OPAMP MspInit.
(+++) MspDeInitCallback : OPAMP MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
(++) Use function HAL_OPAMP_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function. It allows to reset following callbacks:
(+++) MspInitCallback : OPAMP MspInit.
(+++) MspDeInitCallback : OPAMP MspDeInit.
(+++) All Callbacks
(#) Configure the OPAMP using HAL_OPAMP_Init() function:
(++) Select the mode
(++) Select the inverting input
(++) Select the non-inverting input
(++) Select if the internal output should be enabled/disabled (if enabled, regular I/O output is disabled)
(++) Select if the Timer controlled Mux is disabled or enabled and controlled by specified timer(s)
(++) If the Timer controlled Mux mode is enabled, select the secondary inverting input
(++) If the Timer controlled Mux mode is enabled, Select the secondary non-inverting input
(++) If PGA mode is enabled, Select if inverting input is connected.
(++) If PGA mode is enabled, Select PGA gain to be used.
(++) Select either factory or user defined trimming mode.
(++) If the user defined trimming mode is enabled, select PMOS & NMOS trimming values
(typ. settings returned by HAL_OPAMP_SelfCalibrate function).
(#) Enable the OPAMP using HAL_OPAMP_Start() function.
(#) Disable the OPAMP using HAL_OPAMP_Stop() function.
(#) Lock the OPAMP in running mode using HAL_OPAMP_Lock() & HAL_OPAMP_TimerMuxLock functions.
From then the configuration can only be modified
(++) After HW reset
(++) OR thanks to HAL_OPAMP_MspDeInit called (user defined) from HAL_OPAMP_DeInit.
*** Running mode: change of configuration while OPAMP ON ***
============================================
[..] To Re-configure OPAMP when OPAMP is ON (change on the fly)
(#) If needed, fill in the HAL_OPAMP_MspInit()
(++) This is the case for instance if you wish to use new OPAMP I/O
(#) Configure the OPAMP using HAL_OPAMP_Init() function:
(++) As in configure case, selects first the parameters you wish to modify.
(++) If OPAMP control register is locked, it is not possible to modify any values
on the fly (even the timer controlled mux parameters).
(++) If OPAMP timer controlled mux mode register is locked, it is possible to modify any values
of the control register but none on the timer controlled mux mode one.
(#) Change from high speed mode to normal power mode (& vice versa) requires
first HAL_OPAMP_DeInit() (force OPAMP OFF) and then HAL_OPAMP_Init().
In other words, of OPAMP is ON, HAL_OPAMP_Init can NOT change power mode
alone.
@endverbatim
******************************************************************************
*/
/*
Additional Tables:
The OPAMPs non inverting input (both default and secondary) can be
selected among the list shown by table below.
The OPAMPs non inverting input (both default and secondary) can be
selected among the list shown by table below.
Table 1. OPAMPs inverting/non-inverting inputs for the STM32G4 devices:
+-----------------------------------------------------------------------------------------------+
| | | OPAMP1 | OPAMP2 | OPAMP3 | OPAMP4 | OPAMP5 | OPAMP6 |
|-----------------|--------|----------|----------|-------------|----------|----------|----------|
| | No conn| X | X | X | X | X | X |
| Inverting Input | VM0 | PA3 | PA5 | PB2 | PB10 | PB15 | PA1 |
| (1) | VM1 | PC5 | PC5 | PB10 | PD8 | PA3 | PB1 |
|-----------------|--------|----------|----------|-------------|----------|----------|----------|
| | VP0 | PA1 | PA7 | PB0 | PB13 | PB14 | PB12 |
| Non Inverting | VP1 | PA3 | PB14 | PB13 | PD11 | PD12 | PD9 |
| Input | VP2 | PA7 | PB0 | PA1 | PB11 | PC3 | PB13 |
| | VP3 | DAC3_CH1 | PD14 | DAC3_CH2(2) | DAC4_CH1 | DAC4_CH2 | DAC3_CH1 |
+-----------------------------------------------------------------------------------------------+
(1): No connection in follower mode.
(2): Available for STM32G47x/ STM32G48x devices only
Table 2. OPAMPs outputs for the STM32G4 devices:
+------------------------------------------------------------------------------------+
| | | OPAMP1 | OPAMP2 | OPAMP3 | OPAMP4 | OPAMP5 | OPAMP6 |
|-----------------|--------|--------|--------|----------|--------|--------|----------|
| Output | | PA2 | PA6 | PB1 | PB12 | PA8 | PB11 |
|-----------------|--------|--------|--------|----------|--------|--------|----------+
| Internal output | | ADC1 | ADC2 | ADC2 | ADC5 | ADC5 | ADC4 |
| to ADCs | | CH13 | CH16 | CH18 | CH5 | CH3 | CH17(2) |
| (1) | | | | ADC3 | | | ADC3 |
| | | | | CH13(2) | | | CH17(3) |
|-----------------|--------|--------|--------|----------|------ -|--------|----------|
| Internal output | | ADC1 | ADC2 | ADC3 | ADC4 | ADC5 | ADC1 |
| to ADCs input | | CH3 | CH3 | CH1(2) | CH3 | CH1 | CH14 |
| on GPIO | | | | ADC1 | ADC1 | | ADC2 |
| | | | | CH12 | CH11 | | CH14 |
+------------------------------------------------------------------------------------+
(1): This ADC channel is connected internally to the OPAMPx_VOUT when OPAINTOEN
bit is set.
In this case, the I/O on which the OPAMPx_VOUT is available, can be used for
another purpose.
(2): Available for STM32G47x/ STM32G48x devices only.
(3): Available for STM32G491/STM32G4A1 devices only.
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_OPAMP_MODULE_ENABLED
/** @defgroup OPAMP OPAMP
* @brief OPAMP HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup OPAMP_Private_Define OPAMP Private Define
* @{
*/
/* CSR register reset value */
#define OPAMP_CSR_RESET_VALUE (0x00000000UL)
/* CSR register TRIM value upon reset are factory ones, filter them out from CSR register check */
#define OPAMP_CSR_RESET_CHECK_MASK (~(OPAMP_CSR_TRIMOFFSETN | OPAMP_CSR_TRIMOFFSETP))
/* CSR init register Mask */
#define OPAMP_CSR_UPDATE_PARAMETERS_INIT_MASK (OPAMP_CSR_TRIMOFFSETN | OPAMP_CSR_TRIMOFFSETP \
| OPAMP_CSR_HIGHSPEEDEN | OPAMP_CSR_OPAMPINTEN \
| OPAMP_CSR_PGGAIN | OPAMP_CSR_VPSEL \
| OPAMP_CSR_VMSEL | OPAMP_CSR_FORCEVP)
/* TCMR init register Mask */
#define OPAMP_TCMR_UPDATE_PARAMETERS_INIT_MASK (OPAMP_TCMR_T20CMEN | OPAMP_TCMR_T8CMEN \
| OPAMP_TCMR_T1CMEN | OPAMP_TCMR_VPSSEL \
| OPAMP_TCMR_VMSSEL)
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup OPAMP_Exported_Functions OPAMP Exported Functions
* @{
*/
/** @defgroup OPAMP_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
@endverbatim
* @{
*/
/**
* @brief Initializes the OPAMP according to the specified
* parameters in the OPAMP_InitTypeDef and initialize the associated handle.
* @note If the selected opamp is locked, initialization can't be performed.
* To unlock the configuration, perform a system reset.
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_Init(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation and lock status */
/* Init not allowed if calibration is ongoing */
if (hopamp == NULL)
{
return HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_BUSYLOCKED)
{
return HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_CALIBBUSY)
{
return HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
/* Set OPAMP parameters */
assert_param(IS_OPAMP_POWERMODE(hopamp->Init.PowerMode));
assert_param(IS_OPAMP_FUNCTIONAL_NORMALMODE(hopamp->Init.Mode));
assert_param(IS_OPAMP_NONINVERTING_INPUT(hopamp->Init.NonInvertingInput));
#if (USE_HAL_OPAMP_REGISTER_CALLBACKS == 1)
if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
if (hopamp->MspInitCallback == NULL)
{
hopamp->MspInitCallback = HAL_OPAMP_MspInit;
}
}
#endif /* USE_HAL_OPAMP_REGISTER_CALLBACKS */
if ((hopamp->Init.Mode) == OPAMP_STANDALONE_MODE)
{
assert_param(IS_OPAMP_INVERTING_INPUT(hopamp->Init.InvertingInput));
}
assert_param(IS_FUNCTIONAL_STATE(hopamp->Init.InternalOutput));
assert_param(IS_OPAMP_TIMERCONTROLLED_MUXMODE(hopamp->Init.TimerControlledMuxmode));
if ((hopamp->Init.TimerControlledMuxmode) != OPAMP_TIMERCONTROLLEDMUXMODE_DISABLE)
{
assert_param(IS_OPAMP_SEC_NONINVERTING_INPUT(hopamp->Init.NonInvertingInputSecondary));
assert_param(IS_OPAMP_SEC_INVERTING_INPUT(hopamp->Init.InvertingInputSecondary));
}
if ((hopamp->Init.Mode) == OPAMP_PGA_MODE)
{
assert_param(IS_OPAMP_PGACONNECT(hopamp->Init.PgaConnect));
assert_param(IS_OPAMP_PGA_GAIN(hopamp->Init.PgaGain));
}
assert_param(IS_OPAMP_TRIMMING(hopamp->Init.UserTrimming));
if ((hopamp->Init.UserTrimming) == OPAMP_TRIMMING_USER)
{
assert_param(IS_OPAMP_TRIMMINGVALUE(hopamp->Init.TrimmingValueP));
assert_param(IS_OPAMP_TRIMMINGVALUE(hopamp->Init.TrimmingValueN));
}
/* Init SYSCFG and the low level hardware to access opamp */
__HAL_RCC_SYSCFG_CLK_ENABLE();
if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hopamp->Lock = HAL_UNLOCKED;
}
#if (USE_HAL_OPAMP_REGISTER_CALLBACKS == 1)
hopamp->MspInitCallback(hopamp);
#else
/* Call MSP init function */
HAL_OPAMP_MspInit(hopamp);
#endif /* USE_HAL_OPAMP_REGISTER_CALLBACKS */
/* Set OPAMP parameters */
/* Set bits according to hopamp->hopamp->Init.Mode value */
/* Set bits according to hopamp->hopamp->Init.InvertingInput value */
/* Set bits according to hopamp->hopamp->Init.NonInvertingInput value */
/* Set bits according to hopamp->hopamp->Init.InternalOutput value */
/* Set bits according to hopamp->hopamp->Init.TimerControlledMuxmode value */
/* Set bits according to hopamp->hopamp->Init.InvertingInputSecondary value */
/* Set bits according to hopamp->hopamp->Init.NonInvertingInputSecondary value */
/* Set bits according to hopamp->hopamp->Init.PgaConnect value */
/* Set bits according to hopamp->hopamp->Init.PgaGain value */
/* Set bits according to hopamp->hopamp->Init.UserTrimming value */
/* Set bits according to hopamp->hopamp->Init.TrimmingValueP value */
/* Set bits according to hopamp->hopamp->Init.TrimmingValueN value */
/* check if OPAMP_PGA_MODE & in Follower mode */
/* - InvertingInput */
/* is Not Applicable */
if ((hopamp->Init.Mode == OPAMP_PGA_MODE) || (hopamp->Init.Mode == OPAMP_FOLLOWER_MODE))
{
/* Update User Trim config first to be able to modify trimming value afterwards */
MODIFY_REG(hopamp->Instance->CSR,
OPAMP_CSR_USERTRIM,
hopamp->Init.UserTrimming);
MODIFY_REG(hopamp->Instance->CSR,
OPAMP_CSR_UPDATE_PARAMETERS_INIT_MASK,
hopamp->Init.PowerMode |
hopamp->Init.Mode |
hopamp->Init.NonInvertingInput |
((hopamp->Init.InternalOutput == ENABLE) ? OPAMP_CSR_OPAMPINTEN : 0UL) |
hopamp->Init.PgaConnect |
hopamp->Init.PgaGain |
(hopamp->Init.TrimmingValueP << OPAMP_INPUT_NONINVERTING) |
(hopamp->Init.TrimmingValueN << OPAMP_INPUT_INVERTING));
}
else /* OPAMP_STANDALONE_MODE */
{
/* Update User Trim config first to be able to modify trimming value afterwards */
MODIFY_REG(hopamp->Instance->CSR,
OPAMP_CSR_USERTRIM,
hopamp->Init.UserTrimming);
MODIFY_REG(hopamp->Instance->CSR,
OPAMP_CSR_UPDATE_PARAMETERS_INIT_MASK,
hopamp->Init.PowerMode |
hopamp->Init.Mode |
hopamp->Init.InvertingInput |
hopamp->Init.NonInvertingInput |
((hopamp->Init.InternalOutput == ENABLE) ? OPAMP_CSR_OPAMPINTEN : 0UL) |
hopamp->Init.PgaConnect |
hopamp->Init.PgaGain |
(hopamp->Init.TrimmingValueP << OPAMP_INPUT_NONINVERTING) |
(hopamp->Init.TrimmingValueN << OPAMP_INPUT_INVERTING));
}
if ((READ_BIT(hopamp->Instance->TCMR, OPAMP_TCMR_LOCK)) == 0UL)
{
MODIFY_REG(hopamp->Instance->TCMR,
OPAMP_TCMR_UPDATE_PARAMETERS_INIT_MASK,
hopamp->Init.TimerControlledMuxmode |
hopamp->Init.InvertingInputSecondary |
hopamp->Init.NonInvertingInputSecondary);
}
/* Update the OPAMP state*/
if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
/* From RESET state to READY State */
hopamp->State = HAL_OPAMP_STATE_READY;
}
/* else: remain in READY or BUSY state (no update) */
return status;
}
}
/**
* @brief DeInitializes the OPAMP peripheral
* @note Deinitialization can't be performed if the OPAMP configuration is locked.
* To unlock the configuration, perform a system reset.
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_DeInit(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation */
/* DeInit not allowed if calibration is ongoing */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_CALIBBUSY)
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
/* Set OPAMP_CSR register to reset value */
WRITE_REG(hopamp->Instance->CSR, OPAMP_CSR_RESET_VALUE);
/* DeInit the low level hardware: GPIO, CLOCK and NVIC */
/* When OPAMP is locked, unlocking can be achieved thanks to */
/* __HAL_RCC_SYSCFG_CLK_DISABLE() call within HAL_OPAMP_MspDeInit */
/* Note that __HAL_RCC_SYSCFG_CLK_DISABLE() also disables comparator */
#if (USE_HAL_OPAMP_REGISTER_CALLBACKS == 1)
if (hopamp->MspDeInitCallback == NULL)
{
hopamp->MspDeInitCallback = HAL_OPAMP_MspDeInit;
}
/* DeInit the low level hardware */
hopamp->MspDeInitCallback(hopamp);
#else
HAL_OPAMP_MspDeInit(hopamp);
#endif /* USE_HAL_OPAMP_REGISTER_CALLBACKS */
if (OPAMP_CSR_RESET_VALUE == (hopamp->Instance->CSR & OPAMP_CSR_RESET_CHECK_MASK))
{
/* Update the OPAMP state */
hopamp->State = HAL_OPAMP_STATE_RESET;
}
else /* RESET STATE */
{
/* DeInit not complete */
/* It can be the case if OPAMP was formerly locked */
status = HAL_ERROR;
/* The OPAMP state is NOT updated */
}
/* Process unlocked */
__HAL_UNLOCK(hopamp);
}
return status;
}
/**
* @brief Initialize the OPAMP MSP.
* @param hopamp OPAMP handle
* @retval None
*/
__weak void HAL_OPAMP_MspInit(OPAMP_HandleTypeDef *hopamp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hopamp);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_OPAMP_MspInit could be implemented in the user file
*/
/* Example */
}
/**
* @brief DeInitialize OPAMP MSP.
* @param hopamp OPAMP handle
* @retval None
*/
__weak void HAL_OPAMP_MspDeInit(OPAMP_HandleTypeDef *hopamp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hopamp);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_OPAMP_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup OPAMP_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 OPAMP data
transfers.
@endverbatim
* @{
*/
/**
* @brief Start the opamp
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_Start(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation */
/* Check if OPAMP locked */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_BUSYLOCKED)
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
if (hopamp->State == HAL_OPAMP_STATE_READY)
{
/* Enable the selected opamp */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_OPAMPxEN);
/* Update the OPAMP state*/
/* From HAL_OPAMP_STATE_READY to HAL_OPAMP_STATE_BUSY */
hopamp->State = HAL_OPAMP_STATE_BUSY;
}
else
{
status = HAL_ERROR;
}
}
return status;
}
/**
* @brief Stop the opamp
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_Stop(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation */
/* Check if OPAMP locked */
/* Check if OPAMP calibration ongoing */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_BUSYLOCKED)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_CALIBBUSY)
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
if (hopamp->State == HAL_OPAMP_STATE_BUSY)
{
/* Disable the selected opamp */
CLEAR_BIT(hopamp->Instance->CSR, OPAMP_CSR_OPAMPxEN);
/* Update the OPAMP state*/
/* From HAL_OPAMP_STATE_BUSY to HAL_OPAMP_STATE_READY*/
hopamp->State = HAL_OPAMP_STATE_READY;
}
else
{
status = HAL_ERROR;
}
}
return status;
}
/**
* @brief Run the self calibration of one OPAMP
* @note Calibration is performed in the mode specified in OPAMP init
* structure (mode normal or high-speed).
* @param hopamp handle
* @retval Updated offset trimming values (PMOS & NMOS), user trimming is enabled
* @retval HAL status
* @note Calibration runs about 25 ms.
*/
HAL_StatusTypeDef HAL_OPAMP_SelfCalibrate(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t trimmingvaluen;
uint32_t trimmingvaluep;
uint32_t delta;
/* Check the OPAMP handle allocation */
/* Check if OPAMP locked */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_BUSYLOCKED)
{
status = HAL_ERROR;
}
else
{
/* Check if OPAMP in calibration mode and calibration not yet enable */
if (hopamp->State == HAL_OPAMP_STATE_READY)
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
/* Set Calibration mode */
/* Non-inverting input connected to calibration reference voltage. */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_FORCEVP);
/* user trimming values are used for offset calibration */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_USERTRIM);
/* Enable calibration */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_CALON);
/* 1st calibration - N */
/* Select 90% VREF */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_90VDDA);
/* Enable the selected opamp */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_OPAMPxEN);
/* Init trimming counter */
/* Medium value */
trimmingvaluen = 16UL;
delta = 8UL;
while (delta != 0UL)
{
/* Set candidate trimming */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen << OPAMP_INPUT_INVERTING);
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluen += delta;
}
else
{
/* OPAMP_CSR_OUTCAL is LOW try lower trimming */
trimmingvaluen -= delta;
}
delta >>= 1;
}
/* Still need to check if righ calibration is current value or un step below */
/* Indeed the first value that causes the OUTCAL bit to change from 1 to 0 */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen << OPAMP_INPUT_INVERTING);
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluen++;
/* Set right trimming */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen << OPAMP_INPUT_INVERTING);
}
/* 2nd calibration - P */
/* Select 10% VREF */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_CALSEL, OPAMP_VREF_10VDDA);
/* Init trimming counter */
/* Medium value */
trimmingvaluep = 16UL;
delta = 8UL;
while (delta != 0UL)
{
/* Set candidate trimming */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep << OPAMP_INPUT_NONINVERTING);
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is HIGH try higher trimming */
trimmingvaluep += delta;
}
else
{
trimmingvaluep -= delta;
}
delta >>= 1;
}
/* Still need to check if righ calibration is current value or un step below */
/* Indeed the first value that causes the OUTCAL bit to change from 1 to 0U */
/* Set candidate trimming */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep << OPAMP_INPUT_NONINVERTING);
/* OFFTRIMmax delay 2 ms as per datasheet (electrical characteristics */
/* Offset trim time: during calibration, minimum time needed between */
/* two steps to have 1 mV accuracy */
HAL_Delay(2);
if ((hopamp->Instance->CSR & OPAMP_CSR_OUTCAL) != 0UL)
{
/* OPAMP_CSR_OUTCAL is actually one value more */
trimmingvaluep++;
/* Set right trimming */
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep << OPAMP_INPUT_NONINVERTING);
}
/* Disable calibration */
CLEAR_BIT(hopamp->Instance->CSR, OPAMP_CSR_CALON);
/* Disable the OPAMP */
CLEAR_BIT(hopamp->Instance->CSR, OPAMP_CSR_OPAMPxEN);
/* Set operating mode */
/* Non-inverting input connected to calibration reference voltage. */
CLEAR_BIT(hopamp->Instance->CSR, OPAMP_CSR_FORCEVP);
/* Self calibration is successful */
/* Store calibration(user timing) results in init structure. */
/* Write calibration result N */
hopamp->Init.TrimmingValueN = trimmingvaluen;
/* Write calibration result P */
hopamp->Init.TrimmingValueP = trimmingvaluep;
/* Select user timing mode */
/* And updated with calibrated settings */
hopamp->Init.UserTrimming = OPAMP_TRIMMING_USER;
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, trimmingvaluep << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, trimmingvaluen << OPAMP_INPUT_INVERTING);
}
else
{
/* OPAMP can not be calibrated from this mode */
status = HAL_ERROR;
}
}
return status;
}
/**
* @}
*/
/** @defgroup OPAMP_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the OPAMP data
transfers.
@endverbatim
* @{
*/
/**
* @brief Lock the selected opamp configuration.
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_Lock(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation */
/* Check if OPAMP locked */
/* OPAMP can be locked when enabled and running in normal mode */
/* It is meaningless otherwise */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State != HAL_OPAMP_STATE_BUSY)
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
/* Lock OPAMP */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_LOCK);
/* OPAMP state changed to locked */
hopamp->State = HAL_OPAMP_STATE_BUSYLOCKED;
}
return status;
}
/**
* @}
*/
/**
* @brief Lock the selected opamp timer controlled mux configuration.
* @param hopamp OPAMP handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_OPAMP_LockTimerMux(OPAMP_HandleTypeDef *hopamp)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the OPAMP handle allocation */
/* Check if OPAMP timer controlled mux is locked */
/* OPAMP timer controlled mux can be locked when enabled */
/* It is meaningless otherwise */
if (hopamp == NULL)
{
status = HAL_ERROR;
}
else if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
status = HAL_ERROR;
}
else if (READ_BIT(hopamp->Instance->TCMR, OPAMP_TCMR_LOCK) == OPAMP_TCMR_LOCK)
{
status = HAL_ERROR;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
/* Lock OPAMP */
SET_BIT(hopamp->Instance->TCMR, OPAMP_TCMR_LOCK);
}
return status;
}
/**
* @}
*/
/** @defgroup OPAMP_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the OPAMP state
* @param hopamp OPAMP handle
* @retval HAL state
*/
HAL_OPAMP_StateTypeDef HAL_OPAMP_GetState(OPAMP_HandleTypeDef *hopamp)
{
/* Check the OPAMP handle allocation */
if (hopamp == NULL)
{
return HAL_OPAMP_STATE_RESET;
}
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
return hopamp->State;
}
/**
* @brief Return the OPAMP factory trimming value
* @param hopamp OPAMP handle
* @param trimmingoffset Trimming offset (P or N)
* @retval Trimming value (P or N): range: 0->31
* or OPAMP_FACTORYTRIMMING_DUMMY if trimming value is not available
*/
OPAMP_TrimmingValueTypeDef HAL_OPAMP_GetTrimOffset(OPAMP_HandleTypeDef *hopamp, uint32_t trimmingoffset)
{
uint32_t oldusertrimming = 0UL;
OPAMP_TrimmingValueTypeDef oldtrimmingvaluep = 0UL, oldtrimmingvaluen = 0UL, trimmingvalue;
/* Check the OPAMP handle allocation */
/* Value can be retrieved in HAL_OPAMP_STATE_READY state */
if (hopamp == NULL)
{
return OPAMP_FACTORYTRIMMING_DUMMY;
}
else if (hopamp->State != HAL_OPAMP_STATE_READY)
{
return OPAMP_FACTORYTRIMMING_DUMMY;
}
else
{
/* Check the parameter */
assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));
assert_param(IS_OPAMP_FACTORYTRIMMING(trimmingoffset));
/* Check the trimming mode */
if ((READ_BIT(hopamp->Instance->CSR, OPAMP_CSR_USERTRIM)) != 0UL)
{
/* User trimming is used */
oldusertrimming = OPAMP_TRIMMING_USER;
/* Store the TrimmingValueP & TrimmingValueN */
oldtrimmingvaluep = (hopamp->Instance->CSR & OPAMP_CSR_TRIMOFFSETP) >> OPAMP_INPUT_NONINVERTING;
oldtrimmingvaluen = (hopamp->Instance->CSR & OPAMP_CSR_TRIMOFFSETN) >> OPAMP_INPUT_INVERTING;
}
/* Set factory timing mode */
CLEAR_BIT(hopamp->Instance->CSR, OPAMP_CSR_USERTRIM);
/* Get factory trimming */
if (trimmingoffset == OPAMP_FACTORYTRIMMING_P)
{
/* Return TrimOffsetP */
trimmingvalue = ((hopamp->Instance->CSR & OPAMP_CSR_TRIMOFFSETP) >> OPAMP_INPUT_NONINVERTING);
}
else
{
/* Return TrimOffsetN */
trimmingvalue = ((hopamp->Instance->CSR & OPAMP_CSR_TRIMOFFSETN) >> OPAMP_INPUT_INVERTING);
}
/* Restore user trimming configuration if it was formerly set */
/* Check if user trimming was used */
if (oldusertrimming == OPAMP_TRIMMING_USER)
{
/* Restore user trimming */
SET_BIT(hopamp->Instance->CSR, OPAMP_CSR_USERTRIM);
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETP, oldtrimmingvaluep << OPAMP_INPUT_NONINVERTING);
MODIFY_REG(hopamp->Instance->CSR, OPAMP_CSR_TRIMOFFSETN, oldtrimmingvaluen << OPAMP_INPUT_INVERTING);
}
}
return trimmingvalue;
}
/**
* @}
*/
#if (USE_HAL_OPAMP_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User OPAMP Callback
* To be used instead of the weak (surcharged) predefined callback
* @param hopamp : OPAMP handle
* @param CallbackID : ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_OPAMP_MSPINIT_CB_ID OPAMP MspInit callback ID
* @arg @ref HAL_OPAMP_MSPDEINIT_CB_ID OPAMP MspDeInit callback ID
* @param pCallback : pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_OPAMP_RegisterCallback(OPAMP_HandleTypeDef *hopamp, HAL_OPAMP_CallbackIDTypeDef CallbackId,
pOPAMP_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hopamp);
if (hopamp->State == HAL_OPAMP_STATE_READY)
{
switch (CallbackId)
{
case HAL_OPAMP_MSPINIT_CB_ID :
hopamp->MspInitCallback = pCallback;
break;
case HAL_OPAMP_MSPDEINIT_CB_ID :
hopamp->MspDeInitCallback = pCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
switch (CallbackId)
{
case HAL_OPAMP_MSPINIT_CB_ID :
hopamp->MspInitCallback = pCallback;
break;
case HAL_OPAMP_MSPDEINIT_CB_ID :
hopamp->MspDeInitCallback = pCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hopamp);
return status;
}
/**
* @brief Unregister a User OPAMP Callback
* OPAMP Callback is redirected to the weak (surcharged) predefined callback
* @param hopamp : OPAMP handle
* @param CallbackID : ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_OPAMP_MSPINIT_CB_ID OPAMP MSP Init Callback ID
* @arg @ref HAL_OPAMP_MSPDEINIT_CB_ID OPAMP MSP DeInit Callback ID
* @arg @ref HAL_OPAMP_ALL_CB_ID OPAMP All Callbacks
* @retval status
*/
HAL_StatusTypeDef HAL_OPAMP_UnRegisterCallback(OPAMP_HandleTypeDef *hopamp, HAL_OPAMP_CallbackIDTypeDef CallbackId)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hopamp);
if (hopamp->State == HAL_OPAMP_STATE_READY)
{
switch (CallbackId)
{
case HAL_OPAMP_MSPINIT_CB_ID :
hopamp->MspInitCallback = HAL_OPAMP_MspInit;
break;
case HAL_OPAMP_MSPDEINIT_CB_ID :
hopamp->MspDeInitCallback = HAL_OPAMP_MspDeInit;
break;
case HAL_OPAMP_ALL_CB_ID :
hopamp->MspInitCallback = HAL_OPAMP_MspInit;
hopamp->MspDeInitCallback = HAL_OPAMP_MspDeInit;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hopamp->State == HAL_OPAMP_STATE_RESET)
{
switch (CallbackId)
{
case HAL_OPAMP_MSPINIT_CB_ID :
hopamp->MspInitCallback = HAL_OPAMP_MspInit;
break;
case HAL_OPAMP_MSPDEINIT_CB_ID :
hopamp->MspDeInitCallback = HAL_OPAMP_MspDeInit;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hopamp);
return status;
}
#endif /* USE_HAL_OPAMP_REGISTER_CALLBACKS */
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_OPAMP_MODULE_ENABLED */
/**
* @}
*/
| 41,916 |
C
| 33.843724 | 115 | 0.574625 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_sram.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
#if defined(FMC_BANK1)
/** @addtogroup STM32G4xx_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);
/* 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;
/* 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;
/* Enable the DMA Stream */
status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)BufferSize);
/* 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;
/* 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;
/* Enable the DMA Stream */
status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)BufferSize);
/* 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 */
/**
* @}
*/
#endif /* FMC_BANK1 */
| 33,600 |
C
| 29.243924 | 112 | 0.620685 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_irda.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_irda.c
* @author MCD Application Team
* @brief IRDA HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the IrDA (Infrared Data Association) Peripheral
* (IRDA)
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
* + Peripheral Control functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The IRDA HAL driver can be used as follows:
(#) Declare a IRDA_HandleTypeDef handle structure (eg. IRDA_HandleTypeDef hirda).
(#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API
in setting the associated USART or UART in IRDA mode:
(++) Enable the USARTx/UARTx interface clock.
(++) USARTx/UARTx pins configuration:
(+++) Enable the clock for the USARTx/UARTx GPIOs.
(+++) Configure these USARTx/UARTx pins (TX as alternate function pull-up, RX as alternate function Input).
(++) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT()
and HAL_IRDA_Receive_IT() APIs):
(+++) Configure the USARTx/UARTx interrupt priority.
(+++) Enable the NVIC USARTx/UARTx IRQ handle.
(+++) The specific IRDA interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
(++) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA()
and HAL_IRDA_Receive_DMA() APIs):
(+++) Declare a DMA handle structure for the Tx/Rx channel.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
(+++) Configure the DMA Tx/Rx channel.
(+++) Associate the initialized DMA handle to the IRDA DMA Tx/Rx handle.
(+++) Configure the priority and enable the NVIC for the transfer
complete interrupt on the DMA Tx/Rx channel.
(#) Program the Baud Rate, Word Length and Parity and Mode(Receiver/Transmitter),
the normal or low power mode and the clock prescaler in the hirda handle Init structure.
(#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API:
(++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
by calling the customized HAL_IRDA_MspInit() API.
-@@- The specific IRDA interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
(#) Three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Send an amount of data in blocking mode using HAL_IRDA_Transmit()
(+) Receive an amount of data in blocking mode using HAL_IRDA_Receive()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Send an amount of data in non-blocking mode using HAL_IRDA_Transmit_IT()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback()
(+) Receive an amount of data in non-blocking mode using HAL_IRDA_Receive_IT()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback()
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback()
*** DMA mode IO operation ***
==============================
[..]
(+) Send an amount of data in non-blocking mode (DMA) using HAL_IRDA_Transmit_DMA()
(+) At transmission half of transfer HAL_IRDA_TxHalfCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxHalfCpltCallback()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback()
(+) Receive an amount of data in non-blocking mode (DMA) using HAL_IRDA_Receive_DMA()
(+) At reception half of transfer HAL_IRDA_RxHalfCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxHalfCpltCallback()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback()
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback()
*** IRDA HAL driver macros list ***
====================================
[..]
Below the list of most used macros in IRDA HAL driver.
(+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral
(+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral
(+) __HAL_IRDA_GET_FLAG : Check whether the specified IRDA flag is set or not
(+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag
(+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt
(+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt
(+) __HAL_IRDA_GET_IT_SOURCE: Check whether or not the specified IRDA interrupt is enabled
[..]
(@) You can refer to the IRDA HAL driver header file for more useful macros
##### Callback registration #####
==================================
[..]
The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
[..]
Use Function HAL_IRDA_RegisterCallback() to register a user callback.
Function HAL_IRDA_RegisterCallback() allows to register following callbacks:
(+) TxHalfCpltCallback : Tx Half Complete Callback.
(+) TxCpltCallback : Tx Complete Callback.
(+) RxHalfCpltCallback : Rx Half Complete Callback.
(+) RxCpltCallback : Rx Complete Callback.
(+) ErrorCallback : Error Callback.
(+) AbortCpltCallback : Abort Complete Callback.
(+) AbortTransmitCpltCallback : Abort Transmit Complete Callback.
(+) AbortReceiveCpltCallback : Abort Receive Complete Callback.
(+) MspInitCallback : IRDA MspInit.
(+) MspDeInitCallback : IRDA MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_IRDA_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function.
HAL_IRDA_UnRegisterCallback() takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) TxHalfCpltCallback : Tx Half Complete Callback.
(+) TxCpltCallback : Tx Complete Callback.
(+) RxHalfCpltCallback : Rx Half Complete Callback.
(+) RxCpltCallback : Rx Complete Callback.
(+) ErrorCallback : Error Callback.
(+) AbortCpltCallback : Abort Complete Callback.
(+) AbortTransmitCpltCallback : Abort Transmit Complete Callback.
(+) AbortReceiveCpltCallback : Abort Receive Complete Callback.
(+) MspInitCallback : IRDA MspInit.
(+) MspDeInitCallback : IRDA MspDeInit.
[..]
By default, after the HAL_IRDA_Init() and when the state is HAL_IRDA_STATE_RESET
all callbacks are set to the corresponding weak (surcharged) functions:
examples HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxHalfCpltCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) functions in the HAL_IRDA_Init()
and HAL_IRDA_DeInit() only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_IRDA_Init() and HAL_IRDA_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand).
[..]
Callbacks can be registered/unregistered in HAL_IRDA_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_IRDA_STATE_READY or HAL_IRDA_STATE_RESET state, thus registered (user)
MspInit/DeInit callbacks can be used during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_IRDA_RegisterCallback() before calling HAL_IRDA_DeInit()
or HAL_IRDA_Init() function.
[..]
When The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available
and weak (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup IRDA IRDA
* @brief HAL IRDA module driver
* @{
*/
#ifdef HAL_IRDA_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IRDA_Private_Constants IRDA Private Constants
* @{
*/
#define IRDA_TEACK_REACK_TIMEOUT 1000U /*!< IRDA TX or RX enable acknowledge time-out value */
#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \
| USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) /*!< UART or USART CR1 fields of parameters set by IRDA_SetConfig API */
#define USART_BRR_MIN 0x10U /*!< USART BRR minimum authorized value */
#define USART_BRR_MAX 0x0000FFFFU /*!< USART BRR maximum authorized value */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup IRDA_Private_Macros IRDA Private Macros
* @{
*/
/** @brief BRR division operation to set BRR register in 16-bit oversampling mode.
* @param __PCLK__ IRDA clock source.
* @param __BAUD__ Baud rate set by the user.
* @param __PRESCALER__ IRDA clock prescaler value.
* @retval Division result
*/
#define IRDA_DIV_SAMPLING16(__PCLK__, __BAUD__, __PRESCALER__) ((((__PCLK__)/IRDAPrescTable[(__PRESCALER__)])\
+ ((__BAUD__)/2U)) / (__BAUD__))
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup IRDA_Private_Functions
* @{
*/
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status,
uint32_t Tickstart, uint32_t Timeout);
static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda);
static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda);
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAError(DMA_HandleTypeDef *hdma);
static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma);
static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda);
static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda);
static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup IRDA_Exported_Functions IRDA Exported Functions
* @{
*/
/** @defgroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### Initialization and Configuration functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to initialize the USARTx
in asynchronous IRDA mode.
(+) For the asynchronous mode only these parameters can be configured:
(++) Baud Rate
(++) Word Length
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
(++) Power mode
(++) Prescaler setting
(++) Receiver/transmitter modes
[..]
The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures
(details for the procedures are available in reference manual).
@endverbatim
Depending on the frame length defined by the M1 and M0 bits (7-bit,
8-bit or 9-bit), the possible IRDA frame formats are listed in the
following table.
Table 1. IRDA frame format.
+-----------------------------------------------------------------------+
| M1 bit | M0 bit | PCE bit | IRDA frame |
|---------|---------|-----------|---------------------------------------|
| 0 | 0 | 0 | | SB | 8 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 0 | 1 | | SB | 7 bit data | PB | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 1 | 0 | | SB | 9 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 1 | 1 | | SB | 8 bit data | PB | STB | |
|---------|---------|-----------|---------------------------------------|
| 1 | 0 | 0 | | SB | 7 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 1 | 0 | 1 | | SB | 6 bit data | PB | STB | |
+-----------------------------------------------------------------------+
* @{
*/
/**
* @brief Initialize the IRDA mode according to the specified
* parameters in the IRDA_InitTypeDef and initialize the associated handle.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if (hirda == NULL)
{
return HAL_ERROR;
}
/* Check the USART/UART associated to the IRDA handle */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
if (hirda->gState == HAL_IRDA_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hirda->Lock = HAL_UNLOCKED;
#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1
IRDA_InitCallbacksToDefault(hirda);
if (hirda->MspInitCallback == NULL)
{
hirda->MspInitCallback = HAL_IRDA_MspInit;
}
/* Init the low level hardware */
hirda->MspInitCallback(hirda);
#else
/* Init the low level hardware : GPIO, CLOCK */
HAL_IRDA_MspInit(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
}
hirda->gState = HAL_IRDA_STATE_BUSY;
/* Disable the Peripheral to update the configuration registers */
__HAL_IRDA_DISABLE(hirda);
/* Set the IRDA Communication parameters */
if (IRDA_SetConfig(hirda) == HAL_ERROR)
{
return HAL_ERROR;
}
/* In IRDA mode, the following bits must be kept cleared:
- LINEN, STOP and CLKEN bits in the USART_CR2 register,
- SCEN and HDSEL bits in the USART_CR3 register.*/
CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP));
CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL));
/* set the UART/USART in IRDA mode */
hirda->Instance->CR3 |= USART_CR3_IREN;
/* Enable the Peripheral */
__HAL_IRDA_ENABLE(hirda);
/* TEACK and/or REACK to check before moving hirda->gState and hirda->RxState to Ready */
return (IRDA_CheckIdleState(hirda));
}
/**
* @brief DeInitialize the IRDA peripheral.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if (hirda == NULL)
{
return HAL_ERROR;
}
/* Check the USART/UART associated to the IRDA handle */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
hirda->gState = HAL_IRDA_STATE_BUSY;
/* DeInit the low level hardware */
#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1
if (hirda->MspDeInitCallback == NULL)
{
hirda->MspDeInitCallback = HAL_IRDA_MspDeInit;
}
/* DeInit the low level hardware */
hirda->MspDeInitCallback(hirda);
#else
HAL_IRDA_MspDeInit(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
/* Disable the Peripheral */
__HAL_IRDA_DISABLE(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_RESET;
hirda->RxState = HAL_IRDA_STATE_RESET;
/* Process Unlock */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Initialize the IRDA MSP.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the IRDA MSP.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspDeInit can be implemented in the user file
*/
}
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User IRDA Callback
* To be used instead of the weak predefined callback
* @param hirda irda handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID
* @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID
* @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID
* @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID
* @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID
* @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID
* @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID
* @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID
* @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID
* @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_RegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID,
pIRDA_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hirda);
if (hirda->gState == HAL_IRDA_STATE_READY)
{
switch (CallbackID)
{
case HAL_IRDA_TX_HALFCOMPLETE_CB_ID :
hirda->TxHalfCpltCallback = pCallback;
break;
case HAL_IRDA_TX_COMPLETE_CB_ID :
hirda->TxCpltCallback = pCallback;
break;
case HAL_IRDA_RX_HALFCOMPLETE_CB_ID :
hirda->RxHalfCpltCallback = pCallback;
break;
case HAL_IRDA_RX_COMPLETE_CB_ID :
hirda->RxCpltCallback = pCallback;
break;
case HAL_IRDA_ERROR_CB_ID :
hirda->ErrorCallback = pCallback;
break;
case HAL_IRDA_ABORT_COMPLETE_CB_ID :
hirda->AbortCpltCallback = pCallback;
break;
case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID :
hirda->AbortTransmitCpltCallback = pCallback;
break;
case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID :
hirda->AbortReceiveCpltCallback = pCallback;
break;
case HAL_IRDA_MSPINIT_CB_ID :
hirda->MspInitCallback = pCallback;
break;
case HAL_IRDA_MSPDEINIT_CB_ID :
hirda->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hirda->gState == HAL_IRDA_STATE_RESET)
{
switch (CallbackID)
{
case HAL_IRDA_MSPINIT_CB_ID :
hirda->MspInitCallback = pCallback;
break;
case HAL_IRDA_MSPDEINIT_CB_ID :
hirda->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hirda);
return status;
}
/**
* @brief Unregister an IRDA callback
* IRDA callback is redirected to the weak predefined callback
* @param hirda irda handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID
* @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID
* @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID
* @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID
* @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID
* @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID
* @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID
* @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID
* @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID
* @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_UnRegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hirda);
if (HAL_IRDA_STATE_READY == hirda->gState)
{
switch (CallbackID)
{
case HAL_IRDA_TX_HALFCOMPLETE_CB_ID :
hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */
break;
case HAL_IRDA_TX_COMPLETE_CB_ID :
hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */
break;
case HAL_IRDA_RX_HALFCOMPLETE_CB_ID :
hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */
break;
case HAL_IRDA_RX_COMPLETE_CB_ID :
hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */
break;
case HAL_IRDA_ERROR_CB_ID :
hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_IRDA_ABORT_COMPLETE_CB_ID :
hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */
break;
case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID :
hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak
AbortTransmitCpltCallback */
break;
case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID :
hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak
AbortReceiveCpltCallback */
break;
case HAL_IRDA_MSPINIT_CB_ID :
hirda->MspInitCallback = HAL_IRDA_MspInit; /* Legacy weak MspInitCallback */
break;
case HAL_IRDA_MSPDEINIT_CB_ID :
hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; /* Legacy weak MspDeInitCallback */
break;
default :
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_IRDA_STATE_RESET == hirda->gState)
{
switch (CallbackID)
{
case HAL_IRDA_MSPINIT_CB_ID :
hirda->MspInitCallback = HAL_IRDA_MspInit;
break;
case HAL_IRDA_MSPDEINIT_CB_ID :
hirda->MspDeInitCallback = HAL_IRDA_MspDeInit;
break;
default :
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hirda);
return status;
}
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions
* @brief IRDA Transmit and Receive functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the IRDA data transfers.
[..]
IrDA is a half duplex communication protocol. If the Transmitter is busy, any data
on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver
is busy, data on the TX from the USART to IrDA will not be encoded by IrDA.
While receiving data, transmission should be avoided as the data to be transmitted
could be corrupted.
[..]
(#) There are two modes of transfer:
(++) Blocking mode: the communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(++) Non-Blocking mode: the communication is performed using Interrupts
or DMA, these API's return the HAL status.
The end of the data processing will be indicated through the
dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks
will be executed respectively at the end of the Transmit or Receive process
The HAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected
(#) Blocking mode APIs are :
(++) HAL_IRDA_Transmit()
(++) HAL_IRDA_Receive()
(#) Non Blocking mode APIs with Interrupt are :
(++) HAL_IRDA_Transmit_IT()
(++) HAL_IRDA_Receive_IT()
(++) HAL_IRDA_IRQHandler()
(#) Non Blocking mode functions with DMA are :
(++) HAL_IRDA_Transmit_DMA()
(++) HAL_IRDA_Receive_DMA()
(++) HAL_IRDA_DMAPause()
(++) HAL_IRDA_DMAResume()
(++) HAL_IRDA_DMAStop()
(#) A set of Transfer Complete Callbacks are provided in Non Blocking mode:
(++) HAL_IRDA_TxHalfCpltCallback()
(++) HAL_IRDA_TxCpltCallback()
(++) HAL_IRDA_RxHalfCpltCallback()
(++) HAL_IRDA_RxCpltCallback()
(++) HAL_IRDA_ErrorCallback()
(#) Non-Blocking mode transfers could be aborted using Abort API's :
(++) HAL_IRDA_Abort()
(++) HAL_IRDA_AbortTransmit()
(++) HAL_IRDA_AbortReceive()
(++) HAL_IRDA_Abort_IT()
(++) HAL_IRDA_AbortTransmit_IT()
(++) HAL_IRDA_AbortReceive_IT()
(#) For Abort services based on interrupts (HAL_IRDA_Abortxxx_IT), a set of Abort Complete Callbacks are provided:
(++) HAL_IRDA_AbortCpltCallback()
(++) HAL_IRDA_AbortTransmitCpltCallback()
(++) HAL_IRDA_AbortReceiveCpltCallback()
(#) In Non-Blocking mode transfers, possible errors are split into 2 categories.
Errors are handled as follows :
(++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is
to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error
in Interrupt mode reception .
Received character is then retrieved and stored in Rx buffer, Error code is set to allow user
to identify error type, and HAL_IRDA_ErrorCallback() user callback is executed.
Transfer is kept ongoing on IRDA side.
If user wants to abort it, Abort services should be called by user.
(++) Error is considered as Blocking : Transfer could not be completed properly and is aborted.
This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode.
Error code is set to allow user to identify error type, and
HAL_IRDA_ErrorCallback() user callback is executed.
@endverbatim
* @{
*/
/**
* @brief Send an amount of data in blocking mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be sent.
* @param Timeout Specify timeout value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
const uint8_t *pdata8bits;
const uint16_t *pdata16bits;
uint32_t tickstart;
/* Check that a Tx process is not already ongoing */
if (hirda->gState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
/* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
pdata8bits = NULL;
pdata16bits = (const uint16_t *) pData; /* Derogation R.11.3 */
}
else
{
pdata8bits = pData;
pdata16bits = NULL;
}
while (hirda->TxXferCount > 0U)
{
hirda->TxXferCount--;
if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (pdata8bits == NULL)
{
hirda->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU);
pdata16bits++;
}
else
{
hirda->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU);
pdata8bits++;
}
}
if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* At end of Tx process, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in blocking mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the received data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be received.
* @param Timeout Specify timeout value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint8_t *pdata8bits;
uint16_t *pdata16bits;
uint16_t uhMask;
uint32_t tickstart;
/* Check that a Rx process is not already ongoing */
if (hirda->RxState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
/* Computation of the mask to apply to RDR register
of the UART associated to the IRDA */
IRDA_MASK_COMPUTATION(hirda);
uhMask = hirda->Mask;
/* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
pdata8bits = NULL;
pdata16bits = (uint16_t *) pData; /* Derogation R.11.3 */
}
else
{
pdata8bits = pData;
pdata16bits = NULL;
}
/* Check data remaining to be received */
while (hirda->RxXferCount > 0U)
{
hirda->RxXferCount--;
if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (pdata8bits == NULL)
{
*pdata16bits = (uint16_t)(hirda->Instance->RDR & uhMask);
pdata16bits++;
}
else
{
*pdata8bits = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask);
pdata8bits++;
}
}
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Send an amount of data in interrupt mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size)
{
/* Check that a Tx process is not already ongoing */
if (hirda->gState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the IRDA Transmit Data Register Empty Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in interrupt mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the received data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be received.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Rx process is not already ongoing */
if (hirda->RxState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
/* Computation of the mask to apply to the RDR register
of the UART associated to the IRDA */
IRDA_MASK_COMPUTATION(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
if (hirda->Init.Parity != IRDA_PARITY_NONE)
{
/* Enable the IRDA Parity Error and Data Register not empty Interrupts */
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE);
}
else
{
/* Enable the IRDA Data Register not empty Interrupts */
SET_BIT(hirda->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE);
}
/* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Send an amount of data in DMA mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the sent data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size)
{
/* Check that a Tx process is not already ongoing */
if (hirda->gState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Set the IRDA DMA transfer complete callback */
hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt;
/* Set the IRDA DMA half transfer complete callback */
hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt;
/* Set the DMA error callback */
hirda->hdmatx->XferErrorCallback = IRDA_DMAError;
/* Set the DMA abort callback */
hirda->hdmatx->XferAbortCallback = NULL;
/* Enable the IRDA transmit DMA channel */
if (HAL_DMA_Start_IT(hirda->hdmatx, (uint32_t)hirda->pTxBuffPtr, (uint32_t)&hirda->Instance->TDR, Size) == HAL_OK)
{
/* Clear the TC flag in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_TCF);
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
return HAL_OK;
}
else
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Restore hirda->gState to ready */
hirda->gState = HAL_IRDA_STATE_READY;
return HAL_ERROR;
}
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in DMA mode.
* @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
* the received data is handled as a set of u16. In this case, Size must reflect the number
* of u16 available through pData.
* @note When the IRDA parity is enabled (PCE = 1), the received data contains
* the parity bit (MSB position).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be received.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Rx process is not already ongoing */
if (hirda->RxState == HAL_IRDA_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Set the IRDA DMA transfer complete callback */
hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt;
/* Set the IRDA DMA half transfer complete callback */
hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt;
/* Set the DMA error callback */
hirda->hdmarx->XferErrorCallback = IRDA_DMAError;
/* Set the DMA abort callback */
hirda->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, (uint32_t)hirda->pRxBuffPtr, Size) == HAL_OK)
{
/* Process Unlocked */
__HAL_UNLOCK(hirda);
if (hirda->Init.Parity != IRDA_PARITY_NONE)
{
/* Enable the UART Parity Error Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
}
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Enable the DMA transfer for the receiver request by setting the DMAR bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
return HAL_OK;
}
else
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Restore hirda->RxState to ready */
hirda->RxState = HAL_IRDA_STATE_READY;
return HAL_ERROR;
}
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pause the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
/* Disable the IRDA DMA Tx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
}
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Resume the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
/* Enable the IRDA DMA Tx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
/* Clear the Overrun flag before resuming the Rx transfer*/
__HAL_IRDA_CLEAR_OREFLAG(hirda);
/* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */
if (hirda->Init.Parity != IRDA_PARITY_NONE)
{
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
}
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Enable the IRDA DMA Rx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Stop the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda)
{
/* The Lock is not implemented on this API to allow the user application
to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() /
HAL_IRDA_TxHalfCpltCallback / HAL_IRDA_RxHalfCpltCallback:
indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete
interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of
the stream and the corresponding call back is executed. */
/* Stop IRDA DMA Tx request if ongoing */
if (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel */
if (hirda->hdmatx != NULL)
{
if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
IRDA_EndTxTransfer(hirda);
}
}
/* Stop IRDA DMA Rx request if ongoing */
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel */
if (hirda->hdmarx != NULL)
{
if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
IRDA_EndRxTransfer(hirda);
}
}
return HAL_OK;
}
/**
* @brief Abort ongoing transfers (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx and Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \
USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */
if (hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */
if (hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* Reset Tx and Rx transfer counters */
hirda->TxXferCount = 0U;
hirda->RxXferCount = 0U;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Reset Handle ErrorCode to No Error */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
return HAL_OK;
}
/**
* @brief Abort ongoing Transmit transfer (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE));
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */
if (hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* Reset Tx transfer counter */
hirda->TxXferCount = 0U;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief Abort ongoing Receive transfer (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */
if (hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = NULL;
if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK)
{
if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT)
{
/* Set error code to DMA */
hirda->ErrorCode = HAL_IRDA_ERROR_DMA;
return HAL_TIMEOUT;
}
}
}
}
/* Reset Rx transfer counter */
hirda->RxXferCount = 0U;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief Abort ongoing transfers (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx and Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda)
{
uint32_t abortcplt = 1U;
/* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \
USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised
before any call to DMA Abort functions */
/* DMA Tx Handle is valid */
if (hirda->hdmatx != NULL)
{
/* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled.
Otherwise, set it to NULL */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback;
}
else
{
hirda->hdmatx->XferAbortCallback = NULL;
}
}
/* DMA Rx Handle is valid */
if (hirda->hdmarx != NULL)
{
/* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled.
Otherwise, set it to NULL */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback;
}
else
{
hirda->hdmarx->XferAbortCallback = NULL;
}
}
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
/* Disable DMA Tx at UART level */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */
if (hirda->hdmatx != NULL)
{
/* IRDA Tx DMA Abort callback has already been initialised :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK)
{
hirda->hdmatx->XferAbortCallback = NULL;
}
else
{
abortcplt = 0U;
}
}
}
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */
if (hirda->hdmarx != NULL)
{
/* IRDA Rx DMA Abort callback has already been initialised :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
hirda->hdmarx->XferAbortCallback = NULL;
abortcplt = 1U;
}
else
{
abortcplt = 0U;
}
}
}
/* if no DMA abort complete callback execution is required => call user Abort Complete callback */
if (abortcplt == 1U)
{
/* Reset Tx and Rx transfer counters */
hirda->TxXferCount = 0U;
hirda->RxXferCount = 0U;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort complete callback */
hirda->AbortCpltCallback(hirda);
#else
/* Call legacy weak Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
return HAL_OK;
}
/**
* @brief Abort ongoing Transmit transfer (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE));
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */
if (hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback;
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK)
{
/* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */
hirda->hdmatx->XferAbortCallback(hirda->hdmatx);
}
}
else
{
/* Reset Tx transfer counter */
hirda->TxXferCount = 0U;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Transmit Complete Callback */
hirda->AbortTransmitCpltCallback(hirda);
#else
/* Call legacy weak Abort Transmit Complete Callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
}
else
{
/* Reset Tx transfer counter */
hirda->TxXferCount = 0U;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Transmit Complete Callback */
hirda->AbortTransmitCpltCallback(hirda);
#else
/* Call legacy weak Abort Transmit Complete Callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
return HAL_OK;
}
/**
* @brief Abort ongoing Receive transfer (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */
if (hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
/* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */
hirda->hdmarx->XferAbortCallback(hirda->hdmarx);
}
}
else
{
/* Reset Rx transfer counter */
hirda->RxXferCount = 0U;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Receive Complete Callback */
hirda->AbortReceiveCpltCallback(hirda);
#else
/* Call legacy weak Abort Receive Complete Callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
}
else
{
/* Reset Rx transfer counter */
hirda->RxXferCount = 0U;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Receive Complete Callback */
hirda->AbortReceiveCpltCallback(hirda);
#else
/* Call legacy weak Abort Receive Complete Callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
return HAL_OK;
}
/**
* @brief Handle IRDA interrupt request.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda)
{
uint32_t isrflags = READ_REG(hirda->Instance->ISR);
uint32_t cr1its = READ_REG(hirda->Instance->CR1);
uint32_t cr3its;
uint32_t errorflags;
uint32_t errorcode;
/* If no error occurs */
errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE));
if (errorflags == 0U)
{
/* IRDA in mode Receiver ---------------------------------------------------*/
if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U))
{
IRDA_Receive_IT(hirda);
return;
}
}
/* If some errors occur */
cr3its = READ_REG(hirda->Instance->CR3);
if ((errorflags != 0U)
&& (((cr3its & USART_CR3_EIE) != 0U)
|| ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U)))
{
/* IRDA parity error interrupt occurred -------------------------------------*/
if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_PE;
}
/* IRDA frame error interrupt occurred --------------------------------------*/
if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_FE;
}
/* IRDA noise error interrupt occurred --------------------------------------*/
if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_NE;
}
/* IRDA Over-Run interrupt occurred -----------------------------------------*/
if (((isrflags & USART_ISR_ORE) != 0U) &&
(((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_EIE) != 0U)))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF);
hirda->ErrorCode |= HAL_IRDA_ERROR_ORE;
}
/* Call IRDA Error Call back function if need be --------------------------*/
if (hirda->ErrorCode != HAL_IRDA_ERROR_NONE)
{
/* IRDA in mode Receiver ---------------------------------------------------*/
if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U))
{
IRDA_Receive_IT(hirda);
}
/* If Overrun error occurs, or if any error occurs in DMA mode reception,
consider error as blocking */
errorcode = hirda->ErrorCode;
if ((HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) ||
((errorcode & HAL_IRDA_ERROR_ORE) != 0U))
{
/* Blocking error : transfer is aborted
Set the IRDA state ready to be able to start again the process,
Disable Rx Interrupts, and disable Rx DMA request, if ongoing */
IRDA_EndRxTransfer(hirda);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel */
if (hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_ErrorCallback() at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError;
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
/* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */
hirda->hdmarx->XferAbortCallback(hirda->hdmarx);
}
}
else
{
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered user error callback */
hirda->ErrorCallback(hirda);
#else
/* Call legacy weak user error callback */
HAL_IRDA_ErrorCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
}
else
{
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered user error callback */
hirda->ErrorCallback(hirda);
#else
/* Call legacy weak user error callback */
HAL_IRDA_ErrorCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
}
else
{
/* Non Blocking error : transfer could go on.
Error is notified to user through user error callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered user error callback */
hirda->ErrorCallback(hirda);
#else
/* Call legacy weak user error callback */
HAL_IRDA_ErrorCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
}
}
return;
} /* End if some error occurs */
/* IRDA in mode Transmitter ------------------------------------------------*/
if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) && ((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U))
{
IRDA_Transmit_IT(hirda);
return;
}
/* IRDA in mode Transmitter (transmission end) -----------------------------*/
if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U))
{
IRDA_EndTransmit_IT(hirda);
return;
}
}
/**
* @brief Tx Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_TxCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Tx Half Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified USART module.
* @retval None
*/
__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Rx Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_RxCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Rx Half Transfer complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA error callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_ErrorCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Receive Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file.
*/
}
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group4 Peripheral State and Error functions
* @brief IRDA State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Error functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to return the State of IrDA
communication process and also return Peripheral Errors occurred during communication process
(+) HAL_IRDA_GetState() API can be helpful to check in run-time the state
of the IRDA peripheral handle.
(+) HAL_IRDA_GetError() checks in run-time errors that could occur during
communication.
@endverbatim
* @{
*/
/**
* @brief Return the IRDA handle state.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL state
*/
HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda)
{
/* Return IRDA handle state */
uint32_t temp1;
uint32_t temp2;
temp1 = (uint32_t)hirda->gState;
temp2 = (uint32_t)hirda->RxState;
return (HAL_IRDA_StateTypeDef)(temp1 | temp2);
}
/**
* @brief Return the IRDA handle error code.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval IRDA Error Code
*/
uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda)
{
return hirda->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup IRDA_Private_Functions IRDA Private Functions
* @{
*/
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/**
* @brief Initialize the callbacks to their default values.
* @param hirda IRDA handle.
* @retval none
*/
void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda)
{
/* Init the IRDA Callback settings */
hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */
hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */
hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */
hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */
hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */
hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */
hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */
hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */
}
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
/**
* @brief Configure the IRDA peripheral.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
uint32_t tmpreg;
IRDA_ClockSourceTypeDef clocksource;
HAL_StatusTypeDef ret = HAL_OK;
static const uint16_t IRDAPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U};
uint32_t pclk;
/* Check the communication parameters */
assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));
assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
assert_param(IS_IRDA_TX_RX_MODE(hirda->Init.Mode));
assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler));
assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode));
assert_param(IS_IRDA_CLOCKPRESCALER(hirda->Init.ClockPrescaler));
/*-------------------------- USART CR1 Configuration -----------------------*/
/* Configure the IRDA Word Length, Parity and transfer Mode:
Set the M bits according to hirda->Init.WordLength value
Set PCE and PS bits according to hirda->Init.Parity value
Set TE and RE bits according to hirda->Init.Mode value */
tmpreg = (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode ;
MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg);
/*-------------------------- USART CR3 Configuration -----------------------*/
MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode);
/*--------------------- USART clock PRESC Configuration ----------------*/
/* Configure
* - IRDA Clock Prescaler: set PRESCALER according to hirda->Init.ClockPrescaler value */
MODIFY_REG(hirda->Instance->PRESC, USART_PRESC_PRESCALER, hirda->Init.ClockPrescaler);
/*-------------------------- USART GTPR Configuration ----------------------*/
MODIFY_REG(hirda->Instance->GTPR, (uint16_t)USART_GTPR_PSC, (uint16_t)hirda->Init.Prescaler);
/*-------------------------- USART BRR Configuration -----------------------*/
IRDA_GETCLOCKSOURCE(hirda, clocksource);
tmpreg = 0U;
switch (clocksource)
{
case IRDA_CLOCKSOURCE_PCLK1:
pclk = HAL_RCC_GetPCLK1Freq();
tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler));
break;
case IRDA_CLOCKSOURCE_PCLK2:
pclk = HAL_RCC_GetPCLK2Freq();
tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler));
break;
case IRDA_CLOCKSOURCE_HSI:
tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(HSI_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler));
break;
case IRDA_CLOCKSOURCE_SYSCLK:
pclk = HAL_RCC_GetSysClockFreq();
tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler));
break;
case IRDA_CLOCKSOURCE_LSE:
tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16((uint32_t)LSE_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler));
break;
default:
ret = HAL_ERROR;
break;
}
/* USARTDIV must be greater than or equal to 0d16 */
if ((tmpreg >= USART_BRR_MIN) && (tmpreg <= USART_BRR_MAX))
{
hirda->Instance->BRR = (uint16_t)tmpreg;
}
else
{
ret = HAL_ERROR;
}
return ret;
}
/**
* @brief Check the IRDA Idle State.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda)
{
uint32_t tickstart;
/* Initialize the IRDA ErrorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Init tickstart for timeout management */
tickstart = HAL_GetTick();
/* Check if the Transmitter is enabled */
if ((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE)
{
/* Wait until TEACK flag is set */
if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK)
{
/* Timeout occurred */
return HAL_TIMEOUT;
}
}
/* Check if the Receiver is enabled */
if ((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE)
{
/* Wait until REACK flag is set */
if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK)
{
/* Timeout occurred */
return HAL_TIMEOUT;
}
}
/* Initialize the IRDA state*/
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Handle IRDA Communication Timeout. It waits
* until a flag is no longer in the specified status.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param Flag Specifies the IRDA flag to check.
* @param Status The actual Flag status (SET or RESET)
* @param Tickstart Tick start value
* @param Timeout Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status,
uint32_t Tickstart, uint32_t Timeout)
{
/* Wait until flag is set */
while ((__HAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status)
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error)
interrupts for the interrupt process */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE));
/* At end of Tx process, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
}
/**
* @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
}
/**
* @brief DMA IRDA transmit process complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
/* DMA Normal mode */
if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC))
{
hirda->TxXferCount = 0U;
/* Disable the DMA transfer for transmit request by resetting the DMAT bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Enable the IRDA Transmit Complete Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
}
/* DMA Circular mode */
else
{
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Tx complete callback */
hirda->TxCpltCallback(hirda);
#else
/* Call legacy weak Tx complete callback */
HAL_IRDA_TxCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
}
/**
* @brief DMA IRDA transmit process half complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Tx Half complete callback */
hirda->TxHalfCpltCallback(hirda);
#else
/* Call legacy weak Tx complete callback */
HAL_IRDA_TxHalfCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA receive process complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
/* DMA Normal mode */
if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC))
{
hirda->RxXferCount = 0U;
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the DMA transfer for the receiver request by resetting the DMAR bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
}
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Rx complete callback */
hirda->RxCpltCallback(hirda);
#else
/* Call legacy weak Rx complete callback */
HAL_IRDA_RxCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
}
/**
* @brief DMA IRDA receive process half complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/*Call registered Rx Half complete callback*/
hirda->RxHalfCpltCallback(hirda);
#else
/* Call legacy weak Rx Half complete callback */
HAL_IRDA_RxHalfCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA communication error callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAError(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
/* Stop IRDA DMA Tx request if ongoing */
if (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
hirda->TxXferCount = 0U;
IRDA_EndTxTransfer(hirda);
}
}
/* Stop IRDA DMA Rx request if ongoing */
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
hirda->RxXferCount = 0U;
IRDA_EndRxTransfer(hirda);
}
}
hirda->ErrorCode |= HAL_IRDA_ERROR_DMA;
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered user error callback */
hirda->ErrorCallback(hirda);
#else
/* Call legacy weak user error callback */
HAL_IRDA_ErrorCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA communication abort callback, when initiated by HAL services on Error
* (To be called at end of DMA Abort procedure following error occurrence).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
hirda->RxXferCount = 0U;
hirda->TxXferCount = 0U;
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered user error callback */
hirda->ErrorCallback(hirda);
#else
/* Call legacy weak user error callback */
HAL_IRDA_ErrorCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA Tx communication abort callback, when initiated by user
* (To be called at end of DMA Tx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Rx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
hirda->hdmatx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if (hirda->hdmarx != NULL)
{
if (hirda->hdmarx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
hirda->TxXferCount = 0U;
hirda->RxXferCount = 0U;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort complete callback */
hirda->AbortCpltCallback(hirda);
#else
/* Call legacy weak Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA Rx communication abort callback, when initiated by user
* (To be called at end of DMA Rx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Tx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
hirda->hdmarx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if (hirda->hdmatx != NULL)
{
if (hirda->hdmatx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
hirda->TxXferCount = 0U;
hirda->RxXferCount = 0U;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort complete callback */
hirda->AbortCpltCallback(hirda);
#else
/* Call legacy weak Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to
* HAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer)
* (This callback is executed at end of DMA Tx Abort procedure following user abort request,
* and leads to user Tx Abort Complete callback execution).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent);
hirda->TxXferCount = 0U;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Transmit Complete Callback */
hirda->AbortTransmitCpltCallback(hirda);
#else
/* Call legacy weak Abort Transmit Complete Callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to
* HAL_IRDA_AbortReceive_IT API (Abort only Rx transfer)
* (This callback is executed at end of DMA Rx Abort procedure following user abort request,
* and leads to user Rx Abort Complete callback execution).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
hirda->RxXferCount = 0U;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Abort Receive Complete Callback */
hirda->AbortReceiveCpltCallback(hirda);
#else
/* Call legacy weak Abort Receive Complete Callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief Send an amount of data in interrupt mode.
* @note Function is called under interruption only, once
* interruptions have been enabled by HAL_IRDA_Transmit_IT().
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda)
{
const uint16_t *tmp;
/* Check that a Tx process is ongoing */
if (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
if (hirda->TxXferCount == 0U)
{
/* Disable the IRDA Transmit Data Register Empty Interrupt */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE);
/* Enable the IRDA Transmit Complete Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
}
else
{
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (const uint16_t *) hirda->pTxBuffPtr; /* Derogation R.11.3 */
hirda->Instance->TDR = (uint16_t)(*tmp & 0x01FFU);
hirda->pTxBuffPtr += 2U;
}
else
{
hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr & 0xFFU);
hirda->pTxBuffPtr++;
}
hirda->TxXferCount--;
}
}
}
/**
* @brief Wrap up transmission in non-blocking mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable the IRDA Transmit Complete Interrupt */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
/* Tx process is ended, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Tx complete callback */
hirda->TxCpltCallback(hirda);
#else
/* Call legacy weak Tx complete callback */
HAL_IRDA_TxCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */
}
/**
* @brief Receive an amount of data in interrupt mode.
* @note Function is called under interruption only, once
* interruptions have been enabled by HAL_IRDA_Receive_IT()
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda)
{
uint16_t *tmp;
uint16_t uhMask = hirda->Mask;
uint16_t uhdata;
/* Check that a Rx process is ongoing */
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
uhdata = (uint16_t) READ_REG(hirda->Instance->RDR);
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (uint16_t *) hirda->pRxBuffPtr; /* Derogation R.11.3 */
*tmp = (uint16_t)(uhdata & uhMask);
hirda->pRxBuffPtr += 2U;
}
else
{
*hirda->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask);
hirda->pRxBuffPtr++;
}
hirda->RxXferCount--;
if (hirda->RxXferCount == 0U)
{
/* Disable the IRDA Parity Error Interrupt and RXNE interrupt */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE));
/* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Rx process is completed, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1)
/* Call registered Rx complete callback */
hirda->RxCpltCallback(hirda);
#else
/* Call legacy weak Rx complete callback */
HAL_IRDA_RxCpltCallback(hirda);
#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */
}
}
else
{
/* Clear RXNE interrupt flag */
__HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST);
}
}
/**
* @}
*/
#endif /* HAL_IRDA_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 102,960 |
C
| 34.333219 | 157 | 0.630643 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_usart.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_usart.c
* @author MCD Application Team
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_usart.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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__) <= 18750000U)
/* __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);
}
#if defined(UART4)
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);
}
#endif /* UART4 */
#if defined(UART5)
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);
}
#endif /* UART5 */
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);
}
#if defined(UART4)
else if (USARTx == UART4)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART4_CLKSOURCE);
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART5_CLKSOURCE);
}
#endif /* UART5 */
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 */
| 18,047 |
C
| 41.566038 | 117 | 0.57051 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_comp.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_comp.c
* @author MCD Application Team
* @brief COMP LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_comp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
/** @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. */
/* 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) \
)
#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx)
#define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) || \
(((__COMP_INSTANCE__) == COMP1) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \
) || \
(((__COMP_INSTANCE__) == COMP2) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \
) || \
(((__COMP_INSTANCE__) == COMP3) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \
) || \
(((__COMP_INSTANCE__) == COMP4) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \
) || \
(((__COMP_INSTANCE__) == COMP5) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \
) || \
(((__COMP_INSTANCE__) == COMP6) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC2_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH2)) \
) || \
(((__COMP_INSTANCE__) == COMP7) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC2_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \
))
#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx)
#define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) || \
(((__COMP_INSTANCE__) == COMP1) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \
) || \
(((__COMP_INSTANCE__) == COMP2) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \
) || \
(((__COMP_INSTANCE__) == COMP3) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \
) || \
(((__COMP_INSTANCE__) == COMP4) && \
(((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \
((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \
))
#endif
#define IS_LL_COMP_INPUT_HYSTERESIS(__INPUT_HYSTERESIS__) \
( ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_NONE) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_10MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_20MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_30MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_40MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_50MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_60MV) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_70MV) \
)
#define IS_LL_COMP_OUTPUT_POLARITY(__POLARITY__) \
( ((__POLARITY__) == LL_COMP_OUTPUTPOL_NONINVERTED) \
|| ((__POLARITY__) == LL_COMP_OUTPUTPOL_INVERTED) \
)
#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx)
#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \
((((__INSTANCE__) == COMP1) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \
|| \
(((__INSTANCE__) == COMP2) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \
|| \
(((__INSTANCE__) == COMP3) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \
|| \
(((__INSTANCE__) == COMP4) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \
|| \
(((__INSTANCE__) == COMP5) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP5) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP5) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP5) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP5))) \
|| \
(((__INSTANCE__) == COMP6) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP6) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP6) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP6) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP6))) \
|| \
(((__INSTANCE__) == COMP7) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP7) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP7) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP7) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP7))) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \
)
#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx)
#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \
((((__INSTANCE__) == COMP1) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \
|| \
(((__INSTANCE__) == COMP2) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \
|| \
(((__INSTANCE__) == COMP3) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \
|| \
(((__INSTANCE__) == COMP4) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \
)
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \
((((__INSTANCE__) == COMP1) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \
|| \
(((__INSTANCE__) == COMP2) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \
|| \
(((__INSTANCE__) == COMP3) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \
|| \
(((__INSTANCE__) == COMP4) && \
(((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \
((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \
|| ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \
)
#endif
/**
* @}
*/
/* 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_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(COMPx, 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 : */
/* - InputPlus */
/* - InputMinus */
/* - InputHysteresis */
/* - OutputPolarity */
/* - OutputBlankingSource */
MODIFY_REG(COMPx->CSR,
COMP_CSR_INPSEL
| COMP_CSR_SCALEN
| COMP_CSR_BRGEN
| COMP_CSR_INMSEL
| COMP_CSR_HYST
| COMP_CSR_POLARITY
| COMP_CSR_BLANKING
,
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->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 /* USE_FULL_LL_DRIVER */
| 22,802 |
C
| 55.443069 | 146 | 0.443338 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_tim.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_tim.c
* @author MCD Application Team
* @brief TIM LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_tim.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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);
}
#if defined(TIM5)
else if (TIMx == TIM5)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5);
}
#endif /* 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);
}
#if defined(TIM20)
else if (TIMx == TIM20)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM20);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM20);
}
#endif /* TIM20 */
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 */
| 55,786 |
C
| 39.221341 | 220 | 0.621159 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_smartcard_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 */
/**
* @}
*/
/**
* @}
*/
| 16,044 |
C
| 31.34879 | 115 | 0.628522 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_i2c.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_i2c.c
* @author MCD Application Team
* @brief I2C LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_i2c.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C3);
/* Release reset of I2C clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C3);
}
#if defined(I2C4)
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);
}
#endif /* I2C4 */
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 */
| 8,016 |
C
| 31.991769 | 97 | 0.560005 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_lpuart.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_lpuart.c
* @author MCD Application Team
* @brief LPUART LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_lpuart.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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, 50000000].*/
#define IS_LL_LPUART_BAUDRATE(__BAUDRATE__) (((__BAUDRATE__) <= 50000000U) && ((__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_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_LPUART1);
/* Release reset of LPUART peripheral */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_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 */
| 11,666 |
C
| 40.226148 | 116 | 0.543117 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_exti.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_exti.c
* @author MCD Application Team
* @brief EXTI LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_exti.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (EXTI)
/** @defgroup EXTI_LL EXTI
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup EXTI_LL_Private_Macros
* @{
*/
#define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U)
#define IS_LL_EXTI_LINE_32_63(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_32_63) == 0x00000000U)
#define IS_LL_EXTI_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:
* - 0x00: EXTI registers are de-initialized
*/
uint32_t LL_EXTI_DeInit(void)
{
/* Interrupt mask register set to default reset values */
LL_EXTI_WriteReg(IMR1, 0x1F840000U);
/* 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 clear */
LL_EXTI_WriteReg(PR1, 0x007DFFFFU);
/* Interrupt mask register 2 set to default reset values */
#if defined(LL_EXTI_LINE_32) && defined(LL_EXTI_LINE_33) && defined(LL_EXTI_LINE_35) && defined(LL_EXTI_LINE_42)
LL_EXTI_WriteReg(IMR2, 0x0000043CU);
#else
LL_EXTI_WriteReg(IMR2, 0x00000034U);
#endif /* LL_EXTI_LINE_xx */
/* Event mask register 2 set to default reset values */
LL_EXTI_WriteReg(EMR2, 0x00000000U);
/* Rising Trigger selection register 2 set to default reset values */
LL_EXTI_WriteReg(RTSR2, 0x00000000U);
/* Falling Trigger selection register 2 set to default reset values */
LL_EXTI_WriteReg(FTSR2, 0x00000000U);
/* Software interrupt event register 2 set to default reset values */
LL_EXTI_WriteReg(SWIER2, 0x00000000U);
/* Pending register 2 clear */
LL_EXTI_WriteReg(PR2, 0x00000078U);
return 0x00u;
}
/**
* @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:
* - 0x00: EXTI registers are initialized
* - any other value : wrong configuration
*/
uint32_t LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
uint32_t status = 0x00u;
/* Check the parameters */
assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31));
assert_param(IS_LL_EXTI_LINE_32_63(EXTI_InitStruct->Line_32_63));
assert_param(IS_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 on provided Lines */
LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31);
/* Directly Enable Event on provided Lines */
LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status = 0x01u;
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:
/* Enable Rising Trigger on provided Lines */
LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
/* Enable Falling Trigger on provided Lines */
LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status |= 0x02u;
break;
}
}
}
/* Configure EXTI Lines in range from 32 to 63 */
if (EXTI_InitStruct->Line_32_63 != LL_EXTI_LINE_NONE)
{
switch (EXTI_InitStruct->Mode)
{
case LL_EXTI_MODE_IT:
/* First Disable Event on provided Lines */
LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63);
/* Then Enable IT on provided Lines */
LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63);
break;
case LL_EXTI_MODE_EVENT:
/* First Disable IT on provided Lines */
LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63);
/* Then Enable Event on provided Lines */
LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63);
break;
case LL_EXTI_MODE_IT_EVENT:
/* Directly Enable IT on provided Lines */
LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63);
/* Directly Enable IT on provided Lines */
LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63);
break;
default:
status |= 0x04u;
break;
}
if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE)
{
switch (EXTI_InitStruct->Trigger)
{
case LL_EXTI_TRIGGER_RISING:
/* First Disable Falling Trigger on provided Lines */
LL_EXTI_DisableFallingTrig_32_63(EXTI_InitStruct->Line_32_63);
/* Then Enable IT on provided Lines */
LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63);
break;
case LL_EXTI_TRIGGER_FALLING:
/* First Disable Rising Trigger on provided Lines */
LL_EXTI_DisableRisingTrig_32_63(EXTI_InitStruct->Line_32_63);
/* Then Enable Falling Trigger on provided Lines */
LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63);
break;
case LL_EXTI_TRIGGER_RISING_FALLING:
/* Enable Rising Trigger on provided Lines */
LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63);
/* Enable Falling Trigger on provided Lines */
LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63);
break;
default:
status |= 0x05u;
break;
}
}
}
}
/* DISABLE LineCommand */
else
{
/* De-configure IT EXTI Lines in range from 0 to 31 */
LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31);
/* De-configure Event EXTI Lines in range from 0 to 31 */
LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31);
/* De-configure IT EXTI Lines in range from 32 to 63 */
LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63);
/* De-configure Event EXTI Lines in range from 32 to 63 */
LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63);
}
return status;
}
/**
* @brief Set each @ref LL_EXTI_InitTypeDef field to default value.
* @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure.
* @retval None
*/
void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE;
EXTI_InitStruct->Line_32_63 = LL_EXTI_LINE_NONE;
EXTI_InitStruct->LineCommand = DISABLE;
EXTI_InitStruct->Mode = LL_EXTI_MODE_IT;
EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (EXTI) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 10,904 |
C
| 35.717172 | 112 | 0.561904 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_nor.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_nor.c
* @author MCD Application Team
* @brief NOR HAL module driver.
* This file provides a generic firmware to drive NOR memories mounted
* as external device.
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
This driver is a generic layered driver which contains a set of APIs used to
control NOR flash memories. It uses the FMC layer functions to interface
with NOR devices. This driver is used as follows:
(+) NOR flash memory configuration sequence using the function HAL_NOR_Init()
with control and timing parameters for both normal and extended mode.
(+) Read NOR flash memory manufacturer code and device IDs using the function
HAL_NOR_Read_ID(). The read information is stored in the NOR_ID_TypeDef
structure declared by the function caller.
(+) Access NOR flash memory by read/write data unit operations using the functions
HAL_NOR_Read(), HAL_NOR_Program().
(+) Perform NOR flash erase block/chip operations using the functions
HAL_NOR_Erase_Block() and HAL_NOR_Erase_Chip().
(+) Read the NOR flash CFI (common flash interface) IDs using the function
HAL_NOR_Read_CFI(). The read information is stored in the NOR_CFI_TypeDef
structure declared by the function caller.
(+) You can also control the NOR device by calling the control APIs HAL_NOR_WriteOperation_Enable()/
HAL_NOR_WriteOperation_Disable() to respectively enable/disable the NOR write operation
(+) You can monitor the NOR device HAL state by calling the function
HAL_NOR_GetState()
[..]
(@) This driver is a set of generic APIs which handle standard NOR flash operations.
If a NOR flash device contains different operations and/or implementations,
it should be implemented separately.
*** NOR HAL driver macros list ***
=============================================
[..]
Below the list of most used macros in NOR HAL driver.
(+) NOR_WRITE : NOR memory write data to specified address
*** Callback registration ***
=============================================
[..]
The compilation define USE_HAL_NOR_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_NOR_RegisterCallback() to register a user callback,
it allows to register following callbacks:
(+) MspInitCallback : NOR MspInit.
(+) MspDeInitCallback : NOR MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
Use function HAL_NOR_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function. It allows to reset following callbacks:
(+) MspInitCallback : NOR MspInit.
(+) MspDeInitCallback : NOR MspDeInit.
This function) takes as parameters the HAL peripheral handle and the Callback ID.
By default, after the HAL_NOR_Init and if the state is HAL_NOR_STATE_RESET
all callbacks are reset to the corresponding legacy weak (surcharged) functions.
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) functions in the HAL_NOR_Init
and HAL_NOR_DeInit only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_NOR_Init and HAL_NOR_DeInit
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
Callbacks can be registered/unregistered in READY state only.
Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered
in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used
during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_NOR_RegisterCallback before calling HAL_NOR_DeInit
or HAL_NOR_Init function.
When The compilation define USE_HAL_NOR_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registering feature is not available
and weak (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#if defined(FMC_BANK1)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_NOR_MODULE_ENABLED
/** @defgroup NOR NOR
* @brief NOR driver modules
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup NOR_Private_Defines NOR Private Defines
* @{
*/
/* Constants to define address to set to write a command */
#define NOR_CMD_ADDRESS_FIRST (uint16_t)0x0555
#define NOR_CMD_ADDRESS_FIRST_CFI (uint16_t)0x0055
#define NOR_CMD_ADDRESS_SECOND (uint16_t)0x02AA
#define NOR_CMD_ADDRESS_THIRD (uint16_t)0x0555
#define NOR_CMD_ADDRESS_FOURTH (uint16_t)0x0555
#define NOR_CMD_ADDRESS_FIFTH (uint16_t)0x02AA
#define NOR_CMD_ADDRESS_SIXTH (uint16_t)0x0555
/* Constants to define data to program a command */
#define NOR_CMD_DATA_READ_RESET (uint16_t)0x00F0
#define NOR_CMD_DATA_FIRST (uint16_t)0x00AA
#define NOR_CMD_DATA_SECOND (uint16_t)0x0055
#define NOR_CMD_DATA_AUTO_SELECT (uint16_t)0x0090
#define NOR_CMD_DATA_PROGRAM (uint16_t)0x00A0
#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD (uint16_t)0x0080
#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH (uint16_t)0x00AA
#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH (uint16_t)0x0055
#define NOR_CMD_DATA_CHIP_ERASE (uint16_t)0x0010
#define NOR_CMD_DATA_CFI (uint16_t)0x0098
#define NOR_CMD_DATA_BUFFER_AND_PROG (uint8_t)0x25
#define NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM (uint8_t)0x29
#define NOR_CMD_DATA_BLOCK_ERASE (uint8_t)0x30
#define NOR_CMD_READ_ARRAY (uint16_t)0x00FF
#define NOR_CMD_WORD_PROGRAM (uint16_t)0x0040
#define NOR_CMD_BUFFERED_PROGRAM (uint16_t)0x00E8
#define NOR_CMD_CONFIRM (uint16_t)0x00D0
#define NOR_CMD_BLOCK_ERASE (uint16_t)0x0020
#define NOR_CMD_BLOCK_UNLOCK (uint16_t)0x0060
#define NOR_CMD_READ_STATUS_REG (uint16_t)0x0070
#define NOR_CMD_CLEAR_STATUS_REG (uint16_t)0x0050
/* Mask on NOR STATUS REGISTER */
#define NOR_MASK_STATUS_DQ4 (uint16_t)0x0010
#define NOR_MASK_STATUS_DQ5 (uint16_t)0x0020
#define NOR_MASK_STATUS_DQ6 (uint16_t)0x0040
#define NOR_MASK_STATUS_DQ7 (uint16_t)0x0080
/* Address of the primary command set */
#define NOR_ADDRESS_COMMAND_SET (uint16_t)0x0013
/* Command set code assignment (defined in JEDEC JEP137B version may 2004) */
#define NOR_INTEL_SHARP_EXT_COMMAND_SET (uint16_t)0x0001 /* Supported in this driver */
#define NOR_AMD_FUJITSU_COMMAND_SET (uint16_t)0x0002 /* Supported in this driver */
#define NOR_INTEL_STANDARD_COMMAND_SET (uint16_t)0x0003 /* Not Supported in this driver */
#define NOR_AMD_FUJITSU_EXT_COMMAND_SET (uint16_t)0x0004 /* Not Supported in this driver */
#define NOR_WINDBOND_STANDARD_COMMAND_SET (uint16_t)0x0006 /* Not Supported in this driver */
#define NOR_MITSUBISHI_STANDARD_COMMAND_SET (uint16_t)0x0100 /* Not Supported in this driver */
#define NOR_MITSUBISHI_EXT_COMMAND_SET (uint16_t)0x0101 /* Not Supported in this driver */
#define NOR_PAGE_WRITE_COMMAND_SET (uint16_t)0x0102 /* Not Supported in this driver */
#define NOR_INTEL_PERFORMANCE_COMMAND_SET (uint16_t)0x0200 /* Not Supported in this driver */
#define NOR_INTEL_DATA_COMMAND_SET (uint16_t)0x0210 /* Not Supported in this driver */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup NOR_Private_Variables NOR Private Variables
* @{
*/
static uint32_t uwNORMemoryDataWidth = NOR_MEMORY_8B;
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup NOR_Exported_Functions NOR Exported Functions
* @{
*/
/** @defgroup NOR_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### NOR Initialization and de_initialization functions #####
==============================================================================
[..]
This section provides functions allowing to initialize/de-initialize
the NOR memory
@endverbatim
* @{
*/
/**
* @brief Perform the NOR memory Initialization sequence
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param Timing pointer to NOR control timing structure
* @param ExtTiming pointer to NOR extended mode timing structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing,
FMC_NORSRAM_TimingTypeDef *ExtTiming)
{
uint32_t deviceaddress;
/* Check the NOR handle parameter */
if (hnor == NULL)
{
return HAL_ERROR;
}
if (hnor->State == HAL_NOR_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hnor->Lock = HAL_UNLOCKED;
#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1)
if (hnor->MspInitCallback == NULL)
{
hnor->MspInitCallback = HAL_NOR_MspInit;
}
/* Init the low level hardware */
hnor->MspInitCallback(hnor);
#else
/* Initialize the low level hardware (MSP) */
HAL_NOR_MspInit(hnor);
#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */
}
/* Initialize NOR control Interface */
(void)FMC_NORSRAM_Init(hnor->Instance, &(hnor->Init));
/* Initialize NOR timing Interface */
(void)FMC_NORSRAM_Timing_Init(hnor->Instance, Timing, hnor->Init.NSBank);
/* Initialize NOR extended mode timing Interface */
(void)FMC_NORSRAM_Extended_Timing_Init(hnor->Extended, ExtTiming, hnor->Init.NSBank, hnor->Init.ExtendedMode);
/* Enable the NORSRAM device */
__FMC_NORSRAM_ENABLE(hnor->Instance, hnor->Init.NSBank);
/* Initialize NOR Memory Data Width*/
if (hnor->Init.MemoryDataWidth == FMC_NORSRAM_MEM_BUS_WIDTH_8)
{
uwNORMemoryDataWidth = NOR_MEMORY_8B;
}
else
{
uwNORMemoryDataWidth = NOR_MEMORY_16B;
}
/* Initialize the NOR controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Get the value of the command set */
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI);
hnor->CommandSet = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_ADDRESS_COMMAND_SET);
return HAL_NOR_ReturnToReadMode(hnor);
}
/**
* @brief Perform NOR memory De-Initialization sequence
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor)
{
#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1)
if (hnor->MspDeInitCallback == NULL)
{
hnor->MspDeInitCallback = HAL_NOR_MspDeInit;
}
/* DeInit the low level hardware */
hnor->MspDeInitCallback(hnor);
#else
/* De-Initialize the low level hardware (MSP) */
HAL_NOR_MspDeInit(hnor);
#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */
/* Configure the NOR registers with their reset values */
(void)FMC_NORSRAM_DeInit(hnor->Instance, hnor->Extended, hnor->Init.NSBank);
/* Reset the NOR controller state */
hnor->State = HAL_NOR_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hnor);
return HAL_OK;
}
/**
* @brief NOR MSP Init
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval None
*/
__weak void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnor);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NOR_MspInit could be implemented in the user file
*/
}
/**
* @brief NOR MSP DeInit
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval None
*/
__weak void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnor);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NOR_MspDeInit could be implemented in the user file
*/
}
/**
* @brief NOR MSP Wait for Ready/Busy signal
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param Timeout Maximum timeout value
* @retval None
*/
__weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnor);
UNUSED(Timeout);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NOR_MspWait could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup NOR_Exported_Functions_Group2 Input and Output functions
* @brief Input Output and memory control functions
*
@verbatim
==============================================================================
##### NOR Input and Output functions #####
==============================================================================
[..]
This section provides functions allowing to use and control the NOR memory
@endverbatim
* @{
*/
/**
* @brief Read NOR flash IDs
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param pNOR_ID pointer to NOR ID structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID)
{
uint32_t deviceaddress;
HAL_NOR_StateTypeDef state;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
state = hnor->State;
if (state == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_PROTECTED))
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send read ID command */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_AUTO_SELECT);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE(deviceaddress, NOR_CMD_DATA_AUTO_SELECT);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
if (status != HAL_ERROR)
{
/* Read the NOR IDs */
pNOR_ID->Manufacturer_Code = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, MC_ADDRESS);
pNOR_ID->Device_Code1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth,
DEVICE_CODE1_ADDR);
pNOR_ID->Device_Code2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth,
DEVICE_CODE2_ADDR);
pNOR_ID->Device_Code3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth,
DEVICE_CODE3_ADDR);
}
/* Check the NOR controller state */
hnor->State = state;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Returns the NOR memory to Read mode.
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor)
{
uint32_t deviceaddress;
HAL_NOR_StateTypeDef state;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
state = hnor->State;
if (state == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_PROTECTED))
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(deviceaddress, NOR_CMD_DATA_READ_RESET);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
/* Check the NOR controller state */
hnor->State = state;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Read data from NOR memory
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param pAddress pointer to Device address
* @param pData pointer to read data
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData)
{
uint32_t deviceaddress;
HAL_NOR_StateTypeDef state;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
state = hnor->State;
if (state == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_PROTECTED))
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send read data command */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_READ_RESET);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE(pAddress, NOR_CMD_READ_ARRAY);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
if (status != HAL_ERROR)
{
/* Read the data */
*pData = (uint16_t)(*(__IO uint32_t *)pAddress);
}
/* Check the NOR controller state */
hnor->State = state;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Program data to NOR memory
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param pAddress Device address
* @param pData pointer to the data to write
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData)
{
uint32_t deviceaddress;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnor->State == HAL_NOR_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send program data command */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_PROGRAM);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE(pAddress, NOR_CMD_WORD_PROGRAM);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
if (status != HAL_ERROR)
{
/* Write the data */
NOR_WRITE(pAddress, *pData);
}
/* Check the NOR controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Reads a half-word buffer from the NOR memory.
* @param hnor pointer to the NOR handle
* @param uwAddress NOR memory internal address to read from.
* @param pData pointer to the buffer that receives the data read from the
* NOR memory.
* @param uwBufferSize number of Half word to read.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData,
uint32_t uwBufferSize)
{
uint32_t deviceaddress;
uint32_t size = uwBufferSize;
uint32_t address = uwAddress;
uint16_t *data = pData;
HAL_NOR_StateTypeDef state;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
state = hnor->State;
if (state == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_PROTECTED))
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send read data command */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_READ_RESET);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
if (status != HAL_ERROR)
{
/* Read buffer */
while (size > 0U)
{
*data = *(__IO uint16_t *)address;
data++;
address += 2U;
size--;
}
}
/* Check the NOR controller state */
hnor->State = state;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Writes a half-word buffer to the NOR memory. This function must be used
only with S29GL128P NOR memory.
* @param hnor pointer to the NOR handle
* @param uwAddress NOR memory internal start write address
* @param pData pointer to source data buffer.
* @param uwBufferSize Size of the buffer to write
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData,
uint32_t uwBufferSize)
{
uint16_t *p_currentaddress;
const uint16_t *p_endaddress;
uint16_t *data = pData;
uint32_t deviceaddress;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnor->State == HAL_NOR_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Initialize variables */
p_currentaddress = (uint16_t *)(deviceaddress + uwAddress);
p_endaddress = (uint16_t *)(deviceaddress + uwAddress + (2U * (uwBufferSize - 1U)));
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
/* Issue unlock command sequence */
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
/* Write Buffer Load Command */
NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG);
NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U));
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
/* Write Buffer Load Command */
NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_BUFFERED_PROGRAM);
NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U));
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
if (status != HAL_ERROR)
{
/* Load Data into NOR Buffer */
while (p_currentaddress <= p_endaddress)
{
NOR_WRITE(p_currentaddress, *data);
data++;
p_currentaddress ++;
}
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM);
}
else /* => hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET */
{
NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_CONFIRM);
}
}
/* Check the NOR controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Erase the specified block of the NOR memory
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param BlockAddress Block to erase address
* @param Address Device address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address)
{
uint32_t deviceaddress;
HAL_StatusTypeDef status = HAL_OK;
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnor->State == HAL_NOR_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send block erase command sequence */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH);
NOR_WRITE((uint32_t)(BlockAddress + Address), NOR_CMD_DATA_BLOCK_ERASE);
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_UNLOCK);
NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM);
NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_ERASE);
NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
/* Check the NOR memory status and update the controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Erase the entire NOR chip.
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param Address Device address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address)
{
uint32_t deviceaddress;
HAL_StatusTypeDef status = HAL_OK;
UNUSED(Address);
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnor->State == HAL_NOR_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send NOR chip erase command sequence */
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH),
NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH);
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SIXTH), NOR_CMD_DATA_CHIP_ERASE);
}
else
{
/* Primary command set not supported by the driver */
status = HAL_ERROR;
}
/* Check the NOR memory status and update the controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @brief Read NOR flash CFI IDs
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param pNOR_CFI pointer to NOR CFI IDs structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI)
{
uint32_t deviceaddress;
HAL_NOR_StateTypeDef state;
/* Check the NOR controller state */
state = hnor->State;
if (state == HAL_NOR_STATE_BUSY)
{
return HAL_BUSY;
}
else if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_PROTECTED))
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Select the NOR device address */
if (hnor->Init.NSBank == FMC_NORSRAM_BANK1)
{
deviceaddress = NOR_MEMORY_ADRESS1;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2)
{
deviceaddress = NOR_MEMORY_ADRESS2;
}
else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3)
{
deviceaddress = NOR_MEMORY_ADRESS3;
}
else /* FMC_NORSRAM_BANK4 */
{
deviceaddress = NOR_MEMORY_ADRESS4;
}
/* Send read CFI query command */
NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI);
/* read the NOR CFI information */
pNOR_CFI->CFI_1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI1_ADDRESS);
pNOR_CFI->CFI_2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI2_ADDRESS);
pNOR_CFI->CFI_3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI3_ADDRESS);
pNOR_CFI->CFI_4 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI4_ADDRESS);
/* Check the NOR controller state */
hnor->State = state;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User NOR Callback
* To be used instead of the weak (surcharged) predefined callback
* @param hnor : NOR handle
* @param CallbackId : ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID
* @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID
* @param pCallback : pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId,
pNOR_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
HAL_NOR_StateTypeDef state;
if (pCallback == NULL)
{
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hnor);
state = hnor->State;
if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED))
{
switch (CallbackId)
{
case HAL_NOR_MSP_INIT_CB_ID :
hnor->MspInitCallback = pCallback;
break;
case HAL_NOR_MSP_DEINIT_CB_ID :
hnor->MspDeInitCallback = pCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hnor);
return status;
}
/**
* @brief Unregister a User NOR Callback
* NOR Callback is redirected to the weak (surcharged) predefined callback
* @param hnor : NOR handle
* @param CallbackId : ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID
* @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID
* @retval status
*/
HAL_StatusTypeDef HAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId)
{
HAL_StatusTypeDef status = HAL_OK;
HAL_NOR_StateTypeDef state;
/* Process locked */
__HAL_LOCK(hnor);
state = hnor->State;
if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED))
{
switch (CallbackId)
{
case HAL_NOR_MSP_INIT_CB_ID :
hnor->MspInitCallback = HAL_NOR_MspInit;
break;
case HAL_NOR_MSP_DEINIT_CB_ID :
hnor->MspDeInitCallback = HAL_NOR_MspDeInit;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hnor);
return status;
}
#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */
/**
* @}
*/
/** @defgroup NOR_Exported_Functions_Group3 NOR Control functions
* @brief management functions
*
@verbatim
==============================================================================
##### NOR Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control dynamically
the NOR interface.
@endverbatim
* @{
*/
/**
* @brief Enables dynamically NOR write operation.
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor)
{
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_PROTECTED)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Enable write operation */
(void)FMC_NORSRAM_WriteOperation_Enable(hnor->Instance, hnor->Init.NSBank);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Disables dynamically NOR write operation.
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor)
{
/* Check the NOR controller state */
if (hnor->State == HAL_NOR_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnor);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_BUSY;
/* Disable write operation */
(void)FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank);
/* Update the NOR controller state */
hnor->State = HAL_NOR_STATE_PROTECTED;
/* Process unlocked */
__HAL_UNLOCK(hnor);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @}
*/
/** @defgroup NOR_Exported_Functions_Group4 NOR State functions
* @brief Peripheral State functions
*
@verbatim
==============================================================================
##### NOR State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the NOR controller
and the data flow.
@endverbatim
* @{
*/
/**
* @brief return the NOR controller state
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @retval NOR controller state
*/
HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor)
{
return hnor->State;
}
/**
* @brief Returns the NOR operation status.
* @param hnor pointer to a NOR_HandleTypeDef structure that contains
* the configuration information for NOR module.
* @param Address Device address
* @param Timeout NOR programming Timeout
* @retval NOR_Status The returned value can be: HAL_NOR_STATUS_SUCCESS, HAL_NOR_STATUS_ERROR
* or HAL_NOR_STATUS_TIMEOUT
*/
HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout)
{
HAL_NOR_StatusTypeDef status = HAL_NOR_STATUS_ONGOING;
uint16_t tmpsr1;
uint16_t tmpsr2;
uint32_t tickstart;
/* Poll on NOR memory Ready/Busy signal ------------------------------------*/
HAL_NOR_MspWait(hnor, Timeout);
/* Get the NOR memory operation status -------------------------------------*/
/* Get tick */
tickstart = HAL_GetTick();
if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET)
{
while ((status != HAL_NOR_STATUS_SUCCESS) && (status != HAL_NOR_STATUS_TIMEOUT))
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
status = HAL_NOR_STATUS_TIMEOUT;
}
}
/* Read NOR status register (DQ6 and DQ5) */
tmpsr1 = *(__IO uint16_t *)Address;
tmpsr2 = *(__IO uint16_t *)Address;
/* If DQ6 did not toggle between the two reads then return HAL_NOR_STATUS_SUCCESS */
if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6))
{
return HAL_NOR_STATUS_SUCCESS ;
}
if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5)
{
status = HAL_NOR_STATUS_ONGOING;
}
tmpsr1 = *(__IO uint16_t *)Address;
tmpsr2 = *(__IO uint16_t *)Address;
/* If DQ6 did not toggle between the two reads then return HAL_NOR_STATUS_SUCCESS */
if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6))
{
return HAL_NOR_STATUS_SUCCESS;
}
if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5)
{
return HAL_NOR_STATUS_ERROR;
}
}
}
else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET)
{
do
{
NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG);
tmpsr2 = *(__IO uint16_t *)(Address);
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
return HAL_NOR_STATUS_TIMEOUT;
}
}
} while ((tmpsr2 & NOR_MASK_STATUS_DQ7) == 0U);
NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG);
tmpsr1 = *(__IO uint16_t *)(Address);
if ((tmpsr1 & (NOR_MASK_STATUS_DQ5 | NOR_MASK_STATUS_DQ4)) != 0U)
{
/* Clear the Status Register */
NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG);
status = HAL_NOR_STATUS_ERROR;
}
else
{
status = HAL_NOR_STATUS_SUCCESS;
}
}
else
{
/* Primary command set not supported by the driver */
status = HAL_NOR_STATUS_ERROR;
}
/* Return the operation status */
return status;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_NOR_MODULE_ENABLED */
/**
* @}
*/
#endif /* FMC_BANK1 */
| 46,519 |
C
| 29.787558 | 118 | 0.613943 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_cryp.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_cryp.c
* @author MCD Application Team
* @brief CRYP HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Cryptography (CRYP) peripheral:
* + Initialization, de-initialization, set config and get config functions
* + AES processing functions
* + DMA callback functions
* + CRYP IRQ handler management
* + Peripheral State functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 CRYP HAL driver can be used in CRYP or TinyAES peripheral as follows:
(#)Initialize the CRYP low level resources by implementing the HAL_CRYP_MspInit():
(##) Enable the CRYP interface clock using __HAL_RCC_CRYP_CLK_ENABLE()or __HAL_RCC_AES_CLK_ENABLE for TinyAES peripheral
(##) In case of using interrupts (e.g. HAL_CRYP_Encrypt_IT())
(+++) Configure the CRYP interrupt priority using HAL_NVIC_SetPriority()
(+++) Enable the CRYP IRQ handler using HAL_NVIC_EnableIRQ()
(+++) In CRYP IRQ handler, call HAL_CRYP_IRQHandler()
(##) In case of using DMA to control data transfer (e.g. HAL_CRYP_Encrypt_DMA())
(+++) Enable the DMAx interface clock using __RCC_DMAx_CLK_ENABLE()
(+++) Configure and enable two DMA streams one for managing data transfer from
memory to peripheral (input stream) and another stream for managing data
transfer from peripheral to memory (output stream)
(+++) Associate the initialized DMA handle to the CRYP DMA handle
using __HAL_LINKDMA()
(+++) Configure the priority and enable the NVIC for the transfer complete
interrupt on the two DMA channels. The output channel should have higher
priority than the input channel HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ().
(#)Initialize the CRYP according to the specified parameters :
(##) The data type: 1-bit, 8-bit, 16-bit or 32-bit.
(##) The key size: 128, 192 or 256.
(##) The AlgoMode DES/ TDES Algorithm ECB/CBC or AES Algorithm ECB/CBC/CTR/GCM or CCM.
(##) The initialization vector (counter). It is not used in ECB mode.
(##) The key buffer used for encryption/decryption.
(+++) In some specific configurations, the key is written by the application
code out of the HAL scope. In that case, user can still resort to the
HAL APIs as usual but must make sure that pKey pointer is set to NULL.
(##) The DataWidthUnit field. It specifies whether the data length (or the payload length for authentication
algorithms) is in words or bytes.
(##) The Header used only in AES GCM and CCM Algorithm for authentication.
(##) The HeaderSize providing the size of the header buffer in words or bytes, depending upon HeaderWidthUnit field.
(##) The HeaderWidthUnit field. It specifies whether the header length (for authentication algorithms) is in words or bytes.
(##) The B0 block is the first authentication block used only in AES CCM mode.
(##) The KeyIVConfigSkip used to process several messages in a row (please see more information below).
(#)Three processing (encryption/decryption) functions are available:
(##) Polling mode: encryption and decryption APIs are blocking functions
i.e. they process the data and wait till the processing is finished,
e.g. HAL_CRYP_Encrypt & HAL_CRYP_Decrypt
(##) Interrupt mode: encryption and decryption APIs are not blocking functions
i.e. they process the data under interrupt,
e.g. HAL_CRYP_Encrypt_IT & HAL_CRYP_Decrypt_IT
(##) DMA mode: encryption and decryption APIs are not blocking functions
i.e. the data transfer is ensured by DMA,
e.g. HAL_CRYP_Encrypt_DMA & HAL_CRYP_Decrypt_DMA
(#)When the processing function is called at first time after HAL_CRYP_Init()
the CRYP peripheral is configured and processes the buffer in input.
At second call, no need to Initialize the CRYP, user have to get current configuration via
HAL_CRYP_GetConfig() API, then only HAL_CRYP_SetConfig() is requested to set
new parametres, finally user can start encryption/decryption.
(#)Call HAL_CRYP_DeInit() to deinitialize the CRYP peripheral.
(#)To process a single message with consecutive calls to HAL_CRYP_Encrypt() or HAL_CRYP_Decrypt()
without having to configure again the Key or the Initialization Vector between each API call,
the field KeyIVConfigSkip of the initialization structure must be set to CRYP_KEYIVCONFIG_ONCE.
Same is true for consecutive calls of HAL_CRYP_Encrypt_IT(), HAL_CRYP_Decrypt_IT(), HAL_CRYP_Encrypt_DMA()
or HAL_CRYP_Decrypt_DMA().
[..]
The cryptographic processor supports following standards:
(#) The data encryption standard (DES) and Triple-DES (TDES) supported only by CRYP1 peripheral:
(##)64-bit data block processing
(##) chaining modes supported :
(+++) Electronic Code Book(ECB)
(+++) Cipher Block Chaining (CBC)
(##) keys length supported :64-bit, 128-bit and 192-bit.
(#) The advanced encryption standard (AES) supported by CRYP1 & TinyAES peripheral:
(##)128-bit data block processing
(##) chaining modes supported :
(+++) Electronic Code Book(ECB)
(+++) Cipher Block Chaining (CBC)
(+++) Counter mode (CTR)
(+++) Galois/counter mode (GCM/GMAC)
(+++) Counter with Cipher Block Chaining-Message(CCM)
(##) keys length Supported :
(+++) for CRYP1 peripheral: 128-bit, 192-bit and 256-bit.
(+++) for TinyAES peripheral: 128-bit and 256-bit
[..]
(@) Specific care must be taken to format the key and the Initialization Vector IV!
[..] If the key is defined as a 128-bit long array key[127..0] = {b127 ... b0} where
b127 is the MSB and b0 the LSB, the key must be stored in MCU memory
(+) as a sequence of words where the MSB word comes first (occupies the
lowest memory address)
(++) address n+0 : 0b b127 .. b120 b119 .. b112 b111 .. b104 b103 .. b96
(++) address n+4 : 0b b95 .. b88 b87 .. b80 b79 .. b72 b71 .. b64
(++) address n+8 : 0b b63 .. b56 b55 .. b48 b47 .. b40 b39 .. b32
(++) address n+C : 0b b31 .. b24 b23 .. b16 b15 .. b8 b7 .. b0
[..] Hereafter, another illustration when considering a 128-bit long key made of 16 bytes {B15..B0}.
The 4 32-bit words that make the key must be stored as follows in MCU memory:
(+) address n+0 : 0x B15 B14 B13 B12
(+) address n+4 : 0x B11 B10 B9 B8
(+) address n+8 : 0x B7 B6 B5 B4
(+) address n+C : 0x B3 B2 B1 B0
[..] which leads to the expected setting
(+) AES_KEYR3 = 0x B15 B14 B13 B12
(+) AES_KEYR2 = 0x B11 B10 B9 B8
(+) AES_KEYR1 = 0x B7 B6 B5 B4
(+) AES_KEYR0 = 0x B3 B2 B1 B0
[..] Same format must be applied for a 256-bit long key made of 32 bytes {B31..B0}.
The 8 32-bit words that make the key must be stored as follows in MCU memory:
(+) address n+00 : 0x B31 B30 B29 B28
(+) address n+04 : 0x B27 B26 B25 B24
(+) address n+08 : 0x B23 B22 B21 B20
(+) address n+0C : 0x B19 B18 B17 B16
(+) address n+10 : 0x B15 B14 B13 B12
(+) address n+14 : 0x B11 B10 B9 B8
(+) address n+18 : 0x B7 B6 B5 B4
(+) address n+1C : 0x B3 B2 B1 B0
[..] which leads to the expected setting
(+) AES_KEYR7 = 0x B31 B30 B29 B28
(+) AES_KEYR6 = 0x B27 B26 B25 B24
(+) AES_KEYR5 = 0x B23 B22 B21 B20
(+) AES_KEYR4 = 0x B19 B18 B17 B16
(+) AES_KEYR3 = 0x B15 B14 B13 B12
(+) AES_KEYR2 = 0x B11 B10 B9 B8
(+) AES_KEYR1 = 0x B7 B6 B5 B4
(+) AES_KEYR0 = 0x B3 B2 B1 B0
[..] Initialization Vector IV (4 32-bit words) format must follow the same as
that of a 128-bit long key.
[..] Note that key and IV registers are not sensitive to swap mode selection.
[..] This section describes the AES Galois/counter mode (GCM) supported by both CRYP1 and TinyAES peripherals:
(#) Algorithm supported :
(##) Galois/counter mode (GCM)
(##) Galois message authentication code (GMAC) :is exactly the same as
GCM algorithm composed only by an header.
(#) Four phases are performed in GCM :
(##) Init phase: peripheral prepares the GCM hash subkey (H) and do the IV processing
(##) Header phase: peripheral processes the Additional Authenticated Data (AAD), with hash
computation only.
(##) Payload phase: peripheral processes the plaintext (P) with hash computation + keystream
encryption + data XORing. It works in a similar way for ciphertext (C).
(##) Final phase: peripheral generates the authenticated tag (T) using the last block of data.
(#) structure of message construction in GCM is defined as below :
(##) 16 bytes Initial Counter Block (ICB)composed of IV and counter
(##) The authenticated header A (also knows as Additional Authentication Data AAD)
this part of the message is only authenticated, not encrypted.
(##) The plaintext message P is both authenticated and encrypted as ciphertext.
GCM standard specifies that ciphertext has same bit length as the plaintext.
(##) The last block is composed of the length of A (on 64 bits) and the length of ciphertext
(on 64 bits)
[..] A more detailed description of the GCM message structure is available below.
[..] This section describe The AES Counter with Cipher Block Chaining-Message
Authentication Code (CCM) supported by both CRYP1 and TinyAES peripheral:
(#) Specific parameters for CCM :
(##) B0 block : follows NIST Special Publication 800-38C,
(##) B1 block (header)
(##) CTRx block : control blocks
[..] A detailed description of the CCM message structure is available below.
(#) Four phases are performed in CCM for CRYP1 peripheral:
(##) Init phase: peripheral prepares the GCM hash subkey (H) and do the IV processing
(##) Header phase: peripheral processes the Additional Authenticated Data (AAD), with hash
computation only.
(##) Payload phase: peripheral processes the plaintext (P) with hash computation + keystream
encryption + data XORing. It works in a similar way for ciphertext (C).
(##) Final phase: peripheral generates the authenticated tag (T) using the last block of data.
(#) CCM in TinyAES peripheral:
(##) To perform message payload encryption or decryption AES is configured in CTR mode.
(##) For authentication two phases are performed :
- Header phase: peripheral processes the Additional Authenticated Data (AAD) first, then the cleartext message
only cleartext payload (not the ciphertext payload) is used and no outpout.
(##) Final phase: peripheral generates the authenticated tag (T) using the last block of data.
*** Callback registration ***
=============================
[..]
The compilation define USE_HAL_CRYP_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_CRYP_RegisterCallback() or HAL_CRYP_RegisterXXXCallback()
to register an interrupt callback.
[..]
Function HAL_CRYP_RegisterCallback() allows to register following callbacks:
(+) InCpltCallback : Input FIFO transfer completed callback.
(+) OutCpltCallback : Output FIFO transfer completed callback.
(+) ErrorCallback : callback for error detection.
(+) MspInitCallback : CRYP MspInit.
(+) MspDeInitCallback : CRYP MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_CRYP_UnRegisterCallback() to reset a callback to the default
weak function.
HAL_CRYP_UnRegisterCallback() takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) InCpltCallback : Input FIFO transfer completed callback.
(+) OutCpltCallback : Output FIFO transfer completed callback.
(+) ErrorCallback : callback for error detection.
(+) MspInitCallback : CRYP MspInit.
(+) MspDeInitCallback : CRYP MspDeInit.
[..]
By default, after the HAL_CRYP_Init() and when the state is HAL_CRYP_STATE_RESET
all callbacks are set to the corresponding weak functions :
examples HAL_CRYP_InCpltCallback() , HAL_CRYP_OutCpltCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak function in the HAL_CRYP_Init()/ HAL_CRYP_DeInit() only when
these callbacks are null (not registered beforehand).
if not, MspInit or MspDeInit are not null, the HAL_CRYP_Init() / HAL_CRYP_DeInit()
keep and use the user MspInit/MspDeInit functions (registered beforehand)
[..]
Callbacks can be registered/unregistered in HAL_CRYP_STATE_READY state only.
Exception done MspInit/MspDeInit callbacks that can be registered/unregistered
in HAL_CRYP_STATE_READY or HAL_CRYP_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_CRYP_RegisterCallback() before calling HAL_CRYP_DeInit()
or HAL_CRYP_Init() function.
[..]
When The compilation define USE_HAL_CRYP_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.
*** Suspend/Resume feature ***
==============================
[..]
The compilation define USE_HAL_CRYP_SUSPEND_RESUME when set to 1
allows the user to resort to the suspend/resume feature.
A low priority block processing can be suspended to process a high priority block
instead. When the high priority block processing is over, the low priority block
processing can be resumed, restarting from the point where it was suspended. This
feature is applicable only in non-blocking interrupt mode.
[..] User must resort to HAL_CRYP_Suspend() to suspend the low priority block
processing. This API manages the hardware block processing suspension and saves all the
internal data that will be needed to restart later on. Upon HAL_CRYP_Suspend() completion,
the user can launch the processing of any other block (high priority block processing).
[..] When the high priority block processing is over, user must invoke HAL_CRYP_Resume()
to resume the low priority block processing. Ciphering (or deciphering) restarts from
the suspension point and ends as usual.
[..] HAL_CRYP_Suspend() reports an error when the suspension request is sent too late
(i.e when the low priority block processing is about to end). There is no use to
suspend the tag generation processing for authentication algorithms.
[..]
(@) If the key is written out of HAL scope (case pKey pointer set to NULL by the user),
the block processing suspension/resumption mechanism is NOT applicable.
[..]
(@) If the Key and Initialization Vector are configured only once and configuration is
skipped for consecutive processings (case KeyIVConfigSkip set to CRYP_KEYIVCONFIG_ONCE),
the block processing suspension/resumption mechanism is NOT applicable.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @addtogroup CRYP
* @{
*/
#if defined(AES)
#ifdef HAL_CRYP_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup CRYP_Private_Defines
* @{
*/
#define CRYP_TIMEOUT_KEYPREPARATION 82U /* The latency of key preparation operation is 82 clock cycles.*/
#define CRYP_TIMEOUT_GCMCCMINITPHASE 299U /* The latency of GCM/CCM init phase to prepare hash subkey is 299 clock cycles.*/
#define CRYP_TIMEOUT_GCMCCMHEADERPHASE 290U /* The latency of GCM/CCM header phase is 290 clock cycles.*/
#define CRYP_PHASE_READY 0x00000001U /*!< CRYP peripheral is ready for initialization. */
#define CRYP_PHASE_PROCESS 0x00000002U /*!< CRYP peripheral is in processing phase */
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
#define CRYP_PHASE_HEADER_SUSPENDED 0x00000004U /*!< GCM/GMAC/CCM header phase is suspended */
#define CRYP_PHASE_PAYLOAD_SUSPENDED 0x00000005U /*!< GCM/CCM payload phase is suspended */
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
#define CRYP_PHASE_HEADER_DMA_FEED 0x00000006U /*!< GCM/GMAC/CCM header is fed to the peripheral in DMA mode */
#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U /*!< Encryption mode(Mode 1) */
#define CRYP_OPERATINGMODE_KEYDERIVATION AES_CR_MODE_0 /*!< Key derivation mode only used when performing ECB and CBC decryptions (Mode 2) */
#define CRYP_OPERATINGMODE_DECRYPT AES_CR_MODE_1 /*!< Decryption (Mode 3) */
#define CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT AES_CR_MODE /*!< Key derivation and decryption only used when performing ECB and CBC decryptions (Mode 4) */
#define CRYP_PHASE_INIT 0x00000000U /*!< GCM/GMAC (or CCM) init phase */
#define CRYP_PHASE_HEADER AES_CR_GCMPH_0 /*!< GCM/GMAC or CCM header phase */
#define CRYP_PHASE_PAYLOAD AES_CR_GCMPH_1 /*!< GCM(/CCM) payload phase */
#define CRYP_PHASE_FINAL AES_CR_GCMPH /*!< GCM/GMAC or CCM final phase */
/* CTR1 information to use in CCM algorithm */
#define CRYP_CCM_CTR1_0 0x07FFFFFFU
#define CRYP_CCM_CTR1_1 0xFFFFFF00U
#define CRYP_CCM_CTR1_2 0x00000001U
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/** @addtogroup CRYP_Private_Macros
* @{
*/
#define CRYP_SET_PHASE(__HANDLE__, __PHASE__) MODIFY_REG((__HANDLE__)->Instance->CR, AES_CR_GCMPH, (uint32_t)(__PHASE__))
/**
* @}
*/
/* Private struct -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup CRYP_Private_Functions
* @{
*/
static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr);
static HAL_StatusTypeDef CRYP_SetHeaderDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size);
static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma);
static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma);
static void CRYP_DMAError(DMA_HandleTypeDef *hdma);
static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint32_t KeySize);
static void CRYP_AES_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static void CRYP_GCMCCM_SetPayloadPhase_IT(CRYP_HandleTypeDef *hcryp);
static void CRYP_GCMCCM_SetHeaderPhase_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase_DMA(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_GCMCCM_SetPayloadPhase_DMA(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AESGCM_Process_DMA(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AESGCM_Process_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AESGCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_AESCCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_AESCCM_Process_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AESCCM_Process_DMA(CRYP_HandleTypeDef *hcryp);
static void CRYP_AES_ProcessData(CRYP_HandleTypeDef *hcrypt, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_AES_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_AES_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static HAL_StatusTypeDef CRYP_AES_Decrypt_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AES_Encrypt_IT(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_AES_Decrypt_DMA(CRYP_HandleTypeDef *hcryp);
static HAL_StatusTypeDef CRYP_WaitOnCCFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
static void CRYP_ClearCCFlagWhenHigh(CRYP_HandleTypeDef *hcryp, uint32_t Timeout);
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
static void CRYP_Read_IVRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output);
static void CRYP_Write_IVRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input);
static void CRYP_Read_SuspendRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output);
static void CRYP_Write_SuspendRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input);
static void CRYP_Read_KeyRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output, uint32_t KeySize);
static void CRYP_Write_KeyRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input, uint32_t KeySize);
static void CRYP_PhaseProcessingResume(CRYP_HandleTypeDef *hcryp);
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @addtogroup CRYP_Exported_Functions
* @{
*/
/** @defgroup CRYP_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions.
*
@verbatim
========================================================================================
##### Initialization, de-initialization and Set and Get configuration functions #####
========================================================================================
[..] This section provides functions allowing to:
(+) Initialize the CRYP
(+) DeInitialize the CRYP
(+) Initialize the CRYP MSP
(+) DeInitialize the CRYP MSP
(+) configure CRYP (HAL_CRYP_SetConfig) with the specified parameters in the CRYP_ConfigTypeDef
Parameters which are configured in This section are :
(++) Key size
(++) Data Type : 32,16, 8 or 1bit
(++) AlgoMode :
(+++) for CRYP1 peripheral :
ECB and CBC in DES/TDES Standard
ECB,CBC,CTR,GCM/GMAC and CCM in AES Standard.
(+++) for TinyAES2 peripheral, only ECB,CBC,CTR,GCM/GMAC and CCM in AES Standard are supported.
(+) Get CRYP configuration (HAL_CRYP_GetConfig) from the specified parameters in the CRYP_HandleTypeDef
@endverbatim
* @{
*/
/**
* @brief Initializes the CRYP according to the specified
* parameters in the CRYP_ConfigTypeDef and creates the associated handle.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp)
{
/* Check the CRYP handle allocation */
if (hcryp == NULL)
{
return HAL_ERROR;
}
/* Check parameters */
assert_param(IS_CRYP_KEYSIZE(hcryp->Init.KeySize));
assert_param(IS_CRYP_DATATYPE(hcryp->Init.DataType));
assert_param(IS_CRYP_ALGORITHM(hcryp->Init.Algorithm));
assert_param(IS_CRYP_INIT(hcryp->Init.KeyIVConfigSkip));
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
if (hcryp->State == HAL_CRYP_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcryp->Lock = HAL_UNLOCKED;
hcryp->InCpltCallback = HAL_CRYP_InCpltCallback; /* Legacy weak InCpltCallback */
hcryp->OutCpltCallback = HAL_CRYP_OutCpltCallback; /* Legacy weak OutCpltCallback */
hcryp->ErrorCallback = HAL_CRYP_ErrorCallback; /* Legacy weak ErrorCallback */
if (hcryp->MspInitCallback == NULL)
{
hcryp->MspInitCallback = HAL_CRYP_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware */
hcryp->MspInitCallback(hcryp);
}
#else
if (hcryp->State == HAL_CRYP_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcryp->Lock = HAL_UNLOCKED;
/* Init the low level hardware */
HAL_CRYP_MspInit(hcryp);
}
#endif /* (USE_HAL_CRYP_REGISTER_CALLBACKS) */
/* Set the key size (This bit field is do not care in the DES or TDES modes), data type and Algorithm */
MODIFY_REG(hcryp->Instance->CR, AES_CR_DATATYPE | AES_CR_KEYSIZE | AES_CR_CHMOD, hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm);
/* Reset Error Code field */
hcryp->ErrorCode = HAL_CRYP_ERROR_NONE;
/* Reset peripheral Key and IV configuration flag */
hcryp->KeyIVConfig = 0U;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Set the default CRYP phase */
hcryp->Phase = CRYP_PHASE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief De-Initializes the CRYP peripheral.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp)
{
/* Check the CRYP handle allocation */
if (hcryp == NULL)
{
return HAL_ERROR;
}
/* Set the default CRYP phase */
hcryp->Phase = CRYP_PHASE_READY;
/* Reset CrypInCount and CrypOutCount */
hcryp->CrypInCount = 0;
hcryp->CrypOutCount = 0;
hcryp->CrypHeaderCount = 0;
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
if (hcryp->MspDeInitCallback == NULL)
{
hcryp->MspDeInitCallback = HAL_CRYP_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware */
hcryp->MspDeInitCallback(hcryp);
#else
/* DeInit the low level hardware: CLOCK, NVIC.*/
HAL_CRYP_MspDeInit(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hcryp);
/* Return function status */
return HAL_OK;
}
/**
* @brief Configure the CRYP according to the specified
* parameters in the CRYP_ConfigTypeDef
* @param hcryp pointer to a CRYP_HandleTypeDef structure
* @param pConf pointer to a CRYP_ConfigTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_SetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf)
{
/* Check the CRYP handle allocation */
if ((hcryp == NULL) || (pConf == NULL))
{
return HAL_ERROR;
}
/* Check parameters */
assert_param(IS_CRYP_KEYSIZE(pConf->KeySize));
assert_param(IS_CRYP_DATATYPE(pConf->DataType));
assert_param(IS_CRYP_ALGORITHM(pConf->Algorithm));
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Set CRYP parameters */
hcryp->Init.DataType = pConf->DataType;
hcryp->Init.pKey = pConf->pKey;
hcryp->Init.Algorithm = pConf->Algorithm;
hcryp->Init.KeySize = pConf->KeySize;
hcryp->Init.pInitVect = pConf->pInitVect;
hcryp->Init.Header = pConf->Header;
hcryp->Init.HeaderSize = pConf->HeaderSize;
hcryp->Init.B0 = pConf->B0;
hcryp->Init.DataWidthUnit = pConf->DataWidthUnit;
hcryp->Init.HeaderWidthUnit = pConf->HeaderWidthUnit;
hcryp->Init.KeyIVConfigSkip = pConf->KeyIVConfigSkip;
/* Set the key size (This bit field is do not care in the DES or TDES modes), data type and operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_DATATYPE | AES_CR_KEYSIZE | AES_CR_CHMOD, hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm);
/*clear error flags*/
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_ERR_CLEAR);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Reset Error Code field */
hcryp->ErrorCode = HAL_CRYP_ERROR_NONE;
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Set the default CRYP phase */
hcryp->Phase = CRYP_PHASE_READY;
/* Return function status */
return HAL_OK;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
return HAL_ERROR;
}
}
/**
* @brief Get CRYP Configuration parameters in associated handle.
* @param pConf pointer to a CRYP_ConfigTypeDef structure
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_GetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf)
{
/* Check the CRYP handle allocation */
if ((hcryp == NULL) || (pConf == NULL))
{
return HAL_ERROR;
}
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Get CRYP parameters */
pConf->DataType = hcryp->Init.DataType;
pConf->pKey = hcryp->Init.pKey;
pConf->Algorithm = hcryp->Init.Algorithm;
pConf->KeySize = hcryp->Init.KeySize ;
pConf->pInitVect = hcryp->Init.pInitVect;
pConf->Header = hcryp->Init.Header ;
pConf->HeaderSize = hcryp->Init.HeaderSize;
pConf->B0 = hcryp->Init.B0;
pConf->DataWidthUnit = hcryp->Init.DataWidthUnit;
pConf->HeaderWidthUnit = hcryp->Init.HeaderWidthUnit;
pConf->KeyIVConfigSkip = hcryp->Init.KeyIVConfigSkip;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Return function status */
return HAL_OK;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
return HAL_ERROR;
}
}
/**
* @brief Initializes the CRYP MSP.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcryp);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CRYP_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitializes CRYP MSP.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
__weak void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcryp);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CRYP_MspDeInit can be implemented in the user file
*/
}
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/**
* @brief Register a User CRYP Callback
* To be used instead of the weak predefined callback
* @param hcryp cryp handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_CRYP_INPUT_COMPLETE_CB_ID Input FIFO transfer completed callback ID
* @arg @ref HAL_CRYP_OUTPUT_COMPLETE_CB_ID Output FIFO transfer completed callback ID
* @arg @ref HAL_CRYP_ERROR_CB_ID Error callback ID
* @arg @ref HAL_CRYP_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_CRYP_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_CRYP_RegisterCallback(CRYP_HandleTypeDef *hcryp, HAL_CRYP_CallbackIDTypeDef CallbackID, pCRYP_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hcryp);
if (hcryp->State == HAL_CRYP_STATE_READY)
{
switch (CallbackID)
{
case HAL_CRYP_INPUT_COMPLETE_CB_ID :
hcryp->InCpltCallback = pCallback;
break;
case HAL_CRYP_OUTPUT_COMPLETE_CB_ID :
hcryp->OutCpltCallback = pCallback;
break;
case HAL_CRYP_ERROR_CB_ID :
hcryp->ErrorCallback = pCallback;
break;
case HAL_CRYP_MSPINIT_CB_ID :
hcryp->MspInitCallback = pCallback;
break;
case HAL_CRYP_MSPDEINIT_CB_ID :
hcryp->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hcryp->State == HAL_CRYP_STATE_RESET)
{
switch (CallbackID)
{
case HAL_CRYP_MSPINIT_CB_ID :
hcryp->MspInitCallback = pCallback;
break;
case HAL_CRYP_MSPDEINIT_CB_ID :
hcryp->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hcryp);
return status;
}
/**
* @brief Unregister an CRYP Callback
* CRYP callback is redirected to the weak predefined callback
* @param hcryp cryp handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_CRYP_INPUT_COMPLETE_CB_ID Input FIFO transfer completed callback ID
* @arg @ref HAL_CRYP_OUTPUT_COMPLETE_CB_ID Output FIFO transfer completed callback ID
* @arg @ref HAL_CRYP_ERROR_CB_ID Error callback ID
* @arg @ref HAL_CRYP_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_CRYP_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval status
*/
HAL_StatusTypeDef HAL_CRYP_UnRegisterCallback(CRYP_HandleTypeDef *hcryp, HAL_CRYP_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hcryp);
if (hcryp->State == HAL_CRYP_STATE_READY)
{
switch (CallbackID)
{
case HAL_CRYP_INPUT_COMPLETE_CB_ID :
hcryp->InCpltCallback = HAL_CRYP_InCpltCallback; /* Legacy weak InCpltCallback */
break;
case HAL_CRYP_OUTPUT_COMPLETE_CB_ID :
hcryp->OutCpltCallback = HAL_CRYP_OutCpltCallback; /* Legacy weak OutCpltCallback */
break;
case HAL_CRYP_ERROR_CB_ID :
hcryp->ErrorCallback = HAL_CRYP_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_CRYP_MSPINIT_CB_ID :
hcryp->MspInitCallback = HAL_CRYP_MspInit;
break;
case HAL_CRYP_MSPDEINIT_CB_ID :
hcryp->MspDeInitCallback = HAL_CRYP_MspDeInit;
break;
default :
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hcryp->State == HAL_CRYP_STATE_RESET)
{
switch (CallbackID)
{
case HAL_CRYP_MSPINIT_CB_ID :
hcryp->MspInitCallback = HAL_CRYP_MspInit;
break;
case HAL_CRYP_MSPDEINIT_CB_ID :
hcryp->MspDeInitCallback = HAL_CRYP_MspDeInit;
break;
default :
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_INVALID_CALLBACK;;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hcryp);
return status;
}
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
/**
* @brief Request CRYP processing suspension when in interruption mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @note Set the handle field SuspendRequest to the appropriate value so that
* the on-going CRYP processing is suspended as soon as the required
* conditions are met.
* @note HAL_CRYP_ProcessSuspend() can only be invoked when the processing is done
* in non-blocking interrupt mode.
* @note It is advised not to suspend the CRYP processing when the DMA controller
* is managing the data transfer.
* @retval None
*/
void HAL_CRYP_ProcessSuspend(CRYP_HandleTypeDef *hcryp)
{
/* Set Handle SuspendRequest field */
hcryp->SuspendRequest = HAL_CRYP_SUSPEND;
}
/**
* @brief CRYP processing suspension and peripheral internal parameters storage.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @note peripheral internal parameters are stored to be readily available when
* suspended processing is resumed later on.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Suspend(CRYP_HandleTypeDef *hcryp)
{
HAL_CRYP_STATETypeDef state;
/* Request suspension */
HAL_CRYP_ProcessSuspend(hcryp);
do
{
state = HAL_CRYP_GetState(hcryp);
} while ((state != HAL_CRYP_STATE_SUSPENDED) && (state != HAL_CRYP_STATE_READY));
if (HAL_CRYP_GetState(hcryp) == HAL_CRYP_STATE_READY)
{
/* Processing was already over or was about to end. No suspension done */
return HAL_ERROR;
}
else
{
/* Suspend Processing */
/* If authentication algorithms on-going, carry out first saving steps
before disable the peripheral */
if ((hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) || \
(hcryp->Init.Algorithm == CRYP_AES_CCM))
{
/* Save Suspension registers */
CRYP_Read_SuspendRegisters(hcryp, hcryp->SUSPxR_saved);
/* Save Key */
CRYP_Read_KeyRegisters(hcryp, hcryp->Key_saved, hcryp->Init.KeySize);
/* Save IV */
CRYP_Read_IVRegisters(hcryp, hcryp->IV_saved);
}
/* Disable AES */
__HAL_CRYP_DISABLE(hcryp);
/* Save low-priority block CRYP handle parameters */
hcryp->Init_saved = hcryp->Init;
hcryp->pCrypInBuffPtr_saved = hcryp->pCrypInBuffPtr;
hcryp->pCrypOutBuffPtr_saved = hcryp->pCrypOutBuffPtr;
hcryp->CrypInCount_saved = hcryp->CrypInCount;
hcryp->CrypOutCount_saved = hcryp->CrypOutCount;
hcryp->Phase_saved = hcryp->Phase;
hcryp->State_saved = hcryp->State;
hcryp->Size_saved = ( (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) ? (hcryp->Size /4U) : hcryp->Size);
hcryp->SizesSum_saved = hcryp->SizesSum;
hcryp->AutoKeyDerivation_saved = hcryp->AutoKeyDerivation;
hcryp->CrypHeaderCount_saved = hcryp->CrypHeaderCount;
hcryp->SuspendRequest = HAL_CRYP_SUSPEND_NONE;
if ((hcryp->Init.Algorithm == CRYP_AES_CBC) || \
(hcryp->Init.Algorithm == CRYP_AES_CTR))
{
/* Save Initialisation Vector registers */
CRYP_Read_IVRegisters(hcryp, hcryp->IV_saved);
}
/* Save Control register */
hcryp->CR_saved = hcryp->Instance->CR;
}
return HAL_OK;
}
/**
* @brief CRYP processing resumption.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @note Processing restarts at the exact point where it was suspended, based
* on the parameters saved at suspension time.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Resume(CRYP_HandleTypeDef *hcryp)
{
/* Check the CRYP handle allocation */
if (hcryp == NULL)
{
return HAL_ERROR;
}
if (hcryp->State_saved != HAL_CRYP_STATE_SUSPENDED)
{
/* CRYP was not suspended */
return HAL_ERROR;
}
else
{
/* Restore low-priority block CRYP handle parameters */
hcryp->Init = hcryp->Init_saved;
hcryp->State = hcryp->State_saved;
/* Chaining algorithms case */
if ((hcryp->Init_saved.Algorithm == CRYP_AES_ECB) || \
(hcryp->Init_saved.Algorithm == CRYP_AES_CBC) || \
(hcryp->Init_saved.Algorithm == CRYP_AES_CTR))
{
/* Restore low-priority block CRYP handle parameters */
hcryp->AutoKeyDerivation = hcryp->AutoKeyDerivation_saved;
if ((hcryp->Init.Algorithm == CRYP_AES_CBC) || \
(hcryp->Init.Algorithm == CRYP_AES_CTR))
{
hcryp->Init.pInitVect = hcryp->IV_saved;
}
__HAL_CRYP_DISABLE(hcryp);
(void) HAL_CRYP_Init(hcryp);
}
else /* Authentication algorithms case */
{
/* Restore low-priority block CRYP handle parameters */
hcryp->Phase = hcryp->Phase_saved;
hcryp->CrypHeaderCount = hcryp->CrypHeaderCount_saved;
hcryp->SizesSum = hcryp->SizesSum_saved;
/* Disable AES and write-back SUSPxR registers */;
__HAL_CRYP_DISABLE(hcryp);
/* Restore AES Suspend Registers */
CRYP_Write_SuspendRegisters(hcryp, hcryp->SUSPxR_saved);
/* Restore Control, Key and IV Registers, then enable AES */
hcryp->Instance->CR = hcryp->CR_saved;
CRYP_Write_KeyRegisters(hcryp, hcryp->Key_saved, hcryp->Init.KeySize);
CRYP_Write_IVRegisters(hcryp, hcryp->IV_saved);
/* At the same time, set handle state back to READY to be able to resume the AES calculations
without the processing APIs returning HAL_BUSY when called. */
hcryp->State = HAL_CRYP_STATE_READY;
}
/* Resume low-priority block processing under IT */
hcryp->ResumingFlag = 1U;
if (READ_BIT(hcryp->CR_saved, AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT)
{
if (HAL_CRYP_Encrypt_IT(hcryp, hcryp->pCrypInBuffPtr_saved, hcryp->Size_saved, hcryp->pCrypOutBuffPtr_saved) != HAL_OK)
{
return HAL_ERROR;
}
}
else
{
if (HAL_CRYP_Decrypt_IT(hcryp, hcryp->pCrypInBuffPtr_saved, hcryp->Size_saved, hcryp->pCrypOutBuffPtr_saved) != HAL_OK)
{
return HAL_ERROR;
}
}
}
return HAL_OK;
}
#endif /* defined (USE_HAL_CRYP_SUSPEND_RESUME) */
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group2 Encryption Decryption functions
* @brief Encryption Decryption functions.
*
@verbatim
==============================================================================
##### Encrypt Decrypt functions #####
==============================================================================
[..] This section provides API allowing to Encrypt/Decrypt Data following
Standard DES/TDES or AES, and Algorithm configured by the user:
(+) Standard DES/TDES only supported by CRYP1 peripheral, below list of Algorithm supported :
- Electronic Code Book(ECB)
- Cipher Block Chaining (CBC)
(+) Standard AES supported by CRYP1 peripheral & TinyAES, list of Algorithm supported:
- Electronic Code Book(ECB)
- Cipher Block Chaining (CBC)
- Counter mode (CTR)
- Cipher Block Chaining (CBC)
- Counter mode (CTR)
- Galois/counter mode (GCM)
- Counter with Cipher Block Chaining-Message(CCM)
[..] Three processing functions are available:
(+) Polling mode : HAL_CRYP_Encrypt & HAL_CRYP_Decrypt
(+) Interrupt mode : HAL_CRYP_Encrypt_IT & HAL_CRYP_Decrypt_IT
(+) DMA mode : HAL_CRYP_Encrypt_DMA & HAL_CRYP_Decrypt_DMA
@endverbatim
* @{
*/
/* GCM message structure additional details
ICB
+-------------------------------------------------------+
| Initialization vector (IV) | Counter |
|----------------|----------------|-----------|---------|
127 95 63 31 0
Bit Number Register Contents
---------- --------------- -----------
127 ...96 CRYP_IV1R[31:0] ICB[127:96]
95 ...64 CRYP_IV1L[31:0] B0[95:64]
63 ... 32 CRYP_IV0R[31:0] ICB[63:32]
31 ... 0 CRYP_IV0L[31:0] ICB[31:0], where 32-bit counter= 0x2
GCM last block definition
+-------------------------------------------------------------------+
| Bit[0] | Bit[32] | Bit[64] | Bit[96] |
|-----------|--------------------|-----------|----------------------|
| 0x0 | Header length[31:0]| 0x0 | Payload length[31:0] |
|-----------|--------------------|-----------|----------------------|
*/
/* CCM message blocks description
(##) B0 block : According to NIST Special Publication 800-38C,
The first block B0 is formatted as follows, where l(m) is encoded in
most-significant-byte first order:
Octet Number Contents
------------ ---------
0 Flags
1 ... 15-q Nonce N
16-q ... 15 Q
the Flags field is formatted as follows:
Bit Number Contents
---------- ----------------------
7 Reserved (always zero)
6 Adata
5 ... 3 (t-2)/2
2 ... 0 [q-1]3
- Q: a bit string representation of the octet length of P (plaintext)
- q The octet length of the binary representation of the octet length of the payload
- A nonce (N), n The octet length of the where n+q=15.
- Flags: most significant octet containing four flags for control information,
- t The octet length of the MAC.
(##) B1 block (header) : associated data length(a) concatenated with Associated Data (A)
the associated data length expressed in bytes (a) defined as below:
- If 0 < a < 216-28, then it is encoded as [a]16, i.e. two octets
- If 216-28 < a < 232, then it is encoded as 0xff || 0xfe || [a]32, i.e. six octets
- If 232 < a < 264, then it is encoded as 0xff || 0xff || [a]64, i.e. ten octets
(##) CTRx block : control blocks
- Generation of CTR1 from first block B0 information :
equal to B0 with first 5 bits zeroed and most significant bits storing octet
length of P also zeroed, then incremented by one
Bit Number Register Contents
---------- --------------- -----------
127 ...96 CRYP_IV1R[31:0] B0[127:96], where Q length bits are set to 0, except for
bit 0 that is set to 1
95 ...64 CRYP_IV1L[31:0] B0[95:64]
63 ... 32 CRYP_IV0R[31:0] B0[63:32]
31 ... 0 CRYP_IV0L[31:0] B0[31:0], where flag bits set to 0
- Generation of CTR0: same as CTR1 with bit[0] set to zero.
*/
/**
* @brief Encryption mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (plaintext)
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(ciphertext)
* @param Timeout Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, uint32_t Timeout)
{
uint32_t algo;
HAL_StatusTypeDef status;
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set the operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
/* AES encryption */
status = CRYP_AES_Encrypt(hcryp, Timeout);
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM encryption */
status = CRYP_AESGCM_Process(hcryp, Timeout) ;
break;
case CRYP_AES_CCM:
/* AES CCM encryption */
status = CRYP_AESCCM_Process(hcryp, Timeout);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
if (status == HAL_OK)
{
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Decryption mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (ciphertext )
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(plaintext)
* @param Timeout Specify Timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, uint32_t Timeout)
{
HAL_StatusTypeDef status;
uint32_t algo;
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set Decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
/* AES decryption */
status = CRYP_AES_Decrypt(hcryp, Timeout);
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM decryption */
status = CRYP_AESGCM_Process(hcryp, Timeout) ;
break;
case CRYP_AES_CCM:
/* AES CCM decryption */
status = CRYP_AESCCM_Process(hcryp, Timeout);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
if (status == HAL_OK)
{
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Encryption in interrupt mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (plaintext)
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(ciphertext)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output)
{
HAL_StatusTypeDef status;
uint32_t algo;
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
if (hcryp->ResumingFlag == 1U)
{
hcryp->ResumingFlag = 0U;
if (hcryp->Phase != CRYP_PHASE_HEADER_SUSPENDED)
{
hcryp->CrypInCount = (uint16_t) hcryp->CrypInCount_saved;
hcryp->CrypOutCount = (uint16_t) hcryp->CrypOutCount_saved;
}
else
{
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
}
}
else
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
{
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
}
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set encryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
/* AES encryption */
status = CRYP_AES_Encrypt_IT(hcryp);
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM encryption */
status = CRYP_AESGCM_Process_IT(hcryp) ;
break;
case CRYP_AES_CCM:
/* AES CCM encryption */
status = CRYP_AESCCM_Process_IT(hcryp);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Decryption in interrupt mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (ciphertext )
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(plaintext)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output)
{
HAL_StatusTypeDef status;
uint32_t algo;
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
if (hcryp->ResumingFlag == 1U)
{
hcryp->ResumingFlag = 0U;
if (hcryp->Phase != CRYP_PHASE_HEADER_SUSPENDED)
{
hcryp->CrypInCount = (uint16_t) hcryp->CrypInCount_saved;
hcryp->CrypOutCount = (uint16_t) hcryp->CrypOutCount_saved;
}
else
{
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
}
}
else
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
{
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
}
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
/* AES decryption */
status = CRYP_AES_Decrypt_IT(hcryp);
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM decryption */
status = CRYP_AESGCM_Process_IT(hcryp) ;
break;
case CRYP_AES_CCM:
/* AES CCM decryption */
status = CRYP_AESCCM_Process_IT(hcryp);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Encryption in DMA mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (plaintext)
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(ciphertext)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output)
{
HAL_StatusTypeDef status;
uint32_t algo;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set encryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the Initialization Vector*/
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Start DMA process transfer for AES */
CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr));
status = HAL_OK;
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM encryption */
status = CRYP_AESGCM_Process_DMA(hcryp) ;
break;
case CRYP_AES_CCM:
/* AES CCM encryption */
status = CRYP_AESCCM_Process_DMA(hcryp);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @brief Decryption in DMA mode.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Input Pointer to the input buffer (ciphertext )
* @param Size Length of the plaintext buffer in bytes or words (depending upon DataWidthUnit field)
* @param Output Pointer to the output buffer(plaintext)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYP_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output)
{
HAL_StatusTypeDef status;
uint32_t algo;
#ifdef USE_FULL_ASSERT
uint32_t algo_assert = (hcryp->Instance->CR) & AES_CR_CHMOD;
/* Check input buffer size */
assert_param(IS_CRYP_BUFFERSIZE(algo_assert, hcryp->Init.DataWidthUnit, Size));
#endif /* USE_FULL_ASSERT */
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Change state Busy */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Process locked */
__HAL_LOCK(hcryp);
/* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr, pCrypOutBuffPtr and Size parameters*/
hcryp->CrypInCount = 0U;
hcryp->CrypOutCount = 0U;
hcryp->pCrypInBuffPtr = Input;
hcryp->pCrypOutBuffPtr = Output;
/* Calculate Size parameter in Byte*/
if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD)
{
hcryp->Size = Size * 4U;
}
else
{
hcryp->Size = Size;
}
/* Set decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
/* algo get algorithm selected */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
switch (algo)
{
case CRYP_AES_ECB:
case CRYP_AES_CBC:
case CRYP_AES_CTR:
/* AES decryption */
status = CRYP_AES_Decrypt_DMA(hcryp);
break;
case CRYP_AES_GCM_GMAC:
/* AES GCM decryption */
status = CRYP_AESGCM_Process_DMA(hcryp) ;
break;
case CRYP_AES_CCM:
/* AES CCM decryption */
status = CRYP_AESCCM_Process_DMA(hcryp);
break;
default:
hcryp->ErrorCode |= HAL_CRYP_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
break;
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
status = HAL_ERROR;
}
/* Return function status */
return status;
}
/**
* @}
*/
/** @defgroup CRYP_Exported_Functions_Group3 CRYP IRQ handler management
* @brief CRYP IRQ handler.
*
@verbatim
==============================================================================
##### CRYP IRQ handler management #####
==============================================================================
[..] This section provides CRYP IRQ handler and callback functions.
(+) HAL_CRYP_IRQHandler CRYP interrupt request
(+) HAL_CRYP_InCpltCallback input data transfer complete callback
(+) HAL_CRYP_OutCpltCallback output data transfer complete callback
(+) HAL_CRYP_ErrorCallback CRYP error callback
(+) HAL_CRYP_GetState return the CRYP state
(+) HAL_CRYP_GetError return the CRYP error code
@endverbatim
* @{
*/
/**
* @brief This function handles cryptographic interrupt request.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval None
*/
void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp)
{
/* Check if error occurred */
if (__HAL_CRYP_GET_IT_SOURCE(hcryp,CRYP_IT_ERRIE) != RESET)
{
/* If write Error occurred */
if (__HAL_CRYP_GET_FLAG(hcryp,CRYP_IT_WRERR) != RESET)
{
hcryp->ErrorCode |= HAL_CRYP_ERROR_WRITE;
}
/* If read Error occurred */
if (__HAL_CRYP_GET_FLAG(hcryp,CRYP_IT_RDERR) != RESET)
{
hcryp->ErrorCode |= HAL_CRYP_ERROR_READ;
}
}
if (__HAL_CRYP_GET_FLAG(hcryp, CRYP_IT_CCF) != RESET)
{
if(__HAL_CRYP_GET_IT_SOURCE(hcryp, CRYP_IT_CCFIE) != RESET)
{
/* Clear computation complete flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
if ((hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) || (hcryp->Init.Algorithm == CRYP_AES_CCM))
{
/* if header phase */
if ((hcryp->Instance->CR & CRYP_PHASE_HEADER) == CRYP_PHASE_HEADER)
{
CRYP_GCMCCM_SetHeaderPhase_IT(hcryp);
}
else /* if payload phase */
{
CRYP_GCMCCM_SetPayloadPhase_IT(hcryp);
}
}
else /* AES Algorithm ECB,CBC or CTR*/
{
CRYP_AES_IT(hcryp);
}
}
}
}
/**
* @brief Return the CRYP error code.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for the CRYP peripheral
* @retval CRYP error code
*/
uint32_t HAL_CRYP_GetError(CRYP_HandleTypeDef *hcryp)
{
return hcryp->ErrorCode;
}
/**
* @brief Returns the CRYP state.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @retval HAL state
*/
HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp)
{
return hcryp->State;
}
/**
* @brief Input FIFO transfer completed callback.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @retval None
*/
__weak void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcryp);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CRYP_InCpltCallback can be implemented in the user file
*/
}
/**
* @brief Output FIFO transfer completed callback.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @retval None
*/
__weak void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcryp);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CRYP_OutCpltCallback can be implemented in the user file
*/
}
/**
* @brief CRYP error callback.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @retval None
*/
__weak void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcryp);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_CRYP_ErrorCallback can be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup CRYP_Private_Functions
* @{
*/
/**
* @brief Encryption in ECB/CBC & CTR Algorithm with AES Standard
* @param hcryp pointer to a CRYP_HandleTypeDef structure
* @param Timeout specify Timeout value
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AES_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint16_t incount; /* Temporary CrypInCount Value */
uint16_t outcount; /* Temporary CrypOutCount Value */
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
/* Set the Initialization Vector*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
while ((incount < (hcryp->Size / 4U)) && (outcount < (hcryp->Size / 4U)))
{
/* Write plain Ddta and get cipher data */
CRYP_AES_ProcessData(hcryp, Timeout);
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
}
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Encryption in ECB/CBC & CTR mode with AES Standard using interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AES_Encrypt_IT(CRYP_HandleTypeDef *hcryp)
{
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
/* Set the Initialization Vector*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
if (hcryp->Size != 0U)
{
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
else
{
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Decryption in ECB/CBC & CTR mode with AES Standard
* @param hcryp pointer to a CRYP_HandleTypeDef structure
* @param Timeout Specify Timeout value
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AES_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint16_t incount; /* Temporary CrypInCount Value */
uint16_t outcount; /* Temporary CrypOutCount Value */
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Key preparation for ECB/CBC */
if (hcryp->Init.Algorithm != CRYP_AES_CTR) /*ECB or CBC*/
{
if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 Key preparation*/
{
/* Set key preparation for decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION);
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Wait for CCF flag to be raised */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state & error code*/
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Return to decryption operating mode(Mode 3)*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
}
else /*Mode 4 : decryption & Key preparation*/
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set decryption & Key preparation operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT);
}
}
else /*Algorithm CTR */
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
}
/* Set IV */
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
/* Set the Initialization Vector*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
while ((incount < (hcryp->Size / 4U)) && (outcount < (hcryp->Size / 4U)))
{
/* Write plain data and get cipher data */
CRYP_AES_ProcessData(hcryp, Timeout);
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
}
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Decryption in ECB/CBC & CTR mode with AES Standard using interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AES_Decrypt_IT(CRYP_HandleTypeDef *hcryp)
{
__IO uint32_t count = 0U;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Key preparation for ECB/CBC */
if (hcryp->Init.Algorithm != CRYP_AES_CTR)
{
if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 Key preparation*/
{
/* Set key preparation for decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION);
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Wait for CCF flag to be raised */
count = CRYP_TIMEOUT_KEYPREPARATION;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Return to decryption operating mode(Mode 3)*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
}
else /*Mode 4 : decryption & key preparation*/
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set decryption & key preparation operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT);
}
}
else /*Algorithm CTR */
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
}
/* Set IV */
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
/* Set the Initialization Vector*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
if (hcryp->Size != 0U)
{
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
else
{
/* Process locked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Decryption in ECB/CBC & CTR mode with AES Standard using DMA mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AES_Decrypt_DMA(CRYP_HandleTypeDef *hcryp)
{
__IO uint32_t count = 0U;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
}
}
if (DoKeyIVConfig == 1U)
{
/* Key preparation for ECB/CBC */
if (hcryp->Init.Algorithm != CRYP_AES_CTR)
{
if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 key preparation*/
{
/* Set key preparation for decryption operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION);
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Enable CRYP */
__HAL_CRYP_ENABLE(hcryp);
/* Wait for CCF flag to be raised */
count = CRYP_TIMEOUT_KEYPREPARATION;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Return to decryption operating mode(Mode 3)*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT);
}
else /*Mode 4 : decryption & key preparation*/
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set decryption & Key preparation operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT);
}
}
else /*Algorithm CTR */
{
/* Set the Key*/
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
}
if (hcryp->Init.Algorithm != CRYP_AES_ECB)
{
/* Set the Initialization Vector*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
}
} /* if (DoKeyIVConfig == 1U) */
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
if (hcryp->Size != 0U)
{
/* Set the input and output addresses and start DMA transfer */
CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr));
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief DMA CRYP input data process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma)
{
CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
uint32_t loopcounter;
uint32_t headersize_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
/* Stop the DMA transfers to the IN FIFO by clearing to "0" the DMAINEN */
CLEAR_BIT(hcryp->Instance->CR, AES_CR_DMAINEN);
if (hcryp->Phase == CRYP_PHASE_HEADER_DMA_FEED)
{
/* DMA is disabled, CCF is meaningful. Wait for computation completion before moving forward */
CRYP_ClearCCFlagWhenHigh(hcryp, CRYP_TIMEOUT_GCMCCMHEADERPHASE);
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
headersize_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
headersize_in_bytes = hcryp->Init.HeaderSize;
}
if ((headersize_in_bytes % 16U) != 0U)
{
/* Write last words that couldn't be fed by DMA */
hcryp->CrypHeaderCount = (uint16_t)((headersize_in_bytes / 16U) * 4U);
for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes / 4U) % 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((headersize_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
loopcounter++;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
/* Wait for computation completion before moving forward */
CRYP_ClearCCFlagWhenHigh(hcryp, CRYP_TIMEOUT_GCMCCMHEADERPHASE);
} /* if ((headersize_in_bytes % 16U) != 0U) */
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
/* Select payload phase once the header phase is performed */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD);
/* Initiate payload DMA IN and processed data DMA OUT transfers */
(void)CRYP_GCMCCM_SetPayloadPhase_DMA(hcryp);
}
else
{
uint32_t algo;
/* ECB, CBC or CTR end of input data feeding
or
end of GCM/CCM payload data feeding through DMA */
algo = hcryp->Instance->CR & AES_CR_CHMOD;
/* Don't call input data transfer complete callback only if
it remains some input data to write to the peripheral.
This case can only occur for GCM and CCM with a payload length
not a multiple of 16 bytes */
if (!(((algo == CRYP_AES_GCM_GMAC) || (algo == CRYP_AES_CCM)) && \
(((hcryp->Size) % 16U) != 0U)))
{
/* Call input data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
} /* if (hcryp->Phase == CRYP_PHASE_HEADER_DMA_FEED) */
}
/**
* @brief DMA CRYP output data process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma)
{
uint32_t count;
uint32_t npblb;
uint32_t lastwordsize;
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t mode;
CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Stop the DMA transfers to the OUT FIFO by clearing to "0" the DMAOUTEN */
CLEAR_BIT(hcryp->Instance->CR, AES_CR_DMAOUTEN);
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Last block transfer in case of GCM or CCM with Size not %16*/
if (((hcryp->Size) % 16U) != 0U)
{
/* set CrypInCount and CrypOutCount to exact number of word already computed via DMA */
hcryp->CrypInCount = (hcryp->Size / 16U) * 4U;
hcryp->CrypOutCount = hcryp->CrypInCount;
/* Compute the number of padding bytes in last block of payload */
npblb = ((((uint32_t)hcryp->Size / 16U) + 1U) * 16U) - ((uint32_t)hcryp->Size);
mode = hcryp->Instance->CR & AES_CR_MODE;
if (((mode == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
((mode == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Last block optionally pad the data with zeros*/
for (count = 0U; count < lastwordsize; count++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (count < 4U)
{
/* Pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
count++;
}
/* Call input data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
/*Wait on CCF flag*/
CRYP_ClearCCFlagWhenHigh(hcryp, CRYP_TIMEOUT_GCMCCMHEADERPHASE);
/*Read the output block from the output FIFO */
for (count = 0U; count < 4U; count++)
{
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */
temp[count] = hcryp->Instance->DOUTR;
}
count = 0U;
while((hcryp->CrypOutCount < ((hcryp->Size + 3U)/4U)) && (count<4U))
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[count];
hcryp->CrypOutCount++;
count++;
}
}
if (((hcryp->Init.Algorithm & CRYP_AES_GCM_GMAC) != CRYP_AES_GCM_GMAC) && ((hcryp->Init.Algorithm & CRYP_AES_CCM) != CRYP_AES_CCM))
{
/* Disable CRYP (not allowed in GCM)*/
__HAL_CRYP_DISABLE(hcryp);
}
/* Change the CRYP state to ready */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/* Call output data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Output complete callback*/
hcryp->OutCpltCallback(hcryp);
#else
/*Call legacy weak Output complete callback*/
HAL_CRYP_OutCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/**
* @brief DMA CRYP communication error callback.
* @param hdma DMA handle
* @retval None
*/
static void CRYP_DMAError(DMA_HandleTypeDef *hdma)
{
CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* DMA error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_DMA;
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Call error callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/**
* @brief Set the DMA configuration and start the DMA transfer
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param inputaddr address of the input buffer
* @param Size size of the input and output buffers in words, must be a multiple of 4
* @param outputaddr address of the output buffer
* @retval None
*/
static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr)
{
/* Set the CRYP DMA transfer complete callback */
hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt;
/* Set the DMA input error callback */
hcryp->hdmain->XferErrorCallback = CRYP_DMAError;
/* Set the CRYP DMA transfer complete callback */
hcryp->hdmaout->XferCpltCallback = CRYP_DMAOutCplt;
/* Set the DMA output error callback */
hcryp->hdmaout->XferErrorCallback = CRYP_DMAError;
if ((hcryp->Init.Algorithm & CRYP_AES_GCM_GMAC) != CRYP_AES_GCM_GMAC)
{
/* Enable CRYP (not allowed in GCM & CCM)*/
__HAL_CRYP_ENABLE(hcryp);
}
/* Enable the DMA input stream */
if (HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&hcryp->Instance->DINR, Size) != HAL_OK)
{
/* DMA error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_DMA;
/* Call error callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/* Enable the DMA output stream */
if (HAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&hcryp->Instance->DOUTR, outputaddr, Size) != HAL_OK)
{
/* DMA error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_DMA;
/* Call error callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/* Enable In and Out DMA requests */
SET_BIT(hcryp->Instance->CR, (AES_CR_DMAINEN | AES_CR_DMAOUTEN));
}
/**
* @brief Set the DMA configuration and start the header DMA transfer
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param inputaddr address of the input buffer
* @param Size size of the input buffer in words, must be a multiple of 4
* @retval None
*/
static HAL_StatusTypeDef CRYP_SetHeaderDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size)
{
/* Set the CRYP DMA transfer complete callback */
hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt;
/* Set the DMA input error callback */
hcryp->hdmain->XferErrorCallback = CRYP_DMAError;
/* Mark that header is fed to the peripheral in DMA mode */
hcryp->Phase = CRYP_PHASE_HEADER_DMA_FEED;
/* Enable the DMA input stream */
if (HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&hcryp->Instance->DINR, Size) != HAL_OK)
{
/* DMA error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_DMA;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
/* Call error callback */
}
/* Enable IN DMA requests */
SET_BIT(hcryp->Instance->CR, AES_CR_DMAINEN);
return HAL_OK;
}
/**
* @brief Process Data: Write Input data in polling mode and used in AES functions.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Timeout Specify Timeout value
* @retval None
*/
static void CRYP_AES_ProcessData(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t i;
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
/* Wait for CCF flag to be raised */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/*Call registered error callback*/
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/
for (i = 0U; i < 4U; i++)
{
temp[i] = hcryp->Instance->DOUTR;
}
i= 0U;
while((hcryp->CrypOutCount < ((hcryp->Size + 3U)/4U)) && (i<4U))
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i];
hcryp->CrypOutCount++;
i++;
}
}
/**
* @brief Handle CRYP block input/output data handling under interruption.
* @note The function is called under interruption only, once
* interruptions have been enabled by HAL_CRYP_Encrypt_IT or HAL_CRYP_Decrypt_IT.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @retval HAL status
*/
static void CRYP_AES_IT(CRYP_HandleTypeDef *hcryp)
{
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t i;
if (hcryp->State == HAL_CRYP_STATE_BUSY)
{
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/
for (i = 0U; i < 4U; i++)
{
temp[i] = hcryp->Instance->DOUTR;
}
i= 0U;
while((hcryp->CrypOutCount < ((hcryp->Size + 3U)/4U)) && (i<4U))
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i];
hcryp->CrypOutCount++;
i++;
}
if (hcryp->CrypOutCount == (hcryp->Size / 4U))
{
/* Disable Computation Complete flag and errors interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
/* Call Output transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Output complete callback*/
hcryp->OutCpltCallback(hcryp);
#else
/*Call legacy weak Output complete callback*/
HAL_CRYP_OutCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
else
{
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
/* If suspension flag has been raised, suspend processing
only if not already at the end of the payload */
if (hcryp->SuspendRequest == HAL_CRYP_SUSPEND)
{
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* reset SuspendRequest */
hcryp->SuspendRequest = HAL_CRYP_SUSPEND_NONE;
/* Disable Computation Complete Flag and Errors Interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE|CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_SUSPENDED;
/* Mark that the payload phase is suspended */
hcryp->Phase = CRYP_PHASE_PAYLOAD_SUSPENDED;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
}
else
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
{
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if (hcryp->CrypInCount == (hcryp->Size / 4U))
{
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
}
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/**
* @brief Writes Key in Key registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param KeySize Size of Key
* @note If pKey is NULL, the Key registers are not written. This configuration
* occurs when the key is written out of HAL scope.
* @retval None
*/
static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint32_t KeySize)
{
if (hcryp->Init.pKey != NULL)
{
switch (KeySize)
{
case CRYP_KEYSIZE_256B:
hcryp->Instance->KEYR7 = *(uint32_t *)(hcryp->Init.pKey);
hcryp->Instance->KEYR6 = *(uint32_t *)(hcryp->Init.pKey + 1U);
hcryp->Instance->KEYR5 = *(uint32_t *)(hcryp->Init.pKey + 2U);
hcryp->Instance->KEYR4 = *(uint32_t *)(hcryp->Init.pKey + 3U);
hcryp->Instance->KEYR3 = *(uint32_t *)(hcryp->Init.pKey + 4U);
hcryp->Instance->KEYR2 = *(uint32_t *)(hcryp->Init.pKey + 5U);
hcryp->Instance->KEYR1 = *(uint32_t *)(hcryp->Init.pKey + 6U);
hcryp->Instance->KEYR0 = *(uint32_t *)(hcryp->Init.pKey + 7U);
break;
case CRYP_KEYSIZE_128B:
hcryp->Instance->KEYR3 = *(uint32_t *)(hcryp->Init.pKey);
hcryp->Instance->KEYR2 = *(uint32_t *)(hcryp->Init.pKey + 1U);
hcryp->Instance->KEYR1 = *(uint32_t *)(hcryp->Init.pKey + 2U);
hcryp->Instance->KEYR0 = *(uint32_t *)(hcryp->Init.pKey + 3U);
break;
default:
break;
}
}
}
/**
* @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Timeout Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESGCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t wordsize = ((uint32_t)hcryp->Size / 4U) ;
uint32_t npblb;
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t index;
uint32_t lastwordsize;
uint32_t incount; /* Temporary CrypInCount Value */
uint32_t outcount; /* Temporary CrypOutCount Value */
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/****************************** Init phase **********************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector and the counter : Initial Counter Block (ICB)*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked & return error */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/************************ Header phase *************************************/
if (CRYP_GCMCCM_SetHeaderPhase(hcryp, Timeout) != HAL_OK)
{
return HAL_ERROR;
}
/*************************Payload phase ************************************/
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase once the header phase is performed */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
} /* if (DoKeyIVConfig == 1U) */
if ((hcryp->Size % 16U) != 0U)
{
/* recalculate wordsize */
wordsize = ((wordsize / 4U) * 4U) ;
}
/* Get tick */
tickstart = HAL_GetTick();
/* Write input data and get output Data */
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
while ((incount < wordsize) && (outcount < wordsize))
{
/* Write plain data and get cipher data */
CRYP_AES_ProcessData(hcryp, Timeout);
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state & error code */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
}
if ((hcryp->Size % 16U) != 0U)
{
/* Compute the number of padding bytes in last block of payload */
npblb = ((((uint32_t)hcryp->Size / 16U) + 1U) * 16U) - ((uint32_t)hcryp->Size);
/* Set Npblb in case of AES GCM payload encryption to get right tag*/
if ((hcryp->Instance->CR & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT)
{
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* last block optionally pad the data with zeros*/
for (index = 0U; index < lastwordsize; index ++)
{
/* Write the last Input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (index < 4U)
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0U;
index++;
}
/* Wait for CCF flag to be raised */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
hcryp->State = HAL_CRYP_STATE_READY;
__HAL_UNLOCK(hcryp);
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/*Read the output block from the output FIFO */
for (index = 0U; index < 4U; index++)
{
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */
temp[index] = hcryp->Instance->DOUTR;
}
for (index = 0U; index < lastwordsize; index++)
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + (hcryp->CrypOutCount)) = temp[index];
hcryp->CrypOutCount++;
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG in interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESGCM_Process_IT(CRYP_HandleTypeDef *hcryp)
{
__IO uint32_t count = 0U;
uint32_t loopcounter;
uint32_t lastwordsize;
uint32_t npblb;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
uint32_t headersize_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
if ((hcryp->Phase == CRYP_PHASE_HEADER_SUSPENDED) || (hcryp->Phase == CRYP_PHASE_PAYLOAD_SUSPENDED))
{
CRYP_PhaseProcessingResume(hcryp);
return HAL_OK;
}
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
/* Manage header size given in bytes to handle cases where
header size is not a multiple of 4 bytes */
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
headersize_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
headersize_in_bytes = hcryp->Init.HeaderSize;
}
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
/* Configure Key, IV and process message (header and payload) */
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/******************************* Init phase *********************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector and the counter : Initial Counter Block (ICB)*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
count = CRYP_TIMEOUT_GCMCCMINITPHASE;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/***************************** Header phase *********************************/
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
if (hcryp->Init.HeaderSize == 0U) /*header phase is skipped*/
{
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase once the header phase is performed */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
/* Write the payload Input block in the IN FIFO */
if (hcryp->Size == 0U)
{
/* Disable interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else if (hcryp->Size >= 16U)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Size < 16Bytes : first block is the last block*/
{
/* Workaround not implemented for TinyAES2*/
/* Size should be %4 otherwise Tag will be incorrectly generated for GCM Encryption:
Workaround is implemented in polling mode, so if last block of
payload <128bit do not use CRYP_Encrypt_IT otherwise TAG is incorrectly generated for GCM Encryption. */
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - ((uint32_t)hcryp->Size);
if ((hcryp->Instance->CR & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT)
{
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize ; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/* Enter header data */
/* Cher first whether header length is small enough to enter the full header in one shot */
else if (headersize_in_bytes <= 16U)
{
/* Write header data, padded with zeros if need be */
for (loopcounter = 0U; (loopcounter < (headersize_in_bytes / 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((headersize_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
hcryp->CrypHeaderCount++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
loopcounter++;
hcryp->CrypHeaderCount++ ;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
hcryp->CrypHeaderCount++;
}
}
}
else
{
/* Write the first input header block in the Input FIFO,
the following header data will be fed after interrupt occurrence */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
}
} /* end of if (DoKeyIVConfig == 1U) */
else /* Key and IV have already been configured,
header has already been processed;
only process here message payload */
{
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
/* Write the payload Input block in the IN FIFO */
if (hcryp->Size == 0U)
{
/* Disable interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else if (hcryp->Size >= 16U)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Size < 16Bytes : first block is the last block*/
{
/* Workaround not implemented for TinyAES2*/
/* Size should be %4 otherwise Tag will be incorrectly generated for GCM Encryption:
Workaround is implemented in polling mode, so if last block of
payload <128bit do not use CRYP_Encrypt_IT otherwise TAG is incorrectly generated for GCM Encryption. */
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - ((uint32_t)hcryp->Size);
if ((hcryp->Instance->CR & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT)
{
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize ; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG using DMA
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESGCM_Process_DMA(CRYP_HandleTypeDef *hcryp)
{
uint32_t count;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/*************************** Init phase ************************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector and the counter : Initial Counter Block (ICB)*/
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
count = CRYP_TIMEOUT_GCMCCMINITPHASE;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/************************ Header phase *************************************/
if (CRYP_GCMCCM_SetHeaderPhase_DMA(hcryp) != HAL_OK)
{
return HAL_ERROR;
}
}
else
{
/* Initialization and header phases already done, only do payload phase */
if (CRYP_GCMCCM_SetPayloadPhase_DMA(hcryp) != HAL_OK)
{
return HAL_ERROR;
}
} /* if (DoKeyIVConfig == 1U) */
/* Return function status */
return HAL_OK;
}
/**
* @brief AES CCM encryption/decryption processing in polling mode
* for TinyAES peripheral, no encrypt/decrypt performed, only authentication preparation.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param Timeout Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESCCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t wordsize = ((uint32_t)hcryp->Size / 4U) ;
uint32_t loopcounter;
uint32_t npblb;
uint32_t lastwordsize;
uint32_t temp[4] ; /* Temporary CrypOutBuff */
uint32_t incount; /* Temporary CrypInCount Value */
uint32_t outcount; /* Temporary CrypOutCount Value */
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/********************** Init phase ******************************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector (IV) with B0 */
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.B0);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.B0 + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.B0 + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.B0 + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked & return error */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/************************ Header phase *************************************/
/* Header block(B1) : associated data length expressed in bytes concatenated
with Associated Data (A)*/
if (CRYP_GCMCCM_SetHeaderPhase(hcryp, Timeout) != HAL_OK)
{
return HAL_ERROR;
}
/*************************Payload phase ************************************/
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase once the header phase is performed */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
} /* if (DoKeyIVConfig == 1U) */
if ((hcryp->Size % 16U) != 0U)
{
/* recalculate wordsize */
wordsize = ((wordsize / 4U) * 4U) ;
}
/* Get tick */
tickstart = HAL_GetTick();
/* Write input data and get output data */
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
while ((incount < wordsize) && (outcount < wordsize))
{
/* Write plain data and get cipher data */
CRYP_AES_ProcessData(hcryp, Timeout);
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) ||(Timeout == 0U))
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
}
if ((hcryp->Size % 16U) != 0U)
{
/* Compute the number of padding bytes in last block of payload */
npblb = ((((uint32_t)hcryp->Size / 16U) + 1U) * 16U) - ((uint32_t)hcryp->Size);
if ((hcryp->Instance->CR & AES_CR_MODE) == CRYP_OPERATINGMODE_DECRYPT)
{
/* Set Npblb in case of AES CCM payload decryption to get right tag */
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Write the last input block in the IN FIFO */
for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter ++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0U;
loopcounter++;
}
/* just wait for hash computation */
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked & return error */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
for (loopcounter = 0U; loopcounter < 4U; loopcounter++)
{
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */
temp[loopcounter] = hcryp->Instance->DOUTR;
}
for (loopcounter = 0U; loopcounter<lastwordsize; loopcounter++)
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[loopcounter];
hcryp->CrypOutCount++;
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief AES CCM encryption/decryption process in interrupt mode
* for TinyAES peripheral, no encrypt/decrypt performed, only authentication preparation.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESCCM_Process_IT(CRYP_HandleTypeDef *hcryp)
{
__IO uint32_t count = 0U;
uint32_t loopcounter;
uint32_t lastwordsize;
uint32_t npblb;
uint32_t mode;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
uint32_t headersize_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
if ((hcryp->Phase == CRYP_PHASE_HEADER_SUSPENDED) || (hcryp->Phase == CRYP_PHASE_PAYLOAD_SUSPENDED))
{
CRYP_PhaseProcessingResume(hcryp);
return HAL_OK;
}
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
/* Configure Key, IV and process message (header and payload) */
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/********************** Init phase ******************************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector (IV) with B0 */
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.B0);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.B0 + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.B0 + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.B0 + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
count = CRYP_TIMEOUT_GCMCCMINITPHASE;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/***************************** Header phase *********************************/
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
headersize_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
headersize_in_bytes = hcryp->Init.HeaderSize;
}
if (headersize_in_bytes == 0U) /* Header phase is skipped */
{
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase once the header phase is performed */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
if (hcryp->Init.Algorithm == CRYP_AES_CCM)
{
/* Increment CrypHeaderCount to pass in CRYP_GCMCCM_SetPayloadPhase_IT */
hcryp->CrypHeaderCount++;
}
/* Write the payload Input block in the IN FIFO */
if (hcryp->Size == 0U)
{
/* Disable interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else if (hcryp->Size >= 16U)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Size < 4 words : first block is the last block*/
{
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - (uint32_t)hcryp->Size;
mode = hcryp->Instance->CR & AES_CR_MODE;
if (((mode == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
((mode == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* Pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/* Enter header data */
/* Check first whether header length is small enough to enter the full header in one shot */
else if (headersize_in_bytes <= 16U)
{
for (loopcounter = 0U; (loopcounter < (headersize_in_bytes / 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((headersize_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
hcryp->CrypHeaderCount++;
loopcounter++;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
else
{
/* Write the first input header block in the Input FIFO,
the following header data will be fed after interrupt occurrence */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
}/* if (hcryp->Init.HeaderSize == 0U) */ /* Header phase is skipped*/
} /* end of if (dokeyivconfig == 1U) */
else /* Key and IV have already been configured,
header has already been processed;
only process here message payload */
{
/* Write the payload Input block in the IN FIFO */
if (hcryp->Size == 0U)
{
/* Disable interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else if (hcryp->Size >= 16U)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Size < 4 words : first block is the last block*/
{
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - (uint32_t)hcryp->Size;
mode = hcryp->Instance->CR & AES_CR_MODE;
if (((mode == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
((mode == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* Pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call Input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/* Return function status */
return HAL_OK;
}
/**
* @brief AES CCM encryption/decryption process in DMA mode
* for TinyAES peripheral, no encrypt/decrypt performed, only authentication preparation.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_AESCCM_Process_DMA(CRYP_HandleTypeDef *hcryp)
{
uint32_t count;
uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */
if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE)
{
if (hcryp->KeyIVConfig == 1U)
{
/* If the Key and IV configuration has to be done only once
and if it has already been done, skip it */
DoKeyIVConfig = 0U;
hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */
}
else
{
/* If the Key and IV configuration has to be done only once
and if it has not been done already, do it and set KeyIVConfig
to keep track it won't have to be done again next time */
hcryp->KeyIVConfig = 1U;
hcryp->SizesSum = hcryp->Size; /* Merely store payload length */
}
}
else
{
hcryp->SizesSum = hcryp->Size;
}
if (DoKeyIVConfig == 1U)
{
/* Reset CrypHeaderCount */
hcryp->CrypHeaderCount = 0U;
/********************** Init phase ******************************************/
CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT);
/* Set the key */
CRYP_SetKey(hcryp, hcryp->Init.KeySize);
/* Set the initialization vector (IV) with B0 */
hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.B0);
hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.B0 + 1U);
hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.B0 + 2U);
hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.B0 + 3U);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* just wait for hash computation */
count = CRYP_TIMEOUT_GCMCCMINITPHASE;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/********************* Header phase *****************************************/
if (CRYP_GCMCCM_SetHeaderPhase_DMA(hcryp) != HAL_OK)
{
return HAL_ERROR;
}
}
else
{
/* Initialization and header phases already done, only do payload phase */
if (CRYP_GCMCCM_SetPayloadPhase_DMA(hcryp) != HAL_OK)
{
return HAL_ERROR;
}
} /* if (DoKeyIVConfig == 1U) */
/* Return function status */
return HAL_OK;
}
/**
* @brief Sets the payload phase in interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval state
*/
static void CRYP_GCMCCM_SetPayloadPhase_IT(CRYP_HandleTypeDef *hcryp)
{
uint32_t loopcounter;
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t lastwordsize;
uint32_t npblb;
uint32_t mode;
uint16_t incount; /* Temporary CrypInCount Value */
uint16_t outcount; /* Temporary CrypOutCount Value */
uint32_t i;
/***************************** Payload phase *******************************/
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/
for (i = 0U; i < 4U; i++)
{
temp[i] = hcryp->Instance->DOUTR;
}
i= 0U;
while((hcryp->CrypOutCount < ((hcryp->Size + 3U)/4U)) && (i<4U))
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i];
hcryp->CrypOutCount++;
i++;
}
incount = hcryp->CrypInCount;
outcount = hcryp->CrypOutCount;
if ((outcount >= (hcryp->Size / 4U)) && ((incount * 4U) >= hcryp->Size))
{
/* When in CCM with Key and IV configuration skipped, don't disable interruptions */
if (!((hcryp->Init.Algorithm == CRYP_AES_CCM) && (hcryp->KeyIVConfig == 1U)))
{
/* Disable computation complete flag and errors interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
}
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/* Call output transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Output complete callback*/
hcryp->OutCpltCallback(hcryp);
#else
/*Call legacy weak Output complete callback*/
HAL_CRYP_OutCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
else if (((hcryp->Size / 4U) - (hcryp->CrypInCount)) >= 4U)
{
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
/* If suspension flag has been raised, suspend processing
only if not already at the end of the payload */
if (hcryp->SuspendRequest == HAL_CRYP_SUSPEND)
{
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* reset SuspendRequest */
hcryp->SuspendRequest = HAL_CRYP_SUSPEND_NONE;
/* Disable Computation Complete Flag and Errors Interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE|CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_SUSPENDED;
/* Mark that the payload phase is suspended */
hcryp->Phase = CRYP_PHASE_PAYLOAD_SUSPENDED;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
}
else
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
{
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
}
else /* Last block of payload < 128bit*/
{
/* Compute the number of padding bytes in last block of payload */
npblb = ((((uint32_t)hcryp->Size / 16U) + 1U) * 16U) - ((uint32_t)hcryp->Size);
mode = hcryp->Instance->CR & AES_CR_MODE;
if (((mode == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
((mode == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
/**
* @brief Sets the payload phase in DMA mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @retval state
*/
static HAL_StatusTypeDef CRYP_GCMCCM_SetPayloadPhase_DMA(CRYP_HandleTypeDef *hcryp)
{
uint16_t wordsize = hcryp->Size / 4U ;
uint32_t index;
uint32_t npblb;
uint32_t lastwordsize;
uint32_t temp[4]; /* Temporary CrypOutBuff */
uint32_t count;
uint32_t reg;
/************************ Payload phase ************************************/
if (hcryp->Size == 0U)
{
/* Process unLocked */
__HAL_UNLOCK(hcryp);
/* Change the CRYP state and phase */
hcryp->State = HAL_CRYP_STATE_READY;
}
else if (hcryp->Size >= 16U)
{
/*DMA transfer must not include the last block in case of Size is not %16 */
wordsize = wordsize - (wordsize % 4U);
/*DMA transfer */
CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), wordsize, (uint32_t)(hcryp->pCrypOutBuffPtr));
}
else /* length of input data is < 16 */
{
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - (uint32_t)hcryp->Size;
/* Set Npblb in case of AES GCM payload encryption or AES CCM payload decryption to get right tag*/
reg = hcryp->Instance->CR & (AES_CR_CHMOD|AES_CR_MODE);
if ((reg == (CRYP_AES_GCM_GMAC|CRYP_OPERATINGMODE_ENCRYPT)) ||\
(reg == (CRYP_AES_CCM|CRYP_OPERATINGMODE_DECRYPT)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* last block optionally pad the data with zeros*/
for (index = 0U; index < lastwordsize; index ++)
{
/* Write the last Input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (index < 4U)
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0U;
index++;
}
/* Call the input data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
/* Wait for CCF flag to be raised */
count = CRYP_TIMEOUT_GCMCCMHEADERPHASE;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/*Read the output block from the output FIFO */
for (index = 0U; index < 4U; index++)
{
/* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */
temp[index] = hcryp->Instance->DOUTR;
}
for (index = 0U; index < lastwordsize; index++)
{
*(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[index];
hcryp->CrypOutCount++;
}
/* Change the CRYP state to ready */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/* Call Output transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Output complete callback*/
hcryp->OutCpltCallback(hcryp);
#else
/*Call legacy weak Output complete callback*/
HAL_CRYP_OutCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
return HAL_OK;
}
/**
* @brief Sets the header phase in polling mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module(Header & HeaderSize)
* @param Timeout Timeout value
* @retval state
*/
static HAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t loopcounter;
uint32_t size_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
/***************************** Header phase for GCM/GMAC or CCM *********************************/
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
size_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
size_in_bytes = hcryp->Init.HeaderSize;
}
if ((size_in_bytes != 0U))
{
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* If size_in_bytes is a multiple of blocks (a multiple of four 32-bits words ) */
if ((size_in_bytes % 16U) == 0U)
{
/* No padding */
for (loopcounter = 0U; (loopcounter < (size_in_bytes / 4U)); loopcounter += 4U)
{
/* Write the input block in the data input register */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
}
}
else
{
/* Write header block in the IN FIFO without last block */
for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 16U) * 4U)); loopcounter += 4U)
{
/* Write the input block in the data input register */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
}
/* Write last complete words */
for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 4U) % 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((size_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (size_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
loopcounter++;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
if (CRYP_WaitOnCCFlag(hcryp, Timeout) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
}
}
else
{
/*Workaround 1: only AES, before re-enabling the peripheral, datatype can be configured.*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_DATATYPE, hcryp->Init.DataType);
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Sets the header phase when using DMA in process
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module(Header & HeaderSize)
* @retval None
*/
static HAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase_DMA(CRYP_HandleTypeDef *hcryp)
{
uint32_t loopcounter;
uint32_t headersize_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
/***************************** Header phase for GCM/GMAC or CCM *********************************/
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
headersize_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
headersize_in_bytes = hcryp->Init.HeaderSize;
}
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* If header size is at least equal to 16 bytes, feed the header through DMA.
If size_in_bytes is not a multiple of blocks (is not a multiple of four 32-bit words ),
last bytes feeding and padding will be done in CRYP_DMAInCplt() */
if (headersize_in_bytes >= 16U)
{
/* Initiate header DMA transfer */
if (CRYP_SetHeaderDMAConfig(hcryp, (uint32_t)(hcryp->Init.Header), (uint16_t)((headersize_in_bytes / 16U) * 4U)) != HAL_OK)
{
return HAL_ERROR;
}
}
else
{
if (headersize_in_bytes != 0U)
{
/* Header length is larger than 0 and strictly less than 16 bytes */
/* Write last complete words */
for (loopcounter = 0U; (loopcounter < (headersize_in_bytes / 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((headersize_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
loopcounter++;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
if (CRYP_WaitOnCCFlag(hcryp, CRYP_TIMEOUT_GCMCCMHEADERPHASE) != HAL_OK)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
} /* if (headersize_in_bytes != 0U) */
/* Move to payload phase if header length is null or
if the header length was less than 16 and header written by software instead of DMA */
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
/* Select payload phase once the header phase is performed */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD);
/* Initiate payload DMA IN and processed data DMA OUT transfers */
if (CRYP_GCMCCM_SetPayloadPhase_DMA(hcryp) != HAL_OK)
{
return HAL_ERROR;
}
} /* if (headersize_in_bytes >= 16U) */
/* Return function status */
return HAL_OK;
}
/**
* @brief Sets the header phase in interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module(Header & HeaderSize)
* @retval None
*/
static void CRYP_GCMCCM_SetHeaderPhase_IT(CRYP_HandleTypeDef *hcryp)
{
uint32_t loopcounter;
uint32_t lastwordsize;
uint32_t npblb;
uint32_t mode;
uint32_t headersize_in_bytes;
uint32_t tmp;
uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */
0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */
0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD)
{
headersize_in_bytes = hcryp->Init.HeaderSize * 4U;
}
else
{
headersize_in_bytes = hcryp->Init.HeaderSize;
}
/***************************** Header phase *********************************/
/* Test whether or not the header phase is over.
If the test below is true, move to payload phase */
if (headersize_in_bytes <= ((uint32_t)(hcryp->CrypHeaderCount) * 4U))
{
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
if (hcryp->Init.Algorithm == CRYP_AES_CCM)
{
/* Increment CrypHeaderCount to pass in CRYP_GCMCCM_SetPayloadPhase_IT */
hcryp->CrypHeaderCount++;
}
/* Write the payload Input block in the IN FIFO */
if (hcryp->Size == 0U)
{
/* Disable interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else if (hcryp->Size >= 16U)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call the input data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Size < 4 words : first block is the last block*/
{
/* Compute the number of padding bytes in last block of payload */
npblb = 16U - ((uint32_t)hcryp->Size);
mode = hcryp->Instance->CR & AES_CR_MODE;
if (((mode == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
((mode == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, npblb << 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) == 0U)
{
lastwordsize = (16U - npblb) / 4U;
}
else
{
lastwordsize = ((16U - npblb) / 4U) + 1U;
}
/* Last block optionally pad the data with zeros*/
for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount);
hcryp->CrypInCount++;
}
while (loopcounter < 4U)
{
/* Pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
/* Call the input data transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else if ((((headersize_in_bytes / 4U) - (hcryp->CrypHeaderCount)) >= 4U))
{
/* Can enter full 4 header words */
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
/* If suspension flag has been raised, suspend processing
only if not already at the end of the header */
if (hcryp->SuspendRequest == HAL_CRYP_SUSPEND)
{
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* reset SuspendRequest */
hcryp->SuspendRequest = HAL_CRYP_SUSPEND_NONE;
/* Disable Computation Complete Flag and Errors Interrupts */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE|CRYP_IT_ERRIE);
/* Change the CRYP state */
hcryp->State = HAL_CRYP_STATE_SUSPENDED;
/* Mark that the payload phase is suspended */
hcryp->Phase = CRYP_PHASE_HEADER_SUSPENDED;
/* Process Unlocked */
__HAL_UNLOCK(hcryp);
}
else
#endif /* USE_HAL_CRYP_SUSPEND_RESUME */
{
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++;
}
}
else /* Write last header block (4 words), padded with zeros if needed */
{
for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes / 4U) % 4U)); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
/* If the header size is a multiple of words */
if ((headersize_in_bytes % 4U) == 0U)
{
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
hcryp->CrypHeaderCount++;
}
}
else
{
/* Enter last bytes, padded with zeros */
tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount);
tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)];
hcryp->Instance->DINR = tmp;
loopcounter++;
hcryp->CrypHeaderCount++;
/* Pad the data with zeros to have a complete block */
while (loopcounter < 4U)
{
hcryp->Instance->DINR = 0x0U;
loopcounter++;
hcryp->CrypHeaderCount++;
}
}
}
}
/**
* @brief Handle CRYP hardware block Timeout when waiting for CCF flag to be raised.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Timeout Timeout duration.
* @note This function can only be used in thread mode.
* @retval HAL status
*/
static HAL_StatusTypeDef CRYP_WaitOnCCFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t tickstart;
/* Get timeout */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF))
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
return HAL_ERROR;
}
}
}
return HAL_OK;
}
/**
* @brief Wait for Computation Complete Flag (CCF) to raise then clear it.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Timeout Timeout duration.
* @note This function can be used in thread or handler mode.
* @retval HAL status
*/
static void CRYP_ClearCCFlagWhenHigh(CRYP_HandleTypeDef *hcryp, uint32_t Timeout)
{
uint32_t count = Timeout;
do
{
count-- ;
if (count == 0U)
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
hcryp->State = HAL_CRYP_STATE_READY;
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1U)
/*Call registered error callback*/
hcryp->ErrorCallback(hcryp);
#else
/*Call legacy weak error callback*/
HAL_CRYP_ErrorCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF));
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
}
#if (USE_HAL_CRYP_SUSPEND_RESUME == 1U)
/**
* @brief In case of message processing suspension, read the Initialization Vector.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Output Pointer to the buffer containing the saved Initialization Vector.
* @note This value has to be stored for reuse by writing the AES_IVRx registers
* as soon as the suspended processing has to be resumed.
* @retval None
*/
static void CRYP_Read_IVRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output)
{
uint32_t outputaddr = (uint32_t)Output;
*(uint32_t*)(outputaddr) = hcryp->Instance->IVR3;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->IVR2;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->IVR1;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->IVR0;
}
/**
* @brief In case of message processing resumption, rewrite the Initialization
* Vector in the AES_IVRx registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Input Pointer to the buffer containing the saved Initialization Vector to
* write back in the CRYP hardware block.
* @note AES must be disabled when reconfiguring the IV values.
* @retval None
*/
static void CRYP_Write_IVRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input)
{
uint32_t ivaddr = (uint32_t)Input;
hcryp->Instance->IVR3 = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->IVR2 = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->IVR1 = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->IVR0 = *(uint32_t*)(ivaddr);
}
/**
* @brief In case of message GCM/GMAC/CCM processing suspension,
* read the Suspend Registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Output Pointer to the buffer containing the saved Suspend Registers.
* @note These values have to be stored for reuse by writing back the AES_SUSPxR registers
* as soon as the suspended processing has to be resumed.
* @retval None
*/
static void CRYP_Read_SuspendRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output)
{
uint32_t outputaddr = (uint32_t)Output;
__IO uint32_t count = 0U;
/* In case of GCM payload phase encryption, check that suspension can be carried out */
if (READ_BIT(hcryp->Instance->CR, (AES_CR_CHMOD|AES_CR_GCMPH|AES_CR_MODE)) == (CRYP_AES_GCM_GMAC|AES_CR_GCMPH_1|0x0U))
{
/* Wait for BUSY flag to be cleared */
count = 0xFFF;
do
{
count-- ;
if(count == 0U)
{
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
HAL_CRYP_ErrorCallback(hcryp);
return;
}
}
while(HAL_IS_BIT_SET(hcryp->Instance->SR, AES_SR_BUSY));
}
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP7R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP6R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP5R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP4R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP3R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP2R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP1R;
outputaddr+=4U;
*(uint32_t*)(outputaddr) = hcryp->Instance->SUSP0R;
}
/**
* @brief In case of message GCM/GMAC/CCM processing resumption, rewrite the Suspend
* Registers in the AES_SUSPxR registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Input Pointer to the buffer containing the saved suspend registers to
* write back in the CRYP hardware block.
* @note AES must be disabled when reconfiguring the suspend registers.
* @retval None
*/
static void CRYP_Write_SuspendRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input)
{
uint32_t ivaddr = (uint32_t)Input;
hcryp->Instance->SUSP7R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP6R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP5R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP4R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP3R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP2R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP1R = *(uint32_t*)(ivaddr);
ivaddr+=4U;
hcryp->Instance->SUSP0R = *(uint32_t*)(ivaddr);
}
/**
* @brief In case of message GCM/GMAC/CCM processing suspension, read the Key Registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Output Pointer to the buffer containing the saved Key Registers.
* @param KeySize Indicates the key size (128 or 256 bits).
* @note These values have to be stored for reuse by writing back the AES_KEYRx registers
* as soon as the suspended processing has to be resumed.
* @retval None
*/
static void CRYP_Read_KeyRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Output, uint32_t KeySize)
{
uint32_t keyaddr = (uint32_t)Output;
switch (KeySize)
{
case CRYP_KEYSIZE_256B:
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 1U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 2U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 3U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 4U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 5U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 6U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 7U);
break;
case CRYP_KEYSIZE_128B:
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 1U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 2U);
keyaddr+=4U;
*(uint32_t*)(keyaddr) = *(uint32_t *)(hcryp->Init.pKey + 3U);
break;
default:
break;
}
}
/**
* @brief In case of message GCM/GMAC (CCM/CMAC when applicable) processing resumption, rewrite the Key
* Registers in the AES_KEYRx registers.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module.
* @param Input Pointer to the buffer containing the saved key registers to
* write back in the CRYP hardware block.
* @param KeySize Indicates the key size (128 or 256 bits)
* @note AES must be disabled when reconfiguring the Key registers.
* @retval None
*/
static void CRYP_Write_KeyRegisters(CRYP_HandleTypeDef *hcryp, uint32_t* Input, uint32_t KeySize)
{
uint32_t keyaddr = (uint32_t)Input;
if (KeySize == CRYP_KEYSIZE_256B)
{
hcryp->Instance->KEYR7 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR6 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR5 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR4 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
}
hcryp->Instance->KEYR3 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR2 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR1 = *(uint32_t*)(keyaddr);
keyaddr+=4U;
hcryp->Instance->KEYR0 = *(uint32_t*)(keyaddr);
}
/**
* @brief Authentication phase resumption in case of GCM/GMAC/CCM process in interrupt mode
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module(Header & HeaderSize)
* @retval None
*/
static void CRYP_PhaseProcessingResume(CRYP_HandleTypeDef *hcryp)
{
uint32_t loopcounter;
uint16_t lastwordsize;
uint16_t npblb;
uint32_t cr_temp;
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_ERR_CLEAR | CRYP_CCF_CLEAR);
/* Enable computation complete flag and error interrupts */
__HAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Enable the CRYP peripheral */
__HAL_CRYP_ENABLE(hcryp);
/* Case of header phase resumption =================================================*/
if (hcryp->Phase == CRYP_PHASE_HEADER_SUSPENDED)
{
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select header phase */
CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER);
if ((((hcryp->Init.HeaderSize) - (hcryp->CrypHeaderCount)) >= 4U))
{
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount );
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount );
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount );
hcryp->CrypHeaderCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount );
hcryp->CrypHeaderCount++;
}
else /*HeaderSize < 4 or HeaderSize >4 & HeaderSize %4 != 0*/
{
/* Last block optionally pad the data with zeros*/
for(loopcounter = 0U; loopcounter < (hcryp->Init.HeaderSize %4U ); loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t*)(hcryp->Init.Header + hcryp->CrypHeaderCount);
hcryp->CrypHeaderCount++ ;
}
while(loopcounter <4U )
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
}
/* Case of payload phase resumption =================================================*/
else
{
if (hcryp->Phase == CRYP_PHASE_PAYLOAD_SUSPENDED)
{
/* Set the phase */
hcryp->Phase = CRYP_PHASE_PROCESS;
/* Select payload phase once the header phase is performed */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD);
/* Set to 0 the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, 0U);
if (((hcryp->Size/4U) - (hcryp->CrypInCount)) >= 4U)
{
/* Write the input block in the IN FIFO */
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount );
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount );
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount );
hcryp->CrypInCount++;
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount );
hcryp->CrypInCount++;
if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U))
{
/* Call input transfer complete callback */
#if (USE_HAL_CRYP_REGISTER_CALLBACKS == 1)
/*Call registered Input complete callback*/
hcryp->InCpltCallback(hcryp);
#else
/*Call legacy weak Input complete callback*/
HAL_CRYP_InCpltCallback(hcryp);
#endif /* USE_HAL_CRYP_REGISTER_CALLBACKS */
}
}
else /* Last block of payload < 128bit*/
{
/* Compute the number of padding bytes in last block of payload */
npblb = (((hcryp->Size/16U)+1U)*16U) - (hcryp->Size);
cr_temp = hcryp->Instance->CR;
if((((cr_temp & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT) && (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC)) ||
(((cr_temp& AES_CR_MODE) == CRYP_OPERATINGMODE_DECRYPT) && (hcryp->Init.Algorithm == CRYP_AES_CCM)))
{
/* Specify the number of non-valid bytes using NPBLB register*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_NPBLB, ((uint32_t)npblb)<< 20U);
}
/* Number of valid words (lastwordsize) in last block */
if ((npblb % 4U) ==0U)
{
lastwordsize = (16U-npblb)/4U;
}
else
{
lastwordsize = ((16U-npblb)/4U) +1U;
}
/* Last block optionally pad the data with zeros*/
for(loopcounter = 0U; loopcounter < lastwordsize; loopcounter++)
{
hcryp->Instance->DINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount );
hcryp->CrypInCount++;
}
while(loopcounter < 4U )
{
/* pad the data with zeros to have a complete block */
hcryp->Instance->DINR = 0x0U;
loopcounter++;
}
}
}
}
}
#endif /* defined (USE_HAL_CRYP_SUSPEND_RESUME) */
/**
* @}
*/
#endif /* HAL_CRYP_MODULE_ENABLED */
#endif /* AES */
/**
* @}
*/
/**
* @}
*/
| 191,156 |
C
| 33.177901 | 165 | 0.612699 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_qspi.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_qspi.c
* @author MCD Application Team
* @brief QSPI HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the QuadSPI interface (QSPI).
* + Initialization and de-initialization functions
* + 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
*
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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_QSPI_MspInit() :
(++) Enable QuadSPI clock interface with __HAL_RCC_QSPI_CLK_ENABLE().
(++) Reset QuadSPI Peripheral with __HAL_RCC_QSPI_FORCE_RESET() and __HAL_RCC_QSPI_RELEASE_RESET().
(++) Enable the clocks for the QuadSPI GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE().
(++) Configure these QuadSPI pins in alternate mode using HAL_GPIO_Init().
(++) If interrupt mode is used, enable and configure QuadSPI global
interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ().
(++) If DMA mode is used, enable the clocks for the QuadSPI DMA channel
with __HAL_RCC_DMAx_CLK_ENABLE(), configure DMA with HAL_DMA_Init(),
link it with QuadSPI handle using __HAL_LINKDMA(), enable and configure
DMA channel global interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ().
(#) Configure the flash size, the clock prescaler, the fifo threshold, the
clock mode, the sample shifting and the CS high time using the HAL_QSPI_Init() function.
*** Indirect functional mode ***
================================
[..]
(#) Configure the command sequence using the HAL_QSPI_Command() or HAL_QSPI_Command_IT()
functions :
(++) Instruction phase : the mode used and if present the instruction opcode.
(++) Address phase : the mode used and if present the size and the address value.
(++) Alternate-bytes phase : the mode used and if present the size and the alternate
bytes values.
(++) 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.
(++) Double Data Rate (DDR) mode : the activation (or not) of this mode and the delay
if activated.
(++) Sending Instruction Only Once (SIOO) mode : the activation (or not) of this mode.
(#) If no data is required for the command, 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_QSPI_CmdCpltCallback() will be called when the transfer is complete.
(#) For the indirect write mode, use HAL_QSPI_Transmit(), HAL_QSPI_Transmit_DMA() or
HAL_QSPI_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_QSPI_FifoThresholdCallback() will be called when the fifo threshold
is reached and HAL_QSPI_TxCpltCallback() will be called when the transfer is complete.
(++) In DMA mode, HAL_QSPI_TxHalfCpltCallback() will be called at the half transfer and
HAL_QSPI_TxCpltCallback() will be called when the transfer is complete.
(#) For the indirect read mode, use HAL_QSPI_Receive(), HAL_QSPI_Receive_DMA() or
HAL_QSPI_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_QSPI_FifoThresholdCallback() will be called when the fifo threshold
is reached and HAL_QSPI_RxCpltCallback() will be called when the transfer is complete.
(++) In DMA mode, HAL_QSPI_RxHalfCpltCallback() will be called at the half transfer and
HAL_QSPI_RxCpltCallback() will be called when the transfer is complete.
*** Auto-polling functional mode ***
====================================
[..]
(#) Configure the command sequence and the auto-polling functional mode using the
HAL_QSPI_AutoPolling() or HAL_QSPI_AutoPolling_IT() functions :
(++) Instruction phase : the mode used and if present the instruction opcode.
(++) Address phase : the mode used and if present the size and the address value.
(++) Alternate-bytes phase : the mode used and if present the size and the alternate
bytes values.
(++) Dummy-cycles phase : the number of dummy cycles (mode used is same as data phase).
(++) Data phase : the mode used.
(++) Double Data Rate (DDR) mode : the activation (or not) of this mode and the delay
if activated.
(++) Sending Instruction Only Once (SIOO) mode : the activation (or not) of this mode.
(++) 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_QSPI_StatusMatchCallback() will be called each time the status match is reached.
*** Memory-mapped functional mode ***
=====================================
[..]
(#) Configure the command sequence and the memory-mapped functional mode using the
HAL_QSPI_MemoryMapped() functions :
(++) Instruction phase : the mode used and if present the instruction opcode.
(++) Address phase : the mode used and the size.
(++) Alternate-bytes phase : the mode used and if present the size and the alternate
bytes values.
(++) Dummy-cycles phase : the number of dummy cycles (mode used is same as data phase).
(++) Data phase : the mode used.
(++) Double Data Rate (DDR) mode : the activation (or not) of this mode and the delay
if activated.
(++) Sending Instruction Only Once (SIOO) mode : the activation (or not) of this mode.
(++) The timeout activation and the timeout period.
(#) After the configuration, the QuadSPI will be used as soon as an access on the AHB is done on
the address range. HAL_QSPI_TimeOutCallback() will be called when the timeout expires.
*** Errors management and abort functionality ***
=================================================
[..]
(#) HAL_QSPI_GetError() function gives the error raised during the last operation.
(#) HAL_QSPI_Abort() and HAL_QSPI_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_QSPI_AbortCpltCallback() will be called when
the transfer complete bit is set.
*** Control functions ***
=========================
[..]
(#) HAL_QSPI_GetState() function gives the current state of the HAL QuadSPI driver.
(#) HAL_QSPI_SetTimeout() function configures the timeout value used in the driver.
(#) HAL_QSPI_SetFifoThreshold() function configures the threshold on the Fifo of the QSPI IP.
(#) HAL_QSPI_GetFifoThreshold() function gives the current of the Fifo's threshold
(#) HAL_QSPI_SetFlashID() function configures the index of the flash memory to be accessed.
*** Callback registration ***
=============================================
[..]
The compilation define USE_HAL_QSPI_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_QSPI_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 : QSPI MspInit.
(+) MspDeInitCallback : QSPI MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
Use function HAL_QSPI_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 : QSPI MspInit.
(+) MspDeInitCallback : QSPI MspDeInit.
This function) takes as parameters the HAL peripheral handle and the Callback ID.
By default, after the HAL_QSPI_Init and if the state is HAL_QSPI_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_QSPI_Init
and HAL_QSPI_DeInit only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_QSPI_Init and HAL_QSPI_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_QSPI_RegisterCallback before calling HAL_QSPI_DeInit
or HAL_QSPI_Init function.
When The compilation define USE_HAL_QSPI_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registering feature is not available
and weak (surcharged) callbacks are used.
*** Workarounds linked to Silicon Limitation ***
====================================================
[..]
(#) Workarounds Implemented inside HAL Driver
(++) Extra data written in the FIFO at the end of a read transfer
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#if defined(QUADSPI)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup QSPI QSPI
* @brief QSPI HAL module driver
* @{
*/
#ifdef HAL_QSPI_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup QSPI_Private_Constants QSPI Private Constants
* @{
*/
#define QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE 0x00000000U /*!<Indirect write mode*/
#define QSPI_FUNCTIONAL_MODE_INDIRECT_READ ((uint32_t)QUADSPI_CCR_FMODE_0) /*!<Indirect read mode*/
#define QSPI_FUNCTIONAL_MODE_AUTO_POLLING ((uint32_t)QUADSPI_CCR_FMODE_1) /*!<Automatic polling mode*/
#define QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED ((uint32_t)QUADSPI_CCR_FMODE) /*!<Memory-mapped mode*/
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/** @defgroup QSPI_Private_Macros QSPI Private Macros
* @{
*/
#define IS_QSPI_FUNCTIONAL_MODE(MODE) (((MODE) == QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE) || \
((MODE) == QSPI_FUNCTIONAL_MODE_INDIRECT_READ) || \
((MODE) == QSPI_FUNCTIONAL_MODE_AUTO_POLLING) || \
((MODE) == QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED))
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void QSPI_DMARxCplt(DMA_HandleTypeDef *hdma);
static void QSPI_DMATxCplt(DMA_HandleTypeDef *hdma);
static void QSPI_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
static void QSPI_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
static void QSPI_DMAError(DMA_HandleTypeDef *hdma);
static void QSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma);
static HAL_StatusTypeDef QSPI_WaitFlagStateUntilTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Flag, FlagStatus State, uint32_t Tickstart, uint32_t Timeout);
static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t FunctionalMode);
/* Exported functions --------------------------------------------------------*/
/** @defgroup QSPI_Exported_Functions QSPI Exported Functions
* @{
*/
/** @defgroup QSPI_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 QuadSPI.
(+) De-initialize the QuadSPI.
@endverbatim
* @{
*/
/**
* @brief Initialize the QSPI mode according to the specified parameters
* in the QSPI_InitTypeDef and initialize the associated handle.
* @param hqspi : QSPI handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Init(QSPI_HandleTypeDef *hqspi)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the QSPI handle allocation */
if(hqspi == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_QSPI_ALL_INSTANCE(hqspi->Instance));
assert_param(IS_QSPI_CLOCK_PRESCALER(hqspi->Init.ClockPrescaler));
assert_param(IS_QSPI_FIFO_THRESHOLD(hqspi->Init.FifoThreshold));
assert_param(IS_QSPI_SSHIFT(hqspi->Init.SampleShifting));
assert_param(IS_QSPI_FLASH_SIZE(hqspi->Init.FlashSize));
assert_param(IS_QSPI_CS_HIGH_TIME(hqspi->Init.ChipSelectHighTime));
assert_param(IS_QSPI_CLOCK_MODE(hqspi->Init.ClockMode));
assert_param(IS_QSPI_DUAL_FLASH_MODE(hqspi->Init.DualFlash));
if (hqspi->Init.DualFlash != QSPI_DUALFLASH_ENABLE )
{
assert_param(IS_QSPI_FLASH_ID(hqspi->Init.FlashID));
}
if(hqspi->State == HAL_QSPI_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hqspi->Lock = HAL_UNLOCKED;
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
/* Reset Callback pointers in HAL_QSPI_STATE_RESET only */
hqspi->ErrorCallback = HAL_QSPI_ErrorCallback;
hqspi->AbortCpltCallback = HAL_QSPI_AbortCpltCallback;
hqspi->FifoThresholdCallback = HAL_QSPI_FifoThresholdCallback;
hqspi->CmdCpltCallback = HAL_QSPI_CmdCpltCallback;
hqspi->RxCpltCallback = HAL_QSPI_RxCpltCallback;
hqspi->TxCpltCallback = HAL_QSPI_TxCpltCallback;
hqspi->RxHalfCpltCallback = HAL_QSPI_RxHalfCpltCallback;
hqspi->TxHalfCpltCallback = HAL_QSPI_TxHalfCpltCallback;
hqspi->StatusMatchCallback = HAL_QSPI_StatusMatchCallback;
hqspi->TimeOutCallback = HAL_QSPI_TimeOutCallback;
if(hqspi->MspInitCallback == NULL)
{
hqspi->MspInitCallback = HAL_QSPI_MspInit;
}
/* Init the low level hardware */
hqspi->MspInitCallback(hqspi);
#else
/* Init the low level hardware : GPIO, CLOCK */
HAL_QSPI_MspInit(hqspi);
#endif
/* Configure the default timeout for the QSPI memory access */
HAL_QSPI_SetTimeout(hqspi, HAL_QSPI_TIMEOUT_DEFAULT_VALUE);
}
/* Configure QSPI FIFO Threshold */
MODIFY_REG(hqspi->Instance->CR, QUADSPI_CR_FTHRES,
((hqspi->Init.FifoThreshold - 1U) << QUADSPI_CR_FTHRES_Pos));
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout);
if(status == HAL_OK)
{
/* Configure QSPI Clock Prescaler and Sample Shift */
MODIFY_REG(hqspi->Instance->CR, (QUADSPI_CR_PRESCALER | QUADSPI_CR_SSHIFT | QUADSPI_CR_FSEL | QUADSPI_CR_DFM),
((hqspi->Init.ClockPrescaler << QUADSPI_CR_PRESCALER_Pos) |
hqspi->Init.SampleShifting | hqspi->Init.FlashID | hqspi->Init.DualFlash));
/* Configure QSPI Flash Size, CS High Time and Clock Mode */
MODIFY_REG(hqspi->Instance->DCR, (QUADSPI_DCR_FSIZE | QUADSPI_DCR_CSHT | QUADSPI_DCR_CKMODE),
((hqspi->Init.FlashSize << QUADSPI_DCR_FSIZE_Pos) |
hqspi->Init.ChipSelectHighTime | hqspi->Init.ClockMode));
/* Enable the QSPI peripheral */
__HAL_QSPI_ENABLE(hqspi);
/* Set QSPI error code to none */
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Initialize the QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
}
/* Release Lock */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/**
* @brief De-Initialize the QSPI peripheral.
* @param hqspi : QSPI handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_DeInit(QSPI_HandleTypeDef *hqspi)
{
/* Check the QSPI handle allocation */
if(hqspi == NULL)
{
return HAL_ERROR;
}
/* Disable the QSPI Peripheral Clock */
__HAL_QSPI_DISABLE(hqspi);
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
if(hqspi->MspDeInitCallback == NULL)
{
hqspi->MspDeInitCallback = HAL_QSPI_MspDeInit;
}
/* DeInit the low level hardware */
hqspi->MspDeInitCallback(hqspi);
#else
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
HAL_QSPI_MspDeInit(hqspi);
#endif
/* Set QSPI error code to none */
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Initialize the QSPI state */
hqspi->State = HAL_QSPI_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hqspi);
return HAL_OK;
}
/**
* @brief Initialize the QSPI MSP.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_MspInit(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the QSPI MSP.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_MspDeInit(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_MspDeInit can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup QSPI_Exported_Functions_Group2 Input and Output operation functions
* @brief QSPI Transmit/Receive functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to :
(+) Handle the interrupts.
(+) Handle the command sequence.
(+) 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 QSPI interrupt request.
* @param hqspi : QSPI handle
* @retval None
*/
void HAL_QSPI_IRQHandler(QSPI_HandleTypeDef *hqspi)
{
__IO uint32_t *data_reg;
uint32_t flag = READ_REG(hqspi->Instance->SR);
uint32_t itsource = READ_REG(hqspi->Instance->CR);
/* QSPI Fifo Threshold interrupt occurred ----------------------------------*/
if(((flag & QSPI_FLAG_FT) != 0U) && ((itsource & QSPI_IT_FT) != 0U))
{
data_reg = &hqspi->Instance->DR;
if(hqspi->State == HAL_QSPI_STATE_BUSY_INDIRECT_TX)
{
/* Transmission process */
while(__HAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_FT) != RESET)
{
if (hqspi->TxXferCount > 0U)
{
/* Fill the FIFO until the threshold is reached */
*((__IO uint8_t *)data_reg) = *hqspi->pTxBuffPtr;
hqspi->pTxBuffPtr++;
hqspi->TxXferCount--;
}
else
{
/* No more data available for the transfer */
/* Disable the QSPI FIFO Threshold Interrupt */
__HAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_FT);
break;
}
}
}
else if(hqspi->State == HAL_QSPI_STATE_BUSY_INDIRECT_RX)
{
/* Receiving Process */
while(__HAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_FT) != RESET)
{
if (hqspi->RxXferCount > 0U)
{
/* Read the FIFO until the threshold is reached */
*hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg);
hqspi->pRxBuffPtr++;
hqspi->RxXferCount--;
}
else
{
/* All data have been received for the transfer */
/* Disable the QSPI FIFO Threshold Interrupt */
__HAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_FT);
break;
}
}
}
else
{
/* Nothing to do */
}
/* FIFO Threshold callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->FifoThresholdCallback(hqspi);
#else
HAL_QSPI_FifoThresholdCallback(hqspi);
#endif
}
/* QSPI Transfer Complete interrupt occurred -------------------------------*/
else if(((flag & QSPI_FLAG_TC) != 0U) && ((itsource & QSPI_IT_TC) != 0U))
{
/* Clear interrupt */
WRITE_REG(hqspi->Instance->FCR, QSPI_FLAG_TC);
/* Disable the QSPI FIFO Threshold, Transfer Error and Transfer complete Interrupts */
__HAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_TC | QSPI_IT_TE | QSPI_IT_FT);
/* Transfer complete callback */
if(hqspi->State == HAL_QSPI_STATE_BUSY_INDIRECT_TX)
{
if ((hqspi->Instance->CR & QUADSPI_CR_DMAEN) != 0U)
{
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Disable the DMA channel */
__HAL_DMA_DISABLE(hqspi->hdma);
}
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* TX Complete callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->TxCpltCallback(hqspi);
#else
HAL_QSPI_TxCpltCallback(hqspi);
#endif
}
else if(hqspi->State == HAL_QSPI_STATE_BUSY_INDIRECT_RX)
{
if ((hqspi->Instance->CR & QUADSPI_CR_DMAEN) != 0U)
{
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Disable the DMA channel */
__HAL_DMA_DISABLE(hqspi->hdma);
}
else
{
data_reg = &hqspi->Instance->DR;
while(READ_BIT(hqspi->Instance->SR, QUADSPI_SR_FLEVEL) != 0U)
{
if (hqspi->RxXferCount > 0U)
{
/* Read the last data received in the FIFO until it is empty */
*hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg);
hqspi->pRxBuffPtr++;
hqspi->RxXferCount--;
}
else
{
/* All data have been received for the transfer */
break;
}
}
}
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* RX Complete callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->RxCpltCallback(hqspi);
#else
HAL_QSPI_RxCpltCallback(hqspi);
#endif
}
else if(hqspi->State == HAL_QSPI_STATE_BUSY)
{
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* Command Complete callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->CmdCpltCallback(hqspi);
#else
HAL_QSPI_CmdCpltCallback(hqspi);
#endif
}
else if(hqspi->State == HAL_QSPI_STATE_ABORT)
{
/* Reset functional mode configuration to indirect write mode by default */
CLEAR_BIT(hqspi->Instance->CCR, QUADSPI_CCR_FMODE);
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
if (hqspi->ErrorCode == HAL_QSPI_ERROR_NONE)
{
/* Abort called by the user */
/* Abort Complete callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->AbortCpltCallback(hqspi);
#else
HAL_QSPI_AbortCpltCallback(hqspi);
#endif
}
else
{
/* Abort due to an error (eg : DMA error) */
/* Error callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->ErrorCallback(hqspi);
#else
HAL_QSPI_ErrorCallback(hqspi);
#endif
}
}
else
{
/* Nothing to do */
}
}
/* QSPI Status Match interrupt occurred ------------------------------------*/
else if(((flag & QSPI_FLAG_SM) != 0U) && ((itsource & QSPI_IT_SM) != 0U))
{
/* Clear interrupt */
WRITE_REG(hqspi->Instance->FCR, QSPI_FLAG_SM);
/* Check if the automatic poll mode stop is activated */
if(READ_BIT(hqspi->Instance->CR, QUADSPI_CR_APMS) != 0U)
{
/* Disable the QSPI Transfer Error and Status Match Interrupts */
__HAL_QSPI_DISABLE_IT(hqspi, (QSPI_IT_SM | QSPI_IT_TE));
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
}
/* Status match callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->StatusMatchCallback(hqspi);
#else
HAL_QSPI_StatusMatchCallback(hqspi);
#endif
}
/* QSPI Transfer Error interrupt occurred ----------------------------------*/
else if(((flag & QSPI_FLAG_TE) != 0U) && ((itsource & QSPI_IT_TE) != 0U))
{
/* Clear interrupt */
WRITE_REG(hqspi->Instance->FCR, QSPI_FLAG_TE);
/* Disable all the QSPI Interrupts */
__HAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_SM | QSPI_IT_TC | QSPI_IT_TE | QSPI_IT_FT);
/* Set error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_TRANSFER;
if ((hqspi->Instance->CR & QUADSPI_CR_DMAEN) != 0U)
{
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Disable the DMA channel */
hqspi->hdma->XferAbortCallback = QSPI_DMAAbortCplt;
if (HAL_DMA_Abort_IT(hqspi->hdma) != HAL_OK)
{
/* Set error code to DMA */
hqspi->ErrorCode |= HAL_QSPI_ERROR_DMA;
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* Error callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->ErrorCallback(hqspi);
#else
HAL_QSPI_ErrorCallback(hqspi);
#endif
}
}
else
{
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* Error callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->ErrorCallback(hqspi);
#else
HAL_QSPI_ErrorCallback(hqspi);
#endif
}
}
/* QSPI Timeout interrupt occurred -----------------------------------------*/
else if(((flag & QSPI_FLAG_TO) != 0U) && ((itsource & QSPI_IT_TO) != 0U))
{
/* Clear interrupt */
WRITE_REG(hqspi->Instance->FCR, QSPI_FLAG_TO);
/* Timeout callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->TimeOutCallback(hqspi);
#else
HAL_QSPI_TimeOutCallback(hqspi);
#endif
}
else
{
/* Nothing to do */
}
}
/**
* @brief Set the command configuration.
* @param hqspi : QSPI handle
* @param cmd : structure that contains the command configuration information
* @param Timeout : Timeout duration
* @note This function is used only in Indirect Read or Write Modes
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Command(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t Timeout)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the parameters */
assert_param(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode));
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
assert_param(IS_QSPI_INSTRUCTION(cmd->Instruction));
}
assert_param(IS_QSPI_ADDRESS_MODE(cmd->AddressMode));
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
assert_param(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize));
}
assert_param(IS_QSPI_ALTERNATE_BYTES_MODE(cmd->AlternateByteMode));
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
assert_param(IS_QSPI_ALTERNATE_BYTES_SIZE(cmd->AlternateBytesSize));
}
assert_param(IS_QSPI_DUMMY_CYCLES(cmd->DummyCycles));
assert_param(IS_QSPI_DATA_MODE(cmd->DataMode));
assert_param(IS_QSPI_DDR_MODE(cmd->DdrMode));
assert_param(IS_QSPI_DDR_HHC(cmd->DdrHoldHalfCycle));
assert_param(IS_QSPI_SIOO_MODE(cmd->SIOOMode));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_BUSY;
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, Timeout);
if (status == HAL_OK)
{
/* Call the configuration function */
QSPI_Config(hqspi, cmd, QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE);
if (cmd->DataMode == QSPI_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 = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TC, SET, tickstart, Timeout);
if (status == HAL_OK)
{
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
}
}
else
{
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
}
}
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/**
* @brief Set the command configuration in interrupt mode.
* @param hqspi : QSPI handle
* @param cmd : 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_QSPI_Command_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the parameters */
assert_param(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode));
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
assert_param(IS_QSPI_INSTRUCTION(cmd->Instruction));
}
assert_param(IS_QSPI_ADDRESS_MODE(cmd->AddressMode));
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
assert_param(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize));
}
assert_param(IS_QSPI_ALTERNATE_BYTES_MODE(cmd->AlternateByteMode));
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
assert_param(IS_QSPI_ALTERNATE_BYTES_SIZE(cmd->AlternateBytesSize));
}
assert_param(IS_QSPI_DUMMY_CYCLES(cmd->DummyCycles));
assert_param(IS_QSPI_DATA_MODE(cmd->DataMode));
assert_param(IS_QSPI_DDR_MODE(cmd->DdrMode));
assert_param(IS_QSPI_DDR_HHC(cmd->DdrHoldHalfCycle));
assert_param(IS_QSPI_SIOO_MODE(cmd->SIOOMode));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_BUSY;
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout);
if (status == HAL_OK)
{
if (cmd->DataMode == QSPI_DATA_NONE)
{
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TE | QSPI_FLAG_TC);
}
/* Call the configuration function */
QSPI_Config(hqspi, cmd, QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE);
if (cmd->DataMode == QSPI_DATA_NONE)
{
/* When there is no data phase, the transfer start as soon as the configuration is done
so activate TC and TE interrupts */
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI Transfer Error Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TE | QSPI_IT_TC);
}
else
{
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
/* Return function status */
return status;
}
/**
* @brief Transmit an amount of data in blocking mode.
* @param hqspi : QSPI 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_QSPI_Transmit(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tickstart = HAL_GetTick();
__IO uint32_t *data_reg = &hqspi->Instance->DR;
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_TX;
/* Configure counters and size of the handle */
hqspi->TxXferCount = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->TxXferSize = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->pTxBuffPtr = pData;
/* Configure QSPI: CCR register with functional as indirect write */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE);
while(hqspi->TxXferCount > 0U)
{
/* Wait until FT flag is set to send data */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_FT, SET, tickstart, Timeout);
if (status != HAL_OK)
{
break;
}
*((__IO uint8_t *)data_reg) = *hqspi->pTxBuffPtr;
hqspi->pTxBuffPtr++;
hqspi->TxXferCount--;
}
if (status == HAL_OK)
{
/* Wait until TC flag is set to go back in idle state */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TC, SET, tickstart, Timeout);
if (status == HAL_OK)
{
/* Clear Transfer Complete bit */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
}
}
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
}
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
return status;
}
/**
* @brief Receive an amount of data in blocking mode.
* @param hqspi : QSPI 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_QSPI_Receive(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tickstart = HAL_GetTick();
uint32_t addr_reg = READ_REG(hqspi->Instance->AR);
__IO uint32_t *data_reg = &hqspi->Instance->DR;
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_RX;
/* Configure counters and size of the handle */
hqspi->RxXferCount = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->RxXferSize = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->pRxBuffPtr = pData;
/* Configure QSPI: CCR register with functional as indirect read */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_READ);
/* Start the transfer by re-writing the address in AR register */
WRITE_REG(hqspi->Instance->AR, addr_reg);
while(hqspi->RxXferCount > 0U)
{
/* Wait until FT or TC flag is set to read received data */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, (QSPI_FLAG_FT | QSPI_FLAG_TC), SET, tickstart, Timeout);
if (status != HAL_OK)
{
break;
}
*hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg);
hqspi->pRxBuffPtr++;
hqspi->RxXferCount--;
}
if (status == HAL_OK)
{
/* Wait until TC flag is set to go back in idle state */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TC, SET, tickstart, Timeout);
if (status == HAL_OK)
{
/* Clear Transfer Complete bit */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
}
}
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_READY;
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
}
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
return status;
}
/**
* @brief Send an amount of data in non-blocking mode with interrupt.
* @param hqspi : QSPI handle
* @param pData : pointer to data buffer
* @note This function is used only in Indirect Write Mode
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Transmit_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_TX;
/* Configure counters and size of the handle */
hqspi->TxXferCount = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->TxXferSize = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->pTxBuffPtr = pData;
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TE | QSPI_FLAG_TC);
/* Configure QSPI: CCR register with functional as indirect write */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE);
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI transfer error, FIFO threshold and transfer complete Interrupts */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TE | QSPI_IT_FT | QSPI_IT_TC);
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
return status;
}
/**
* @brief Receive an amount of data in non-blocking mode with interrupt.
* @param hqspi : QSPI handle
* @param pData : pointer to data buffer
* @note This function is used only in Indirect Read Mode
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Receive_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t addr_reg = READ_REG(hqspi->Instance->AR);
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_RX;
/* Configure counters and size of the handle */
hqspi->RxXferCount = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->RxXferSize = READ_REG(hqspi->Instance->DLR) + 1U;
hqspi->pRxBuffPtr = pData;
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TE | QSPI_FLAG_TC);
/* Configure QSPI: CCR register with functional as indirect read */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_READ);
/* Start the transfer by re-writing the address in AR register */
WRITE_REG(hqspi->Instance->AR, addr_reg);
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI transfer error, FIFO threshold and transfer complete Interrupts */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TE | QSPI_IT_FT | QSPI_IT_TC);
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
return status;
}
/**
* @brief Send an amount of data in non-blocking mode with DMA.
* @param hqspi : QSPI 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_QSPI_Transmit_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t data_size = (READ_REG(hqspi->Instance->DLR) + 1U);
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
/* Clear the error code */
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Configure counters of the handle */
if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_BYTE)
{
hqspi->TxXferCount = data_size;
}
else if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_HALFWORD)
{
if (((data_size % 2U) != 0U) || ((hqspi->Init.FifoThreshold % 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 */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
else
{
hqspi->TxXferCount = (data_size >> 1U);
}
}
else if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_WORD)
{
if (((data_size % 4U) != 0U) || ((hqspi->Init.FifoThreshold % 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 */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
else
{
hqspi->TxXferCount = (data_size >> 2U);
}
}
else
{
/* Nothing to do */
}
if (status == HAL_OK)
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_TX;
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, (QSPI_FLAG_TE | QSPI_FLAG_TC));
/* Configure size and pointer of the handle */
hqspi->TxXferSize = hqspi->TxXferCount;
hqspi->pTxBuffPtr = pData;
/* Configure QSPI: CCR register with functional mode as indirect write */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE);
/* Set the QSPI DMA transfer complete callback */
hqspi->hdma->XferCpltCallback = QSPI_DMATxCplt;
/* Set the QSPI DMA Half transfer complete callback */
hqspi->hdma->XferHalfCpltCallback = QSPI_DMATxHalfCplt;
/* Set the DMA error callback */
hqspi->hdma->XferErrorCallback = QSPI_DMAError;
/* Clear the DMA abort callback */
hqspi->hdma->XferAbortCallback = NULL;
/* Configure the direction of the DMA */
hqspi->hdma->Init.Direction = DMA_MEMORY_TO_PERIPH;
MODIFY_REG(hqspi->hdma->Instance->CCR, DMA_CCR_DIR, hqspi->hdma->Init.Direction);
/* Enable the QSPI transmit DMA Channel */
if (HAL_DMA_Start_IT(hqspi->hdma, (uint32_t)pData, (uint32_t)&hqspi->Instance->DR, hqspi->TxXferSize) == HAL_OK)
{
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI transfer error Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TE);
/* Enable the DMA transfer by setting the DMAEN bit in the QSPI CR register */
SET_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
}
else
{
status = HAL_ERROR;
hqspi->ErrorCode |= HAL_QSPI_ERROR_DMA;
hqspi->State = HAL_QSPI_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
return status;
}
/**
* @brief Receive an amount of data in non-blocking mode with DMA.
* @param hqspi : QSPI 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_QSPI_Receive_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t addr_reg = READ_REG(hqspi->Instance->AR);
uint32_t data_size = (READ_REG(hqspi->Instance->DLR) + 1U);
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
/* Clear the error code */
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
if(pData != NULL )
{
/* Configure counters of the handle */
if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_BYTE)
{
hqspi->RxXferCount = data_size;
}
else if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_HALFWORD)
{
if (((data_size % 2U) != 0U) || ((hqspi->Init.FifoThreshold % 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 */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
else
{
hqspi->RxXferCount = (data_size >> 1U);
}
}
else if (hqspi->hdma->Init.PeriphDataAlignment == DMA_PDATAALIGN_WORD)
{
if (((data_size % 4U) != 0U) || ((hqspi->Init.FifoThreshold % 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 */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
else
{
hqspi->RxXferCount = (data_size >> 2U);
}
}
else
{
/* Nothing to do */
}
if (status == HAL_OK)
{
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_INDIRECT_RX;
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, (QSPI_FLAG_TE | QSPI_FLAG_TC));
/* Configure size and pointer of the handle */
hqspi->RxXferSize = hqspi->RxXferCount;
hqspi->pRxBuffPtr = pData;
/* Set the QSPI DMA transfer complete callback */
hqspi->hdma->XferCpltCallback = QSPI_DMARxCplt;
/* Set the QSPI DMA Half transfer complete callback */
hqspi->hdma->XferHalfCpltCallback = QSPI_DMARxHalfCplt;
/* Set the DMA error callback */
hqspi->hdma->XferErrorCallback = QSPI_DMAError;
/* Clear the DMA abort callback */
hqspi->hdma->XferAbortCallback = NULL;
/* Configure the direction of the DMA */
hqspi->hdma->Init.Direction = DMA_PERIPH_TO_MEMORY;
MODIFY_REG(hqspi->hdma->Instance->CCR, DMA_CCR_DIR, hqspi->hdma->Init.Direction);
/* Enable the DMA Channel */
if (HAL_DMA_Start_IT(hqspi->hdma, (uint32_t)&hqspi->Instance->DR, (uint32_t)pData, hqspi->RxXferSize) == HAL_OK)
{
/* Configure QSPI: CCR register with functional as indirect read */
MODIFY_REG(hqspi->Instance->CCR, QUADSPI_CCR_FMODE, QSPI_FUNCTIONAL_MODE_INDIRECT_READ);
/* Start the transfer by re-writing the address in AR register */
WRITE_REG(hqspi->Instance->AR, addr_reg);
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI transfer error Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TE);
/* Enable the DMA transfer by setting the DMAEN bit in the QSPI CR register */
SET_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
}
else
{
status = HAL_ERROR;
hqspi->ErrorCode |= HAL_QSPI_ERROR_DMA;
hqspi->State = HAL_QSPI_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
}
else
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_PARAM;
status = HAL_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
return status;
}
/**
* @brief Configure the QSPI Automatic Polling Mode in blocking mode.
* @param hqspi : QSPI handle
* @param cmd : structure that contains the command configuration information.
* @param cfg : 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_QSPI_AutoPolling(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg, uint32_t Timeout)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the parameters */
assert_param(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode));
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
assert_param(IS_QSPI_INSTRUCTION(cmd->Instruction));
}
assert_param(IS_QSPI_ADDRESS_MODE(cmd->AddressMode));
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
assert_param(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize));
}
assert_param(IS_QSPI_ALTERNATE_BYTES_MODE(cmd->AlternateByteMode));
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
assert_param(IS_QSPI_ALTERNATE_BYTES_SIZE(cmd->AlternateBytesSize));
}
assert_param(IS_QSPI_DUMMY_CYCLES(cmd->DummyCycles));
assert_param(IS_QSPI_DATA_MODE(cmd->DataMode));
assert_param(IS_QSPI_DDR_MODE(cmd->DdrMode));
assert_param(IS_QSPI_DDR_HHC(cmd->DdrHoldHalfCycle));
assert_param(IS_QSPI_SIOO_MODE(cmd->SIOOMode));
assert_param(IS_QSPI_INTERVAL(cfg->Interval));
assert_param(IS_QSPI_STATUS_BYTES_SIZE(cfg->StatusBytesSize));
assert_param(IS_QSPI_MATCH_MODE(cfg->MatchMode));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_AUTO_POLLING;
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, Timeout);
if (status == HAL_OK)
{
/* Configure QSPI: PSMAR register with the status match value */
WRITE_REG(hqspi->Instance->PSMAR, cfg->Match);
/* Configure QSPI: PSMKR register with the status mask value */
WRITE_REG(hqspi->Instance->PSMKR, cfg->Mask);
/* Configure QSPI: PIR register with the interval value */
WRITE_REG(hqspi->Instance->PIR, cfg->Interval);
/* Configure QSPI: CR register with Match mode and Automatic stop enabled
(otherwise there will be an infinite loop in blocking mode) */
MODIFY_REG(hqspi->Instance->CR, (QUADSPI_CR_PMM | QUADSPI_CR_APMS),
(cfg->MatchMode | QSPI_AUTOMATIC_STOP_ENABLE));
/* Call the configuration function */
cmd->NbData = cfg->StatusBytesSize;
QSPI_Config(hqspi, cmd, QSPI_FUNCTIONAL_MODE_AUTO_POLLING);
/* Wait until SM flag is set to go back in idle state */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_SM, SET, tickstart, Timeout);
if (status == HAL_OK)
{
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_SM);
/* Update state */
hqspi->State = HAL_QSPI_STATE_READY;
}
}
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/**
* @brief Configure the QSPI Automatic Polling Mode in non-blocking mode.
* @param hqspi : QSPI handle
* @param cmd : structure that contains the command configuration information.
* @param cfg : structure that contains the polling configuration information.
* @note This function is used only in Automatic Polling Mode
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_AutoPolling_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the parameters */
assert_param(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode));
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
assert_param(IS_QSPI_INSTRUCTION(cmd->Instruction));
}
assert_param(IS_QSPI_ADDRESS_MODE(cmd->AddressMode));
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
assert_param(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize));
}
assert_param(IS_QSPI_ALTERNATE_BYTES_MODE(cmd->AlternateByteMode));
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
assert_param(IS_QSPI_ALTERNATE_BYTES_SIZE(cmd->AlternateBytesSize));
}
assert_param(IS_QSPI_DUMMY_CYCLES(cmd->DummyCycles));
assert_param(IS_QSPI_DATA_MODE(cmd->DataMode));
assert_param(IS_QSPI_DDR_MODE(cmd->DdrMode));
assert_param(IS_QSPI_DDR_HHC(cmd->DdrHoldHalfCycle));
assert_param(IS_QSPI_SIOO_MODE(cmd->SIOOMode));
assert_param(IS_QSPI_INTERVAL(cfg->Interval));
assert_param(IS_QSPI_STATUS_BYTES_SIZE(cfg->StatusBytesSize));
assert_param(IS_QSPI_MATCH_MODE(cfg->MatchMode));
assert_param(IS_QSPI_AUTOMATIC_STOP(cfg->AutomaticStop));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_AUTO_POLLING;
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout);
if (status == HAL_OK)
{
/* Configure QSPI: PSMAR register with the status match value */
WRITE_REG(hqspi->Instance->PSMAR, cfg->Match);
/* Configure QSPI: PSMKR register with the status mask value */
WRITE_REG(hqspi->Instance->PSMKR, cfg->Mask);
/* Configure QSPI: PIR register with the interval value */
WRITE_REG(hqspi->Instance->PIR, cfg->Interval);
/* Configure QSPI: CR register with Match mode and Automatic stop mode */
MODIFY_REG(hqspi->Instance->CR, (QUADSPI_CR_PMM | QUADSPI_CR_APMS),
(cfg->MatchMode | cfg->AutomaticStop));
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TE | QSPI_FLAG_SM);
/* Call the configuration function */
cmd->NbData = cfg->StatusBytesSize;
QSPI_Config(hqspi, cmd, QSPI_FUNCTIONAL_MODE_AUTO_POLLING);
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Enable the QSPI Transfer Error and status match Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, (QSPI_IT_SM | QSPI_IT_TE));
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
}
else
{
status = HAL_BUSY;
/* Process unlocked */
__HAL_UNLOCK(hqspi);
}
/* Return function status */
return status;
}
/**
* @brief Configure the Memory Mapped mode.
* @param hqspi : QSPI handle
* @param cmd : structure that contains the command configuration information.
* @param cfg : structure that contains the memory mapped configuration information.
* @note This function is used only in Memory mapped Mode
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_MemoryMapped(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_MemoryMappedTypeDef *cfg)
{
HAL_StatusTypeDef status;
uint32_t tickstart = HAL_GetTick();
/* Check the parameters */
assert_param(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode));
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
assert_param(IS_QSPI_INSTRUCTION(cmd->Instruction));
}
assert_param(IS_QSPI_ADDRESS_MODE(cmd->AddressMode));
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
assert_param(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize));
}
assert_param(IS_QSPI_ALTERNATE_BYTES_MODE(cmd->AlternateByteMode));
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
assert_param(IS_QSPI_ALTERNATE_BYTES_SIZE(cmd->AlternateBytesSize));
}
assert_param(IS_QSPI_DUMMY_CYCLES(cmd->DummyCycles));
assert_param(IS_QSPI_DATA_MODE(cmd->DataMode));
assert_param(IS_QSPI_DDR_MODE(cmd->DdrMode));
assert_param(IS_QSPI_DDR_HHC(cmd->DdrHoldHalfCycle));
assert_param(IS_QSPI_SIOO_MODE(cmd->SIOOMode));
assert_param(IS_QSPI_TIMEOUT_ACTIVATION(cfg->TimeOutActivation));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
hqspi->ErrorCode = HAL_QSPI_ERROR_NONE;
/* Update state */
hqspi->State = HAL_QSPI_STATE_BUSY_MEM_MAPPED;
/* Wait till BUSY flag reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout);
if (status == HAL_OK)
{
/* Configure QSPI: CR register with timeout counter enable */
MODIFY_REG(hqspi->Instance->CR, QUADSPI_CR_TCEN, cfg->TimeOutActivation);
if (cfg->TimeOutActivation == QSPI_TIMEOUT_COUNTER_ENABLE)
{
assert_param(IS_QSPI_TIMEOUT_PERIOD(cfg->TimeOutPeriod));
/* Configure QSPI: LPTR register with the low-power timeout value */
WRITE_REG(hqspi->Instance->LPTR, cfg->TimeOutPeriod);
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TO);
/* Enable the QSPI TimeOut Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TO);
}
/* Call the configuration function */
QSPI_Config(hqspi, cmd, QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED);
}
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/**
* @brief Transfer Error callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_ErrorCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_ErrorCallback could be implemented in the user file
*/
}
/**
* @brief Abort completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_AbortCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_AbortCpltCallback could be implemented in the user file
*/
}
/**
* @brief Command completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_CmdCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_CmdCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Tx Transfer completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_TxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Half Transfer completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_RxHalfCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_RxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief Tx Half Transfer completed callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_TxHalfCpltCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_QSPI_TxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief FIFO Threshold callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_FifoThresholdCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_FIFOThresholdCallback could be implemented in the user file
*/
}
/**
* @brief Status Match callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_StatusMatchCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_StatusMatchCallback could be implemented in the user file
*/
}
/**
* @brief Timeout callback.
* @param hqspi : QSPI handle
* @retval None
*/
__weak void HAL_QSPI_TimeOutCallback(QSPI_HandleTypeDef *hqspi)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hqspi);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_QSPI_TimeOutCallback could be implemented in the user file
*/
}
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User QSPI Callback
* To be used instead of the weak (surcharged) predefined callback
* @param hqspi : QSPI handle
* @param CallbackId : ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_QSPI_ERROR_CB_ID QSPI Error Callback ID
* @arg @ref HAL_QSPI_ABORT_CB_ID QSPI Abort Callback ID
* @arg @ref HAL_QSPI_FIFO_THRESHOLD_CB_ID QSPI FIFO Threshold Callback ID
* @arg @ref HAL_QSPI_CMD_CPLT_CB_ID QSPI Command Complete Callback ID
* @arg @ref HAL_QSPI_RX_CPLT_CB_ID QSPI Rx Complete Callback ID
* @arg @ref HAL_QSPI_TX_CPLT_CB_ID QSPI Tx Complete Callback ID
* @arg @ref HAL_QSPI_RX_HALF_CPLT_CB_ID QSPI Rx Half Complete Callback ID
* @arg @ref HAL_QSPI_TX_HALF_CPLT_CB_ID QSPI Tx Half Complete Callback ID
* @arg @ref HAL_QSPI_STATUS_MATCH_CB_ID QSPI Status Match Callback ID
* @arg @ref HAL_QSPI_TIMEOUT_CB_ID QSPI Timeout Callback ID
* @arg @ref HAL_QSPI_MSP_INIT_CB_ID QSPI MspInit callback ID
* @arg @ref HAL_QSPI_MSP_DEINIT_CB_ID QSPI MspDeInit callback ID
* @param pCallback : pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_QSPI_RegisterCallback (QSPI_HandleTypeDef *hqspi, HAL_QSPI_CallbackIDTypeDef CallbackId, pQSPI_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if(pCallback == NULL)
{
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
switch (CallbackId)
{
case HAL_QSPI_ERROR_CB_ID :
hqspi->ErrorCallback = pCallback;
break;
case HAL_QSPI_ABORT_CB_ID :
hqspi->AbortCpltCallback = pCallback;
break;
case HAL_QSPI_FIFO_THRESHOLD_CB_ID :
hqspi->FifoThresholdCallback = pCallback;
break;
case HAL_QSPI_CMD_CPLT_CB_ID :
hqspi->CmdCpltCallback = pCallback;
break;
case HAL_QSPI_RX_CPLT_CB_ID :
hqspi->RxCpltCallback = pCallback;
break;
case HAL_QSPI_TX_CPLT_CB_ID :
hqspi->TxCpltCallback = pCallback;
break;
case HAL_QSPI_RX_HALF_CPLT_CB_ID :
hqspi->RxHalfCpltCallback = pCallback;
break;
case HAL_QSPI_TX_HALF_CPLT_CB_ID :
hqspi->TxHalfCpltCallback = pCallback;
break;
case HAL_QSPI_STATUS_MATCH_CB_ID :
hqspi->StatusMatchCallback = pCallback;
break;
case HAL_QSPI_TIMEOUT_CB_ID :
hqspi->TimeOutCallback = pCallback;
break;
case HAL_QSPI_MSP_INIT_CB_ID :
hqspi->MspInitCallback = pCallback;
break;
case HAL_QSPI_MSP_DEINIT_CB_ID :
hqspi->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hqspi->State == HAL_QSPI_STATE_RESET)
{
switch (CallbackId)
{
case HAL_QSPI_MSP_INIT_CB_ID :
hqspi->MspInitCallback = pCallback;
break;
case HAL_QSPI_MSP_DEINIT_CB_ID :
hqspi->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hqspi);
return status;
}
/**
* @brief Unregister a User QSPI Callback
* QSPI Callback is redirected to the weak (surcharged) predefined callback
* @param hqspi : QSPI handle
* @param CallbackId : ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_QSPI_ERROR_CB_ID QSPI Error Callback ID
* @arg @ref HAL_QSPI_ABORT_CB_ID QSPI Abort Callback ID
* @arg @ref HAL_QSPI_FIFO_THRESHOLD_CB_ID QSPI FIFO Threshold Callback ID
* @arg @ref HAL_QSPI_CMD_CPLT_CB_ID QSPI Command Complete Callback ID
* @arg @ref HAL_QSPI_RX_CPLT_CB_ID QSPI Rx Complete Callback ID
* @arg @ref HAL_QSPI_TX_CPLT_CB_ID QSPI Tx Complete Callback ID
* @arg @ref HAL_QSPI_RX_HALF_CPLT_CB_ID QSPI Rx Half Complete Callback ID
* @arg @ref HAL_QSPI_TX_HALF_CPLT_CB_ID QSPI Tx Half Complete Callback ID
* @arg @ref HAL_QSPI_STATUS_MATCH_CB_ID QSPI Status Match Callback ID
* @arg @ref HAL_QSPI_TIMEOUT_CB_ID QSPI Timeout Callback ID
* @arg @ref HAL_QSPI_MSP_INIT_CB_ID QSPI MspInit callback ID
* @arg @ref HAL_QSPI_MSP_DEINIT_CB_ID QSPI MspDeInit callback ID
* @retval status
*/
HAL_StatusTypeDef HAL_QSPI_UnRegisterCallback (QSPI_HandleTypeDef *hqspi, HAL_QSPI_CallbackIDTypeDef CallbackId)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
switch (CallbackId)
{
case HAL_QSPI_ERROR_CB_ID :
hqspi->ErrorCallback = HAL_QSPI_ErrorCallback;
break;
case HAL_QSPI_ABORT_CB_ID :
hqspi->AbortCpltCallback = HAL_QSPI_AbortCpltCallback;
break;
case HAL_QSPI_FIFO_THRESHOLD_CB_ID :
hqspi->FifoThresholdCallback = HAL_QSPI_FifoThresholdCallback;
break;
case HAL_QSPI_CMD_CPLT_CB_ID :
hqspi->CmdCpltCallback = HAL_QSPI_CmdCpltCallback;
break;
case HAL_QSPI_RX_CPLT_CB_ID :
hqspi->RxCpltCallback = HAL_QSPI_RxCpltCallback;
break;
case HAL_QSPI_TX_CPLT_CB_ID :
hqspi->TxCpltCallback = HAL_QSPI_TxCpltCallback;
break;
case HAL_QSPI_RX_HALF_CPLT_CB_ID :
hqspi->RxHalfCpltCallback = HAL_QSPI_RxHalfCpltCallback;
break;
case HAL_QSPI_TX_HALF_CPLT_CB_ID :
hqspi->TxHalfCpltCallback = HAL_QSPI_TxHalfCpltCallback;
break;
case HAL_QSPI_STATUS_MATCH_CB_ID :
hqspi->StatusMatchCallback = HAL_QSPI_StatusMatchCallback;
break;
case HAL_QSPI_TIMEOUT_CB_ID :
hqspi->TimeOutCallback = HAL_QSPI_TimeOutCallback;
break;
case HAL_QSPI_MSP_INIT_CB_ID :
hqspi->MspInitCallback = HAL_QSPI_MspInit;
break;
case HAL_QSPI_MSP_DEINIT_CB_ID :
hqspi->MspDeInitCallback = HAL_QSPI_MspDeInit;
break;
default :
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hqspi->State == HAL_QSPI_STATE_RESET)
{
switch (CallbackId)
{
case HAL_QSPI_MSP_INIT_CB_ID :
hqspi->MspInitCallback = HAL_QSPI_MspInit;
break;
case HAL_QSPI_MSP_DEINIT_CB_ID :
hqspi->MspDeInitCallback = HAL_QSPI_MspDeInit;
break;
default :
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hqspi->ErrorCode |= HAL_QSPI_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hqspi);
return status;
}
#endif
/**
* @}
*/
/** @defgroup QSPI_Exported_Functions_Group3 Peripheral Control and State functions
* @brief QSPI 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.
@endverbatim
* @{
*/
/**
* @brief Return the QSPI handle state.
* @param hqspi : QSPI handle
* @retval HAL state
*/
HAL_QSPI_StateTypeDef HAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi)
{
/* Return QSPI handle state */
return hqspi->State;
}
/**
* @brief Return the QSPI error code.
* @param hqspi : QSPI handle
* @retval QSPI Error Code
*/
uint32_t HAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi)
{
return hqspi->ErrorCode;
}
/**
* @brief Abort the current transmission.
* @param hqspi : QSPI handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Abort(QSPI_HandleTypeDef *hqspi)
{
HAL_StatusTypeDef status = HAL_OK;
uint32_t tickstart = HAL_GetTick();
/* Check if the state is in one of the busy states */
if (((uint32_t)hqspi->State & 0x2U) != 0U)
{
/* Process unlocked */
__HAL_UNLOCK(hqspi);
if ((hqspi->Instance->CR & QUADSPI_CR_DMAEN) != 0U)
{
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Abort DMA channel */
status = HAL_DMA_Abort(hqspi->hdma);
if(status != HAL_OK)
{
hqspi->ErrorCode |= HAL_QSPI_ERROR_DMA;
}
}
/* Configure QSPI: CR register with Abort request */
SET_BIT(hqspi->Instance->CR, QUADSPI_CR_ABORT);
/* Wait until TC flag is set to go back in idle state */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TC, SET, tickstart, hqspi->Timeout);
if (status == HAL_OK)
{
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
/* Wait until BUSY flag is reset */
status = QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout);
}
if (status == HAL_OK)
{
/* Reset functional mode configuration to indirect write mode by default */
CLEAR_BIT(hqspi->Instance->CCR, QUADSPI_CCR_FMODE);
/* Update state */
hqspi->State = HAL_QSPI_STATE_READY;
}
}
return status;
}
/**
* @brief Abort the current transmission (non-blocking function)
* @param hqspi : QSPI handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_Abort_IT(QSPI_HandleTypeDef *hqspi)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check if the state is in one of the busy states */
if (((uint32_t)hqspi->State & 0x2U) != 0U)
{
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Update QSPI state */
hqspi->State = HAL_QSPI_STATE_ABORT;
/* Disable all interrupts */
__HAL_QSPI_DISABLE_IT(hqspi, (QSPI_IT_TO | QSPI_IT_SM | QSPI_IT_FT | QSPI_IT_TC | QSPI_IT_TE));
if ((hqspi->Instance->CR & QUADSPI_CR_DMAEN) != 0U)
{
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Abort DMA channel */
hqspi->hdma->XferAbortCallback = QSPI_DMAAbortCplt;
if (HAL_DMA_Abort_IT(hqspi->hdma) != HAL_OK)
{
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* Abort Complete callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->AbortCpltCallback(hqspi);
#else
HAL_QSPI_AbortCpltCallback(hqspi);
#endif
}
}
else
{
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
/* Enable the QSPI Transfer Complete Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TC);
/* Configure QSPI: CR register with Abort request */
SET_BIT(hqspi->Instance->CR, QUADSPI_CR_ABORT);
}
}
return status;
}
/** @brief Set QSPI timeout.
* @param hqspi : QSPI handle.
* @param Timeout : Timeout for the QSPI memory access.
* @retval None
*/
void HAL_QSPI_SetTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Timeout)
{
hqspi->Timeout = Timeout;
}
/** @brief Set QSPI Fifo threshold.
* @param hqspi : QSPI handle.
* @param Threshold : Threshold of the Fifo (value between 1 and 16).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_SetFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
/* Synchronize init structure with new FIFO threshold value */
hqspi->Init.FifoThreshold = Threshold;
/* Configure QSPI FIFO Threshold */
MODIFY_REG(hqspi->Instance->CR, QUADSPI_CR_FTHRES,
((hqspi->Init.FifoThreshold - 1U) << QUADSPI_CR_FTHRES_Pos));
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/** @brief Get QSPI Fifo threshold.
* @param hqspi : QSPI handle.
* @retval Fifo threshold (value between 1 and 16)
*/
uint32_t HAL_QSPI_GetFifoThreshold(QSPI_HandleTypeDef *hqspi)
{
return ((READ_BIT(hqspi->Instance->CR, QUADSPI_CR_FTHRES) >> QUADSPI_CR_FTHRES_Pos) + 1U);
}
/** @brief Set FlashID.
* @param hqspi : QSPI handle.
* @param FlashID : Index of the flash memory to be accessed.
* This parameter can be a value of @ref QSPI_Flash_Select.
* @note The FlashID is ignored when dual flash mode is enabled.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_QSPI_SetFlashID(QSPI_HandleTypeDef *hqspi, uint32_t FlashID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameter */
assert_param(IS_QSPI_FLASH_ID(FlashID));
/* Process locked */
__HAL_LOCK(hqspi);
if(hqspi->State == HAL_QSPI_STATE_READY)
{
/* Synchronize init structure with new FlashID value */
hqspi->Init.FlashID = FlashID;
/* Configure QSPI FlashID */
MODIFY_REG(hqspi->Instance->CR, QUADSPI_CR_FSEL, FlashID);
}
else
{
status = HAL_BUSY;
}
/* Process unlocked */
__HAL_UNLOCK(hqspi);
/* Return function status */
return status;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup QSPI_Private_Functions QSPI Private Functions
* @{
*/
/**
* @brief DMA QSPI receive process complete callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMARxCplt(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = (QSPI_HandleTypeDef*)(hdma->Parent);
hqspi->RxXferCount = 0U;
/* Enable the QSPI transfer complete Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TC);
}
/**
* @brief DMA QSPI transmit process complete callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMATxCplt(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = (QSPI_HandleTypeDef*)(hdma->Parent);
hqspi->TxXferCount = 0U;
/* Enable the QSPI transfer complete Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TC);
}
/**
* @brief DMA QSPI receive process half complete callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = (QSPI_HandleTypeDef*)(hdma->Parent);
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->RxHalfCpltCallback(hqspi);
#else
HAL_QSPI_RxHalfCpltCallback(hqspi);
#endif
}
/**
* @brief DMA QSPI transmit process half complete callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = (QSPI_HandleTypeDef*)(hdma->Parent);
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->TxHalfCpltCallback(hqspi);
#else
HAL_QSPI_TxHalfCpltCallback(hqspi);
#endif
}
/**
* @brief DMA QSPI communication error callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMAError(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = ( QSPI_HandleTypeDef* )(hdma->Parent);
hqspi->RxXferCount = 0U;
hqspi->TxXferCount = 0U;
hqspi->ErrorCode |= HAL_QSPI_ERROR_DMA;
/* Disable the DMA transfer by clearing the DMAEN bit in the QSPI CR register */
CLEAR_BIT(hqspi->Instance->CR, QUADSPI_CR_DMAEN);
/* Abort the QSPI */
(void)HAL_QSPI_Abort_IT(hqspi);
}
/**
* @brief DMA QSPI abort complete callback.
* @param hdma : DMA handle
* @retval None
*/
static void QSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma)
{
QSPI_HandleTypeDef* hqspi = ( QSPI_HandleTypeDef* )(hdma->Parent);
hqspi->RxXferCount = 0U;
hqspi->TxXferCount = 0U;
if(hqspi->State == HAL_QSPI_STATE_ABORT)
{
/* DMA Abort called by QSPI abort */
/* Clear interrupt */
__HAL_QSPI_CLEAR_FLAG(hqspi, QSPI_FLAG_TC);
/* Enable the QSPI Transfer Complete Interrupt */
__HAL_QSPI_ENABLE_IT(hqspi, QSPI_IT_TC);
/* Configure QSPI: CR register with Abort request */
SET_BIT(hqspi->Instance->CR, QUADSPI_CR_ABORT);
}
else
{
/* DMA Abort called due to a transfer error interrupt */
/* Change state of QSPI */
hqspi->State = HAL_QSPI_STATE_READY;
/* Error callback */
#if (USE_HAL_QSPI_REGISTER_CALLBACKS == 1)
hqspi->ErrorCallback(hqspi);
#else
HAL_QSPI_ErrorCallback(hqspi);
#endif
}
}
/**
* @brief Wait for a flag state until timeout.
* @param hqspi : QSPI handle
* @param Flag : Flag checked
* @param State : Value of the flag expected
* @param Tickstart : Tick start value
* @param Timeout : Duration of the timeout
* @retval HAL status
*/
static HAL_StatusTypeDef QSPI_WaitFlagStateUntilTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Flag,
FlagStatus State, uint32_t Tickstart, uint32_t Timeout)
{
/* Wait until flag is in expected state */
while((__HAL_QSPI_GET_FLAG(hqspi, Flag)) != State)
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if(((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U))
{
hqspi->State = HAL_QSPI_STATE_ERROR;
hqspi->ErrorCode |= HAL_QSPI_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
}
return HAL_OK;
}
/**
* @brief Configure the communication registers.
* @param hqspi : QSPI handle
* @param cmd : structure that contains the command configuration information
* @param FunctionalMode : functional mode to configured
* This parameter can be one of the following values:
* @arg QSPI_FUNCTIONAL_MODE_INDIRECT_WRITE: Indirect write mode
* @arg QSPI_FUNCTIONAL_MODE_INDIRECT_READ: Indirect read mode
* @arg QSPI_FUNCTIONAL_MODE_AUTO_POLLING: Automatic polling mode
* @arg QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED: Memory-mapped mode
* @retval None
*/
static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t FunctionalMode)
{
assert_param(IS_QSPI_FUNCTIONAL_MODE(FunctionalMode));
if ((cmd->DataMode != QSPI_DATA_NONE) && (FunctionalMode != QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED))
{
/* Configure QSPI: DLR register with the number of data to read or write */
WRITE_REG(hqspi->Instance->DLR, (cmd->NbData - 1U));
}
if (cmd->InstructionMode != QSPI_INSTRUCTION_NONE)
{
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
/* Configure QSPI: ABR register with alternate bytes value */
WRITE_REG(hqspi->Instance->ABR, cmd->AlternateBytes);
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
/*---- Command with instruction, address and alternate bytes ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateBytesSize | cmd->AlternateByteMode |
cmd->AddressSize | cmd->AddressMode | cmd->InstructionMode |
cmd->Instruction | FunctionalMode));
if (FunctionalMode != QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)
{
/* Configure QSPI: AR register with address value */
WRITE_REG(hqspi->Instance->AR, cmd->Address);
}
}
else
{
/*---- Command with instruction and alternate bytes ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateBytesSize | cmd->AlternateByteMode |
cmd->AddressMode | cmd->InstructionMode |
cmd->Instruction | FunctionalMode));
}
}
else
{
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
/*---- Command with instruction and address ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateByteMode | cmd->AddressSize | cmd->AddressMode |
cmd->InstructionMode | cmd->Instruction | FunctionalMode));
if (FunctionalMode != QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)
{
/* Configure QSPI: AR register with address value */
WRITE_REG(hqspi->Instance->AR, cmd->Address);
}
}
else
{
/*---- Command with only instruction ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateByteMode | cmd->AddressMode |
cmd->InstructionMode | cmd->Instruction | FunctionalMode));
}
}
}
else
{
if (cmd->AlternateByteMode != QSPI_ALTERNATE_BYTES_NONE)
{
/* Configure QSPI: ABR register with alternate bytes value */
WRITE_REG(hqspi->Instance->ABR, cmd->AlternateBytes);
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
/*---- Command with address and alternate bytes ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateBytesSize | cmd->AlternateByteMode |
cmd->AddressSize | cmd->AddressMode |
cmd->InstructionMode | FunctionalMode));
if (FunctionalMode != QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)
{
/* Configure QSPI: AR register with address value */
WRITE_REG(hqspi->Instance->AR, cmd->Address);
}
}
else
{
/*---- Command with only alternate bytes ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateBytesSize | cmd->AlternateByteMode |
cmd->AddressMode | cmd->InstructionMode | FunctionalMode));
}
}
else
{
if (cmd->AddressMode != QSPI_ADDRESS_NONE)
{
/*---- Command with only address ----*/
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateByteMode | cmd->AddressSize |
cmd->AddressMode | cmd->InstructionMode | FunctionalMode));
if (FunctionalMode != QSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)
{
/* Configure QSPI: AR register with address value */
WRITE_REG(hqspi->Instance->AR, cmd->Address);
}
}
else
{
/*---- Command with only data phase ----*/
if (cmd->DataMode != QSPI_DATA_NONE)
{
/* Configure QSPI: CCR register with all communications parameters */
WRITE_REG(hqspi->Instance->CCR, (cmd->DdrMode | cmd->DdrHoldHalfCycle | cmd->SIOOMode |
cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) |
cmd->AlternateByteMode | cmd->AddressMode |
cmd->InstructionMode | FunctionalMode));
}
}
}
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_QSPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
#endif /* defined(QUADSPI) */
| 90,765 |
C
| 31.6379 | 154 | 0.616956 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_cordic.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_cordic.c
* @author MCD Application Team
* @brief CORDIC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_cordic.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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 */
| 2,525 |
C
| 23.524272 | 84 | 0.473663 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_adc_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_adc_ex.c
* @author MCD Application Team
* @brief This file provides firmware functions to manage the following
* functionalities of the Analog to Digital Converter (ADC)
* peripheral:
* + Peripheral Control functions
* Other functions (generic functions) are available in file
* "stm32g4xx_hal_adc.c".
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
[..]
(@) Sections "ADC peripheral features" and "How to use this driver" are
available in file of generic functions "stm32g4xx_hal_adc.c".
[..]
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup ADCEx ADCEx
* @brief ADC Extended HAL module driver
* @{
*/
#ifdef HAL_ADC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ADCEx_Private_Constants ADC Extended Private Constants
* @{
*/
#define ADC_JSQR_FIELDS ((ADC_JSQR_JL | ADC_JSQR_JEXTSEL | ADC_JSQR_JEXTEN |\
ADC_JSQR_JSQ1 | ADC_JSQR_JSQ2 |\
ADC_JSQR_JSQ3 | ADC_JSQR_JSQ4 )) /*!< ADC_JSQR fields of parameters that can be updated anytime once the ADC is enabled */
/* Fixed timeout value for ADC calibration. */
/* Values defined to be higher than worst cases: low clock frequency, */
/* maximum prescalers. */
/* Ex of profile low frequency : f_ADC at f_CPU/3968 (minimum value */
/* considering both possible ADC clocking scheme: */
/* - ADC clock from synchronous clock with AHB prescaler 512, */
/* ADC prescaler 4. */
/* Ratio max = 512 *4 = 2048 */
/* - ADC clock from asynchronous clock (PLLP) with prescaler 256. */
/* Highest CPU clock PLL (PLLR). */
/* Ratio max = PLLRmax /PPLPmin * 256 = (VCO/2) / (VCO/31) * 256 */
/* = 3968 ) */
/* Calibration_time MAX = 81 / f_ADC */
/* = 81 / (f_CPU/3938) = 318978 CPU cycles */
#define ADC_CALIBRATION_TIMEOUT (318978UL) /*!< ADC calibration time-out value (unit: CPU cycles) */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup ADCEx_Exported_Functions ADC Extended Exported Functions
* @{
*/
/** @defgroup ADCEx_Exported_Functions_Group1 Extended Input and Output operation functions
* @brief Extended IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Perform the ADC self-calibration for single or differential ending.
(+) Get calibration factors for single or differential ending.
(+) Set calibration factors for single or differential ending.
(+) Start conversion of ADC group injected.
(+) Stop conversion of ADC group injected.
(+) Poll for conversion complete on ADC group injected.
(+) Get result of ADC group injected channel conversion.
(+) Start conversion of ADC group injected and enable interruptions.
(+) Stop conversion of ADC group injected and disable interruptions.
(+) When multimode feature is available, start multimode and enable DMA transfer.
(+) Stop multimode and disable ADC DMA transfer.
(+) Get result of multimode conversion.
@endverbatim
* @{
*/
/**
* @brief Perform an ADC automatic self-calibration
* Calibration prerequisite: ADC must be disabled (execute this
* function before HAL_ADC_Start() or after HAL_ADC_Stop() ).
* @param hadc ADC handle
* @param SingleDiff Selection of single-ended or differential input
* This parameter can be one of the following values:
* @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended
* @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef *hadc, uint32_t SingleDiff)
{
HAL_StatusTypeDef tmp_hal_status;
__IO uint32_t wait_loop_index = 0UL;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff));
/* Process locked */
__HAL_LOCK(hadc);
/* Calibration prerequisite: ADC must be disabled. */
/* Disable the ADC (if not already disabled) */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_BUSY_INTERNAL);
/* Start ADC calibration in mode single-ended or differential */
LL_ADC_StartCalibration(hadc->Instance, SingleDiff);
/* Wait for calibration completion */
while (LL_ADC_IsCalibrationOnGoing(hadc->Instance) != 0UL)
{
wait_loop_index++;
if (wait_loop_index >= ADC_CALIBRATION_TIMEOUT)
{
/* Update ADC state machine to error */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_BUSY_INTERNAL,
HAL_ADC_STATE_ERROR_INTERNAL);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
}
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_BUSY_INTERNAL,
HAL_ADC_STATE_READY);
}
else
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Note: No need to update variable "tmp_hal_status" here: already set */
/* to state "HAL_ERROR" by function disabling the ADC. */
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Get the calibration factor.
* @param hadc ADC handle.
* @param SingleDiff This parameter can be only:
* @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended
* @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended
* @retval Calibration value.
*/
uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff)
{
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff));
/* Return the selected ADC calibration value */
return LL_ADC_GetCalibrationFactor(hadc->Instance, SingleDiff);
}
/**
* @brief Set the calibration factor to overwrite automatic conversion result.
* ADC must be enabled and no conversion is ongoing.
* @param hadc ADC handle
* @param SingleDiff This parameter can be only:
* @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended
* @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended
* @param CalibrationFactor Calibration factor (coded on 7 bits maximum)
* @retval HAL state
*/
HAL_StatusTypeDef HAL_ADCEx_Calibration_SetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff,
uint32_t CalibrationFactor)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff));
assert_param(IS_ADC_CALFACT(CalibrationFactor));
/* Process locked */
__HAL_LOCK(hadc);
/* Verification of hardware constraints before modifying the calibration */
/* factors register: ADC must be enabled, no conversion on going. */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
&& (tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
/* Set the selected ADC calibration value */
LL_ADC_SetCalibrationFactor(hadc->Instance, SingleDiff, CalibrationFactor);
}
else
{
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
/* Update ADC error code */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
/* Update ADC state machine to error */
tmp_hal_status = HAL_ERROR;
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Enable ADC, start conversion of injected group.
* @note Interruptions enabled in this function: None.
* @note Case of multimode enabled when multimode feature is available:
* HAL_ADCEx_InjectedStart() API must be called for ADC slave first,
* then for ADC master.
* For ADC slave, ADC is enabled only (conversion is not started).
* For ADC master, ADC is enabled and multimode conversion is started.
* @param hadc ADC handle.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tmp_config_injected_queue;
#if defined(ADC_MULTIMODE_SUPPORT)
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL)
{
return HAL_BUSY;
}
else
{
/* In case of software trigger detection enabled, JQDIS must be set
(which can be done only if ADSTART and JADSTART are both cleared).
If JQDIS is not set at that point, returns an error
- since software trigger detection is disabled. User needs to
resort to HAL_ADCEx_DisableInjectedQueue() API to set JQDIS.
- or (if JQDIS is intentionally reset) since JEXTEN = 0 which means
the queue is empty */
tmp_config_injected_queue = READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS);
if ((READ_BIT(hadc->Instance->JSQR, ADC_JSQR_JEXTEN) == 0UL)
&& (tmp_config_injected_queue == 0UL)
)
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hadc);
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
/* Start conversion if ADC is effectively enabled */
if (tmp_hal_status == HAL_OK)
{
/* Check if a regular conversion is ongoing */
if ((hadc->State & HAL_ADC_STATE_REG_BUSY) != 0UL)
{
/* Reset ADC error code field related to injected conversions only */
CLEAR_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
}
else
{
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
}
/* Set ADC state */
/* - Clear state bitfield related to injected group conversion results */
/* - Set state bitfield related to injected operation */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC,
HAL_ADC_STATE_INJ_BUSY);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
- if ADC instance is master or if multimode feature is not available
- if multimode setting is disabled (ADC instance slave in independent mode) */
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
)
{
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#endif
/* Clear ADC group injected group conversion flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* Enable conversion of injected group, if automatic injected conversion */
/* is disabled. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Case of multimode enabled (when multimode feature is available): */
/* if ADC is slave, */
/* - ADC is enabled only (conversion is not started), */
/* - if multimode only concerns regular conversion, ADC is enabled */
/* and conversion is started. */
/* If ADC is master or independent, */
/* - ADC is enabled and conversion is started. */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
)
{
/* ADC instance is not a multimode slave instance with multimode injected conversions enabled */
if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT)
{
LL_ADC_INJ_StartConversion(hadc->Instance);
}
}
else
{
/* ADC instance is not a multimode slave instance with multimode injected conversions enabled */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#else
if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT)
{
/* Start ADC group injected conversion */
LL_ADC_INJ_StartConversion(hadc->Instance);
}
#endif
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
/* Return function status */
return tmp_hal_status;
}
}
/**
* @brief Stop conversion of injected channels. Disable ADC peripheral if
* no regular conversion is on going.
* @note If ADC must be disabled and if conversion is on going on
* regular group, function HAL_ADC_Stop must be used to stop both
* injected and regular groups, and disable the ADC.
* @note If injected group mode auto-injection is enabled,
* function HAL_ADC_Stop must be used.
* @note In case of multimode enabled (when multimode feature is available),
* HAL_ADCEx_InjectedStop() must be called for ADC master first, then for ADC slave.
* For ADC master, conversion is stopped and ADC is disabled.
* For ADC slave, ADC is disabled only (conversion stop of ADC master
* has already stopped conversion of ADC slave).
* @param hadc ADC handle.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential conversion on going on injected group only. */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_INJECTED_GROUP);
/* Disable ADC peripheral if injected conversions are effectively stopped */
/* and if no conversion on regular group is on-going */
if (tmp_hal_status == HAL_OK)
{
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* 2. Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Conversion on injected group is stopped, but ADC not disabled since */
/* conversion on regular group is still running. */
else
{
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Wait for injected group conversion to be completed.
* @param hadc ADC handle
* @param Timeout Timeout value in millisecond.
* @note Depending on hadc->Init.EOCSelection, JEOS or JEOC is
* checked and cleared depending on AUTDLY bit status.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
{
uint32_t tickstart;
uint32_t tmp_Flag_End;
uint32_t tmp_adc_inj_is_trigger_source_sw_start;
uint32_t tmp_adc_reg_is_trigger_source_sw_start;
uint32_t tmp_cfgr;
#if defined(ADC_MULTIMODE_SUPPORT)
const ADC_TypeDef *tmpADC_Master;
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* If end of sequence selected */
if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
{
tmp_Flag_End = ADC_FLAG_JEOS;
}
else /* end of conversion selected */
{
tmp_Flag_End = ADC_FLAG_JEOC;
}
/* Get timeout */
tickstart = HAL_GetTick();
/* Wait until End of Conversion or Sequence flag is raised */
while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
{
/* Check if timeout is disabled (set to infinite wait) */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
{
/* New check to avoid false timeout detection in case of preemption */
if ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
{
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_TIMEOUT;
}
}
}
}
/* Retrieve ADC configuration */
tmp_adc_inj_is_trigger_source_sw_start = LL_ADC_INJ_IsTriggerSourceSWStart(hadc->Instance);
tmp_adc_reg_is_trigger_source_sw_start = LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance);
/* Get relevant register CFGR in ADC instance of ADC master or slave */
/* in function of multimode state (for devices with multimode */
/* available). */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
)
{
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
}
else
{
tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
}
#else
tmp_cfgr = READ_REG(hadc->Instance->CFGR);
#endif
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
/* Determine whether any further conversion upcoming on group injected */
/* by external trigger or by automatic injected conversion */
/* from group regular. */
if ((tmp_adc_inj_is_trigger_source_sw_start != 0UL) ||
((READ_BIT(tmp_cfgr, ADC_CFGR_JAUTO) == 0UL) &&
((tmp_adc_reg_is_trigger_source_sw_start != 0UL) &&
(READ_BIT(tmp_cfgr, ADC_CFGR_CONT) == 0UL))))
{
/* Check whether end of sequence is reached */
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS))
{
/* Particular case if injected contexts queue is enabled: */
/* when the last context has been fully processed, JSQR is reset */
/* by the hardware. Even if no injected conversion is planned to come */
/* (queue empty, triggers are ignored), it can start again */
/* immediately after setting a new context (JADSTART is still set). */
/* Therefore, state of HAL ADC injected group is kept to busy. */
if (READ_BIT(tmp_cfgr, ADC_CFGR_JQM) == 0UL)
{
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
if ((hadc->State & HAL_ADC_STATE_REG_BUSY) == 0UL)
{
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
}
}
/* Clear polled flag */
if (tmp_Flag_End == ADC_FLAG_JEOS)
{
/* Clear end of sequence JEOS flag of injected group if low power feature */
/* "LowPowerAutoWait " is disabled, to not interfere with this feature. */
/* For injected groups, no new conversion will start before JEOS is */
/* cleared. */
if (READ_BIT(tmp_cfgr, ADC_CFGR_AUTDLY) == 0UL)
{
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS));
}
}
else
{
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC);
}
/* Return API HAL status */
return HAL_OK;
}
/**
* @brief Enable ADC, start conversion of injected group with interruption.
* @note Interruptions enabled in this function according to initialization
* setting : JEOC (end of conversion) or JEOS (end of sequence)
* @note Case of multimode enabled (when multimode feature is enabled):
* HAL_ADCEx_InjectedStart_IT() API must be called for ADC slave first,
* then for ADC master.
* For ADC slave, ADC is enabled only (conversion is not started).
* For ADC master, ADC is enabled and multimode conversion is started.
* @param hadc ADC handle.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tmp_config_injected_queue;
#if defined(ADC_MULTIMODE_SUPPORT)
uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
#endif
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL)
{
return HAL_BUSY;
}
else
{
/* In case of software trigger detection enabled, JQDIS must be set
(which can be done only if ADSTART and JADSTART are both cleared).
If JQDIS is not set at that point, returns an error
- since software trigger detection is disabled. User needs to
resort to HAL_ADCEx_DisableInjectedQueue() API to set JQDIS.
- or (if JQDIS is intentionally reset) since JEXTEN = 0 which means
the queue is empty */
tmp_config_injected_queue = READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS);
if ((READ_BIT(hadc->Instance->JSQR, ADC_JSQR_JEXTEN) == 0UL)
&& (tmp_config_injected_queue == 0UL)
)
{
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hadc);
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
/* Start conversion if ADC is effectively enabled */
if (tmp_hal_status == HAL_OK)
{
/* Check if a regular conversion is ongoing */
if ((hadc->State & HAL_ADC_STATE_REG_BUSY) != 0UL)
{
/* Reset ADC error code field related to injected conversions only */
CLEAR_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
}
else
{
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
}
/* Set ADC state */
/* - Clear state bitfield related to injected group conversion results */
/* - Set state bitfield related to injected operation */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC,
HAL_ADC_STATE_INJ_BUSY);
#if defined(ADC_MULTIMODE_SUPPORT)
/* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
- if ADC instance is master or if multimode feature is not available
- if multimode setting is disabled (ADC instance slave in independent mode) */
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
)
{
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#endif
/* Clear ADC group injected group conversion flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* Enable ADC Injected context queue overflow interrupt if this feature */
/* is enabled. */
if ((hadc->Instance->CFGR & ADC_CFGR_JQM) != 0UL)
{
__HAL_ADC_ENABLE_IT(hadc, ADC_FLAG_JQOVF);
}
/* Enable ADC end of conversion interrupt */
switch (hadc->Init.EOCSelection)
{
case ADC_EOC_SEQ_CONV:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
break;
/* case ADC_EOC_SINGLE_CONV */
default:
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
break;
}
/* Enable conversion of injected group, if automatic injected conversion */
/* is disabled. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Case of multimode enabled (when multimode feature is available): */
/* if ADC is slave, */
/* - ADC is enabled only (conversion is not started), */
/* - if multimode only concerns regular conversion, ADC is enabled */
/* and conversion is started. */
/* If ADC is master or independent, */
/* - ADC is enabled and conversion is started. */
#if defined(ADC_MULTIMODE_SUPPORT)
if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
|| (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
|| (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
)
{
/* ADC instance is not a multimode slave instance with multimode injected conversions enabled */
if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT)
{
LL_ADC_INJ_StartConversion(hadc->Instance);
}
}
else
{
/* ADC instance is not a multimode slave instance with multimode injected conversions enabled */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
#else
if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT)
{
/* Start ADC group injected conversion */
LL_ADC_INJ_StartConversion(hadc->Instance);
}
#endif
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
/* Return function status */
return tmp_hal_status;
}
}
/**
* @brief Stop conversion of injected channels, disable interruption of
* end-of-conversion. Disable ADC peripheral if no regular conversion
* is on going.
* @note If ADC must be disabled and if conversion is on going on
* regular group, function HAL_ADC_Stop must be used to stop both
* injected and regular groups, and disable the ADC.
* @note If injected group mode auto-injection is enabled,
* function HAL_ADC_Stop must be used.
* @note Case of multimode enabled (when multimode feature is available):
* HAL_ADCEx_InjectedStop_IT() API must be called for ADC master first,
* then for ADC slave.
* For ADC master, conversion is stopped and ADC is disabled.
* For ADC slave, ADC is disabled only (conversion stop of ADC master
* has already stopped conversion of ADC slave).
* @note In case of auto-injection mode, HAL_ADC_Stop() must be used.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential conversion on going on injected group only. */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_INJECTED_GROUP);
/* Disable ADC peripheral if injected conversions are effectively stopped */
/* and if no conversion on the other group (regular group) is intended to */
/* continue. */
if (tmp_hal_status == HAL_OK)
{
/* Disable ADC end of conversion interrupt for injected channels */
__HAL_ADC_DISABLE_IT(hadc, (ADC_IT_JEOC | ADC_IT_JEOS | ADC_FLAG_JQOVF));
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* 2. Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Conversion on injected group is stopped, but ADC not disabled since */
/* conversion on regular group is still running. */
else
{
/* Set ADC state */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
#if defined(ADC_MULTIMODE_SUPPORT)
/**
* @brief Enable ADC, start MultiMode conversion and transfer regular results through DMA.
* @note Multimode must have been previously configured using
* HAL_ADCEx_MultiModeConfigChannel() function.
* Interruptions enabled in this function:
* overrun, DMA half transfer, DMA transfer complete.
* Each of these interruptions has its dedicated callback function.
* @note State field of Slave ADC handle is not updated in this configuration:
* user should not rely on it for information related to Slave regular
* conversions.
* @param hadc ADC handle of ADC master (handle of ADC slave must not be used)
* @param pData Destination Buffer address.
* @param Length Length of data to be transferred from ADC peripheral to memory (in bytes).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length)
{
HAL_StatusTypeDef tmp_hal_status;
ADC_HandleTypeDef tmphadcSlave;
ADC_Common_TypeDef *tmpADC_Common;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
{
return HAL_BUSY;
}
else
{
/* Process locked */
__HAL_LOCK(hadc);
/* Temporary handle minimum initialization */
__HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave);
ADC_CLEAR_ERRORCODE(&tmphadcSlave);
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
if (tmphadcSlave.Instance == NULL)
{
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
/* Enable the ADC peripherals: master and slave (in case if not already */
/* enabled previously) */
tmp_hal_status = ADC_Enable(hadc);
if (tmp_hal_status == HAL_OK)
{
tmp_hal_status = ADC_Enable(&tmphadcSlave);
}
/* Start multimode conversion of ADCs pair */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
(HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP),
HAL_ADC_STATE_REG_BUSY);
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
/* Set the DMA transfer complete callback */
hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
/* Set the DMA half transfer complete callback */
hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
/* Set the DMA error callback */
hadc->DMA_Handle->XferErrorCallback = ADC_DMAError ;
/* Pointer to the common control register */
tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance);
/* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */
/* start (in case of SW start): */
/* Clear regular group conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
/* Enable ADC overrun interrupt */
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
/* Start the DMA channel */
tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&tmpADC_Common->CDR, (uint32_t)pData, Length);
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversion(hadc->Instance);
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
/* Return function status */
return tmp_hal_status;
}
}
/**
* @brief Stop multimode ADC conversion, disable ADC DMA transfer, disable ADC peripheral.
* @note Multimode is kept enabled after this function. MultiMode DMA bits
* (MDMA and DMACFG bits of common CCR register) are maintained. To disable
* Multimode (set with HAL_ADCEx_MultiModeConfigChannel()), ADC must be
* reinitialized using HAL_ADC_Init() or HAL_ADC_DeInit(), or the user can
* resort to HAL_ADCEx_DisableMultiMode() API.
* @note In case of DMA configured in circular mode, function
* HAL_ADC_Stop_DMA() must be called after this function with handle of
* ADC slave, to properly disable the DMA channel.
* @param hadc ADC handle of ADC master (handle of ADC slave must not be used)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tickstart;
ADC_HandleTypeDef tmphadcSlave;
uint32_t tmphadcSlave_conversion_on_going;
HAL_StatusTypeDef tmphadcSlave_disable_status;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential multimode conversion on going, on regular and injected groups */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* Temporary handle minimum initialization */
__HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave);
ADC_CLEAR_ERRORCODE(&tmphadcSlave);
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
if (tmphadcSlave.Instance == NULL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
/* Procedure to disable the ADC peripheral: wait for conversions */
/* effectively stopped (ADC master and ADC slave), then disable ADC */
/* 1. Wait for ADC conversion completion for ADC master and ADC slave */
tickstart = HAL_GetTick();
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
while ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL)
|| (tmphadcSlave_conversion_on_going == 1UL)
)
{
if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL)
|| (tmphadcSlave_conversion_on_going == 1UL)
)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
}
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
}
/* Disable the DMA channel (in case of DMA in circular mode or stop */
/* while DMA transfer is on going) */
/* Note: DMA channel of ADC slave should be stopped after this function */
/* with HAL_ADC_Stop_DMA() API. */
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
/* Check if DMA channel effectively disabled */
if (tmp_hal_status == HAL_ERROR)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
}
/* Disable ADC overrun interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
/* 2. Disable the ADC peripherals: master and slave */
/* Update "tmp_hal_status" only if DMA channel disabling passed, to keep in */
/* memory a potential failing status. */
if (tmp_hal_status == HAL_OK)
{
tmphadcSlave_disable_status = ADC_Disable(&tmphadcSlave);
if ((ADC_Disable(hadc) == HAL_OK) &&
(tmphadcSlave_disable_status == HAL_OK))
{
tmp_hal_status = HAL_OK;
}
}
else
{
/* In case of error, attempt to disable ADC master and slave without status assert */
(void) ADC_Disable(hadc);
(void) ADC_Disable(&tmphadcSlave);
}
/* Set ADC state (ADC master) */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Return the last ADC Master and Slave regular conversions results when in multimode configuration.
* @param hadc ADC handle of ADC Master (handle of ADC Slave must not be used)
* @retval The converted data values.
*/
uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc)
{
const ADC_Common_TypeDef *tmpADC_Common;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
/* Prevent unused argument(s) compilation warning if no assert_param check */
/* and possible no usage in __LL_ADC_COMMON_INSTANCE() below */
UNUSED(hadc);
/* Pointer to the common control register */
tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance);
/* Return the multi mode conversion value */
return tmpADC_Common->CDR;
}
#endif /* ADC_MULTIMODE_SUPPORT */
/**
* @brief Get ADC injected group conversion result.
* @note Reading register JDRx automatically clears ADC flag JEOC
* (ADC group injected end of unitary conversion).
* @note This function does not clear ADC flag JEOS
* (ADC group injected end of sequence conversion)
* Occurrence of flag JEOS rising:
* - If sequencer is composed of 1 rank, flag JEOS is equivalent
* to flag JEOC.
* - If sequencer is composed of several ranks, during the scan
* sequence flag JEOC only is raised, at the end of the scan sequence
* both flags JEOC and EOS are raised.
* Flag JEOS must not be cleared by this function because
* it would not be compliant with low power features
* (feature low power auto-wait, not available on all STM32 families).
* To clear this flag, either use function:
* in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
* model polling: @ref HAL_ADCEx_InjectedPollForConversion()
* or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_JEOS).
* @param hadc ADC handle
* @param InjectedRank the converted ADC injected rank.
* This parameter can be one of the following values:
* @arg @ref ADC_INJECTED_RANK_1 ADC group injected rank 1
* @arg @ref ADC_INJECTED_RANK_2 ADC group injected rank 2
* @arg @ref ADC_INJECTED_RANK_3 ADC group injected rank 3
* @arg @ref ADC_INJECTED_RANK_4 ADC group injected rank 4
* @retval ADC group injected conversion data
*/
uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef *hadc, uint32_t InjectedRank)
{
uint32_t tmp_jdr;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_INJECTED_RANK(InjectedRank));
/* Get ADC converted value */
switch (InjectedRank)
{
case ADC_INJECTED_RANK_4:
tmp_jdr = hadc->Instance->JDR4;
break;
case ADC_INJECTED_RANK_3:
tmp_jdr = hadc->Instance->JDR3;
break;
case ADC_INJECTED_RANK_2:
tmp_jdr = hadc->Instance->JDR2;
break;
case ADC_INJECTED_RANK_1:
default:
tmp_jdr = hadc->Instance->JDR1;
break;
}
/* Return ADC converted value */
return tmp_jdr;
}
/**
* @brief Injected conversion complete callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADCEx_InjectedConvCpltCallback must be implemented in the user file.
*/
}
/**
* @brief Injected context queue overflow callback.
* @note This callback is called if injected context queue is enabled
(parameter "QueueInjectedContext" in injected channel configuration)
and if a new injected context is set when queue is full (maximum 2
contexts).
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADCEx_InjectedQueueOverflowCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADCEx_InjectedQueueOverflowCallback must be implemented in the user file.
*/
}
/**
* @brief Analog watchdog 2 callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADCEx_LevelOutOfWindow2Callback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADCEx_LevelOutOfWindow2Callback must be implemented in the user file.
*/
}
/**
* @brief Analog watchdog 3 callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADCEx_LevelOutOfWindow3Callback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADCEx_LevelOutOfWindow3Callback must be implemented in the user file.
*/
}
/**
* @brief End Of Sampling callback in non-blocking mode.
* @param hadc ADC handle
* @retval None
*/
__weak void HAL_ADCEx_EndOfSamplingCallback(ADC_HandleTypeDef *hadc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADCEx_EndOfSamplingCallback must be implemented in the user file.
*/
}
/**
* @brief Stop ADC conversion of regular group (and injected channels in
* case of auto_injection mode), disable ADC peripheral if no
* conversion is on going on injected group.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADCEx_RegularStop(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential regular conversion on going */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP);
/* Disable ADC peripheral if regular conversions are effectively stopped
and if no injected conversions are on-going */
if (tmp_hal_status == HAL_OK)
{
/* Clear HAL_ADC_STATE_REG_BUSY bit */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* 2. Disable the ADC peripheral */
tmp_hal_status = ADC_Disable(hadc);
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
/* Conversion on injected group is stopped, but ADC not disabled since */
/* conversion on regular group is still running. */
else
{
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Stop ADC conversion of ADC groups regular and injected,
* disable interrution of end-of-conversion,
* disable ADC peripheral if no conversion is on going
* on injected group.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADCEx_RegularStop_IT(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential regular conversion on going */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped
and if no injected conversion is on-going */
if (tmp_hal_status == HAL_OK)
{
/* Clear HAL_ADC_STATE_REG_BUSY bit */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
/* Disable all regular-related interrupts */
__HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
/* 2. Disable ADC peripheral if no injected conversions are on-going */
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
tmp_hal_status = ADC_Disable(hadc);
/* if no issue reported */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
else
{
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
/**
* @brief Stop ADC conversion of regular group (and injected group in
* case of auto_injection mode), disable ADC DMA transfer, disable
* ADC peripheral if no conversion is on going
* on injected group.
* @note HAL_ADCEx_RegularStop_DMA() function is dedicated to single-ADC mode only.
* For multimode (when multimode feature is available),
* HAL_ADCEx_RegularMultiModeStop_DMA() API must be used.
* @param hadc ADC handle
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_ADCEx_RegularStop_DMA(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential regular conversion on going */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped
and if no injected conversion is on-going */
if (tmp_hal_status == HAL_OK)
{
/* Clear HAL_ADC_STATE_REG_BUSY bit */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
/* Disable ADC DMA (ADC DMA configuration ADC_CFGR_DMACFG is kept) */
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN);
/* Disable the DMA channel (in case of DMA in circular mode or stop while */
/* while DMA transfer is on going) */
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
/* Check if DMA channel effectively disabled */
if (tmp_hal_status != HAL_OK)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
}
/* Disable ADC overrun interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
/* 2. Disable the ADC peripheral */
/* Update "tmp_hal_status" only if DMA channel disabling passed, */
/* to keep in memory a potential failing status. */
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
if (tmp_hal_status == HAL_OK)
{
tmp_hal_status = ADC_Disable(hadc);
}
else
{
(void)ADC_Disable(hadc);
}
/* Check if ADC is effectively disabled */
if (tmp_hal_status == HAL_OK)
{
/* Set ADC state */
ADC_STATE_CLR_SET(hadc->State,
HAL_ADC_STATE_INJ_BUSY,
HAL_ADC_STATE_READY);
}
}
else
{
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
#if defined(ADC_MULTIMODE_SUPPORT)
/**
* @brief Stop DMA-based multimode ADC conversion, disable ADC DMA transfer, disable ADC peripheral if no injected conversion is on-going.
* @note Multimode is kept enabled after this function. Multimode DMA bits
* (MDMA and DMACFG bits of common CCR register) are maintained. To disable
* multimode (set with HAL_ADCEx_MultiModeConfigChannel()), ADC must be
* reinitialized using HAL_ADC_Init() or HAL_ADC_DeInit(), or the user can
* resort to HAL_ADCEx_DisableMultiMode() API.
* @note In case of DMA configured in circular mode, function
* HAL_ADCEx_RegularStop_DMA() must be called after this function with handle of
* ADC slave, to properly disable the DMA channel.
* @param hadc ADC handle of ADC master (handle of ADC slave must not be used)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_RegularMultiModeStop_DMA(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tickstart;
ADC_HandleTypeDef tmphadcSlave;
uint32_t tmphadcSlave_conversion_on_going;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
/* 1. Stop potential multimode conversion on going, on regular groups */
tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP);
/* Disable ADC peripheral if conversions are effectively stopped */
if (tmp_hal_status == HAL_OK)
{
/* Clear HAL_ADC_STATE_REG_BUSY bit */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
/* Temporary handle minimum initialization */
__HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave);
ADC_CLEAR_ERRORCODE(&tmphadcSlave);
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
if (tmphadcSlave.Instance == NULL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
/* Procedure to disable the ADC peripheral: wait for conversions */
/* effectively stopped (ADC master and ADC slave), then disable ADC */
/* 1. Wait for ADC conversion completion for ADC master and ADC slave */
tickstart = HAL_GetTick();
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
while ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL)
|| (tmphadcSlave_conversion_on_going == 1UL)
)
{
if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
{
/* New check to avoid false timeout detection in case of preemption */
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL)
|| (tmphadcSlave_conversion_on_going == 1UL)
)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
}
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
}
/* Disable the DMA channel (in case of DMA in circular mode or stop */
/* while DMA transfer is on going) */
/* Note: DMA channel of ADC slave should be stopped after this function */
/* with HAL_ADCEx_RegularStop_DMA() API. */
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
/* Check if DMA channel effectively disabled */
if (tmp_hal_status != HAL_OK)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
}
/* Disable ADC overrun interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
/* 2. Disable the ADC peripherals: master and slave if no injected */
/* conversion is on-going. */
/* Update "tmp_hal_status" only if DMA channel disabling passed, to keep in */
/* memory a potential failing status. */
if (tmp_hal_status == HAL_OK)
{
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
tmp_hal_status = ADC_Disable(hadc);
if (tmp_hal_status == HAL_OK)
{
if (LL_ADC_INJ_IsConversionOngoing((&tmphadcSlave)->Instance) == 0UL)
{
tmp_hal_status = ADC_Disable(&tmphadcSlave);
}
}
}
if (tmp_hal_status == HAL_OK)
{
/* Both Master and Slave ADC's could be disabled. Update Master State */
/* Clear HAL_ADC_STATE_INJ_BUSY bit, set HAL_ADC_STATE_READY bit */
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
else
{
/* injected (Master or Slave) conversions are still on-going,
no Master State change */
}
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
#endif /* ADC_MULTIMODE_SUPPORT */
/**
* @}
*/
/** @defgroup ADCEx_Exported_Functions_Group2 ADC Extended Peripheral Control functions
* @brief ADC Extended Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure channels on injected group
(+) Configure multimode when multimode feature is available
(+) Enable or Disable Injected Queue
(+) Disable ADC voltage regulator
(+) Enter ADC deep-power-down mode
@endverbatim
* @{
*/
/**
* @brief Configure a channel to be assigned to ADC group injected.
* @note Possibility to update parameters on the fly:
* This function initializes injected group, following calls to this
* function can be used to reconfigure some parameters of structure
* "ADC_InjectionConfTypeDef" on the fly, without resetting the ADC.
* The setting of these parameters is conditioned to ADC state:
* Refer to comments of structure "ADC_InjectionConfTypeDef".
* @note In case of usage of internal measurement channels:
* Vbat/VrefInt/TempSensor.
* These internal paths can be disabled using function
* HAL_ADC_DeInit().
* @note Caution: For Injected Context Queue use, a context must be fully
* defined before start of injected conversion. All channels are configured
* consecutively for the same ADC instance. Therefore, the number of calls to
* HAL_ADCEx_InjectedConfigChannel() must be equal to the value of parameter
* InjectedNbrOfConversion for each context.
* - Example 1: If 1 context is intended to be used (or if there is no use of the
* Injected Queue Context feature) and if the context contains 3 injected ranks
* (InjectedNbrOfConversion = 3), HAL_ADCEx_InjectedConfigChannel() must be
* called once for each channel (i.e. 3 times) before starting a conversion.
* This function must not be called to configure a 4th injected channel:
* it would start a new context into context queue.
* - Example 2: If 2 contexts are intended to be used and each of them contains
* 3 injected ranks (InjectedNbrOfConversion = 3),
* HAL_ADCEx_InjectedConfigChannel() must be called once for each channel and
* for each context (3 channels x 2 contexts = 6 calls). Conversion can
* start once the 1st context is set, that is after the first three
* HAL_ADCEx_InjectedConfigChannel() calls. The 2nd context can be set on the fly.
* @param hadc ADC handle
* @param sConfigInjected Structure of ADC injected group and ADC channel for
* injected group.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
uint32_t tmpOffsetShifted;
uint32_t tmp_config_internal_channel;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
__IO uint32_t wait_loop_index = 0;
uint32_t tmp_JSQR_ContextQueueBeingBuilt = 0U;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime));
assert_param(IS_ADC_SINGLE_DIFFERENTIAL(sConfigInjected->InjectedSingleDiff));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->QueueInjectedContext));
assert_param(IS_ADC_EXTTRIGINJEC_EDGE(sConfigInjected->ExternalTrigInjecConvEdge));
assert_param(IS_ADC_EXTTRIGINJEC(hadc, sConfigInjected->ExternalTrigInjecConv));
assert_param(IS_ADC_OFFSET_NUMBER(sConfigInjected->InjectedOffsetNumber));
assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), sConfigInjected->InjectedOffset));
assert_param(IS_ADC_OFFSET_SIGN(sConfigInjected->InjectedOffsetSign));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedOffsetSaturation));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjecOversamplingMode));
if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
{
assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank));
assert_param(IS_ADC_INJECTED_NB_CONV(sConfigInjected->InjectedNbrOfConversion));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode));
}
/* if JOVSE is set, the value of the OFFSETy_EN bit in ADCx_OFRy register is
ignored (considered as reset) */
assert_param(!((sConfigInjected->InjectedOffsetNumber != ADC_OFFSET_NONE) && (sConfigInjected->InjecOversamplingMode == ENABLE)));
/* JDISCEN and JAUTO bits can't be set at the same time */
assert_param(!((sConfigInjected->InjectedDiscontinuousConvMode == ENABLE) && (sConfigInjected->AutoInjectedConv == ENABLE)));
/* DISCEN and JAUTO bits can't be set at the same time */
assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (sConfigInjected->AutoInjectedConv == ENABLE)));
/* Verification of channel number */
if (sConfigInjected->InjectedSingleDiff != ADC_DIFFERENTIAL_ENDED)
{
assert_param(IS_ADC_CHANNEL(hadc, sConfigInjected->InjectedChannel));
}
else
{
assert_param(IS_ADC_DIFF_CHANNEL(hadc, sConfigInjected->InjectedChannel));
}
/* Process locked */
__HAL_LOCK(hadc);
/* Configuration of injected group sequencer: */
/* Hardware constraint: Must fully define injected context register JSQR */
/* before make it entering into injected sequencer queue. */
/* */
/* - if scan mode is disabled: */
/* * Injected channels sequence length is set to 0x00: 1 channel */
/* converted (channel on injected rank 1) */
/* Parameter "InjectedNbrOfConversion" is discarded. */
/* * Injected context register JSQR setting is simple: register is fully */
/* defined on one call of this function (for injected rank 1) and can */
/* be entered into queue directly. */
/* - if scan mode is enabled: */
/* * Injected channels sequence length is set to parameter */
/* "InjectedNbrOfConversion". */
/* * Injected context register JSQR setting more complex: register is */
/* fully defined over successive calls of this function, for each */
/* injected channel rank. It is entered into queue only when all */
/* injected ranks have been set. */
/* Note: Scan mode is not present by hardware on this device, but used */
/* by software for alignment over all STM32 devices. */
if ((hadc->Init.ScanConvMode == ADC_SCAN_DISABLE) ||
(sConfigInjected->InjectedNbrOfConversion == 1U))
{
/* Configuration of context register JSQR: */
/* - number of ranks in injected group sequencer: fixed to 1st rank */
/* (scan mode disabled, only rank 1 used) */
/* - external trigger to start conversion */
/* - external trigger polarity */
/* - channel set to rank 1 (scan mode disabled, only rank 1 can be used) */
if (sConfigInjected->InjectedRank == ADC_INJECTED_RANK_1)
{
/* Enable external trigger if trigger selection is different of */
/* software start. */
/* Note: This configuration keeps the hardware feature of parameter */
/* ExternalTrigInjecConvEdge "trigger edge none" equivalent to */
/* software start. */
if (sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START)
{
tmp_JSQR_ContextQueueBeingBuilt = (ADC_JSQR_RK(sConfigInjected->InjectedChannel, ADC_INJECTED_RANK_1)
| (sConfigInjected->ExternalTrigInjecConv & ADC_JSQR_JEXTSEL)
| sConfigInjected->ExternalTrigInjecConvEdge
);
}
else
{
tmp_JSQR_ContextQueueBeingBuilt = (ADC_JSQR_RK(sConfigInjected->InjectedChannel, ADC_INJECTED_RANK_1));
}
MODIFY_REG(hadc->Instance->JSQR, ADC_JSQR_FIELDS, tmp_JSQR_ContextQueueBeingBuilt);
/* For debug and informative reasons, hadc handle saves JSQR setting */
hadc->InjectionConfig.ContextQueue = tmp_JSQR_ContextQueueBeingBuilt;
}
}
else
{
/* Case of scan mode enabled, several channels to set into injected group */
/* sequencer. */
/* */
/* Procedure to define injected context register JSQR over successive */
/* calls of this function, for each injected channel rank: */
/* 1. Start new context and set parameters related to all injected */
/* channels: injected sequence length and trigger. */
/* if hadc->InjectionConfig.ChannelCount is equal to 0, this is the first */
/* call of the context under setting */
if (hadc->InjectionConfig.ChannelCount == 0U)
{
/* Initialize number of channels that will be configured on the context */
/* being built */
hadc->InjectionConfig.ChannelCount = sConfigInjected->InjectedNbrOfConversion;
/* Handle hadc saves the context under build up over each HAL_ADCEx_InjectedConfigChannel()
call, this context will be written in JSQR register at the last call.
At this point, the context is merely reset */
hadc->InjectionConfig.ContextQueue = 0x00000000U;
/* Configuration of context register JSQR: */
/* - number of ranks in injected group sequencer */
/* - external trigger to start conversion */
/* - external trigger polarity */
/* Enable external trigger if trigger selection is different of */
/* software start. */
/* Note: This configuration keeps the hardware feature of parameter */
/* ExternalTrigInjecConvEdge "trigger edge none" equivalent to */
/* software start. */
if (sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START)
{
tmp_JSQR_ContextQueueBeingBuilt = ((sConfigInjected->InjectedNbrOfConversion - 1U)
| (sConfigInjected->ExternalTrigInjecConv & ADC_JSQR_JEXTSEL)
| sConfigInjected->ExternalTrigInjecConvEdge
);
}
else
{
tmp_JSQR_ContextQueueBeingBuilt = ((sConfigInjected->InjectedNbrOfConversion - 1U));
}
}
/* 2. Continue setting of context under definition with parameter */
/* related to each channel: channel rank sequence */
/* Clear the old JSQx bits for the selected rank */
tmp_JSQR_ContextQueueBeingBuilt &= ~ADC_JSQR_RK(ADC_SQR3_SQ10, sConfigInjected->InjectedRank);
/* Set the JSQx bits for the selected rank */
tmp_JSQR_ContextQueueBeingBuilt |= ADC_JSQR_RK(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank);
/* Decrease channel count */
hadc->InjectionConfig.ChannelCount--;
/* 3. tmp_JSQR_ContextQueueBeingBuilt is fully built for this HAL_ADCEx_InjectedConfigChannel()
call, aggregate the setting to those already built during the previous
HAL_ADCEx_InjectedConfigChannel() calls (for the same context of course) */
hadc->InjectionConfig.ContextQueue |= tmp_JSQR_ContextQueueBeingBuilt;
/* 4. End of context setting: if this is the last channel set, then write context
into register JSQR and make it enter into queue */
if (hadc->InjectionConfig.ChannelCount == 0U)
{
MODIFY_REG(hadc->Instance->JSQR, ADC_JSQR_FIELDS, hadc->InjectionConfig.ContextQueue);
}
}
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on injected group: */
/* - Injected context queue: Queue disable (active context is kept) or */
/* enable (context decremented, up to 2 contexts queued) */
/* - Injected discontinuous mode: can be enabled only if auto-injected */
/* mode is disabled. */
if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
{
/* If auto-injected mode is disabled: no constraint */
if (sConfigInjected->AutoInjectedConv == DISABLE)
{
MODIFY_REG(hadc->Instance->CFGR,
ADC_CFGR_JQM | ADC_CFGR_JDISCEN,
ADC_CFGR_INJECT_CONTEXT_QUEUE((uint32_t)sConfigInjected->QueueInjectedContext) |
ADC_CFGR_INJECT_DISCCONTINUOUS((uint32_t)sConfigInjected->InjectedDiscontinuousConvMode));
}
/* If auto-injected mode is enabled: Injected discontinuous setting is */
/* discarded. */
else
{
MODIFY_REG(hadc->Instance->CFGR,
ADC_CFGR_JQM | ADC_CFGR_JDISCEN,
ADC_CFGR_INJECT_CONTEXT_QUEUE((uint32_t)sConfigInjected->QueueInjectedContext));
}
}
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular and injected groups: */
/* - Automatic injected conversion: can be enabled if injected group */
/* external triggers are disabled. */
/* - Channel sampling time */
/* - Channel offset */
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
/* If injected group external triggers are disabled (set to injected */
/* software start): no constraint */
if ((sConfigInjected->ExternalTrigInjecConv == ADC_INJECTED_SOFTWARE_START)
|| (sConfigInjected->ExternalTrigInjecConvEdge == ADC_EXTERNALTRIGINJECCONV_EDGE_NONE))
{
if (sConfigInjected->AutoInjectedConv == ENABLE)
{
SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO);
}
else
{
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO);
}
}
/* If Automatic injected conversion was intended to be set and could not */
/* due to injected group external triggers enabled, error is reported. */
else
{
if (sConfigInjected->AutoInjectedConv == ENABLE)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
tmp_hal_status = HAL_ERROR;
}
else
{
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO);
}
}
if (sConfigInjected->InjecOversamplingMode == ENABLE)
{
assert_param(IS_ADC_OVERSAMPLING_RATIO(sConfigInjected->InjecOversampling.Ratio));
assert_param(IS_ADC_RIGHT_BIT_SHIFT(sConfigInjected->InjecOversampling.RightBitShift));
/* JOVSE must be reset in case of triggered regular mode */
assert_param(!(READ_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSE | ADC_CFGR2_TROVS) == (ADC_CFGR2_ROVSE | ADC_CFGR2_TROVS)));
/* Configuration of Injected Oversampler: */
/* - Oversampling Ratio */
/* - Right bit shift */
/* Enable OverSampling mode */
MODIFY_REG(hadc->Instance->CFGR2,
ADC_CFGR2_JOVSE |
ADC_CFGR2_OVSR |
ADC_CFGR2_OVSS,
ADC_CFGR2_JOVSE |
sConfigInjected->InjecOversampling.Ratio |
sConfigInjected->InjecOversampling.RightBitShift
);
}
else
{
/* Disable Regular OverSampling */
CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_JOVSE);
}
/* Manage specific case of sampling time 3.5 cycles replacing 2.5 cyles */
if (sConfigInjected->InjectedSamplingTime == ADC_SAMPLETIME_3CYCLES_5)
{
/* Set sampling time of the selected ADC channel */
LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfigInjected->InjectedChannel, LL_ADC_SAMPLINGTIME_2CYCLES_5);
/* Set ADC sampling time common configuration */
LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_3C5_REPL_2C5);
}
else
{
/* Set sampling time of the selected ADC channel */
LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfigInjected->InjectedChannel, sConfigInjected->InjectedSamplingTime);
/* Set ADC sampling time common configuration */
LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_DEFAULT);
}
/* Configure the offset: offset enable/disable, channel, offset value */
/* Shift the offset with respect to the selected ADC resolution. */
/* Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 */
tmpOffsetShifted = ADC_OFFSET_SHIFT_RESOLUTION(hadc, sConfigInjected->InjectedOffset);
if (sConfigInjected->InjectedOffsetNumber != ADC_OFFSET_NONE)
{
/* Set ADC selected offset number */
LL_ADC_SetOffset(hadc->Instance, sConfigInjected->InjectedOffsetNumber, sConfigInjected->InjectedChannel,
tmpOffsetShifted);
/* Set ADC selected offset sign & saturation */
LL_ADC_SetOffsetSign(hadc->Instance, sConfigInjected->InjectedOffsetNumber, sConfigInjected->InjectedOffsetSign);
LL_ADC_SetOffsetSaturation(hadc->Instance, sConfigInjected->InjectedOffsetNumber,
(sConfigInjected->InjectedOffsetSaturation == ENABLE) ? LL_ADC_OFFSET_SATURATION_ENABLE : LL_ADC_OFFSET_SATURATION_DISABLE);
}
else
{
/* Scan each offset register to check if the selected channel is targeted. */
/* If this is the case, the corresponding offset number is disabled. */
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_1))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_1, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_2))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_2, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_3))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_3, LL_ADC_OFFSET_DISABLE);
}
if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_4))
== __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel))
{
LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_4, LL_ADC_OFFSET_DISABLE);
}
}
}
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated only when ADC is disabled: */
/* - Single or differential mode */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
/* Set mode single-ended or differential input of the selected ADC channel */
LL_ADC_SetChannelSingleDiff(hadc->Instance, sConfigInjected->InjectedChannel, sConfigInjected->InjectedSingleDiff);
/* Configuration of differential mode */
/* Note: ADC channel number masked with value "0x1F" to ensure shift value within 32 bits range */
if (sConfigInjected->InjectedSingleDiff == ADC_DIFFERENTIAL_ENDED)
{
/* Set sampling time of the selected ADC channel */
LL_ADC_SetChannelSamplingTime(hadc->Instance,
(uint32_t)(__LL_ADC_DECIMAL_NB_TO_CHANNEL((__LL_ADC_CHANNEL_TO_DECIMAL_NB((uint32_t)sConfigInjected->InjectedChannel)
+ 1UL) & 0x1FUL)), sConfigInjected->InjectedSamplingTime);
}
}
/* Management of internal measurement channels: Vbat/VrefInt/TempSensor */
/* internal measurement paths enable: If internal channel selected, */
/* enable dedicated internal buffers and path. */
/* Note: these internal measurement paths can be disabled using */
/* HAL_ADC_DeInit(). */
if (__LL_ADC_IS_CHANNEL_INTERNAL(sConfigInjected->InjectedChannel))
{
tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
/* If the requested internal measurement path has already been enabled, */
/* bypass the configuration processing. */
if (((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR_ADC1)
|| (sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR_ADC5))
&& ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL))
{
if (ADC_TEMPERATURE_SENSOR_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel);
/* Delay for temperature sensor stabilization time */
/* Wait loop initialization and execution */
/* Note: Variable divided by 2 to compensate partially */
/* CPU processing cycles, scaling in us split to not */
/* exceed 32 bits register capacity and handle low frequency. */
wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * (((SystemCoreClock / (100000UL * 2UL)) + 1UL) + 1UL));
while (wait_loop_index != 0UL)
{
wait_loop_index--;
}
}
}
else if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT)
&& ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VBAT) == 0UL))
{
if (ADC_BATTERY_VOLTAGE_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_VBAT | tmp_config_internal_channel);
}
}
else if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT)
&& ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
{
if (ADC_VREFINT_INSTANCE(hadc))
{
LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel);
}
}
else
{
/* nothing to do */
}
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
#if defined(ADC_MULTIMODE_SUPPORT)
/**
* @brief Enable ADC multimode and configure multimode parameters
* @note Possibility to update parameters on the fly:
* This function initializes multimode parameters, following
* calls to this function can be used to reconfigure some parameters
* of structure "ADC_MultiModeTypeDef" on the fly, without resetting
* the ADCs.
* The setting of these parameters is conditioned to ADC state.
* For parameters constraints, see comments of structure
* "ADC_MultiModeTypeDef".
* @note To move back configuration from multimode to single mode, ADC must
* be reset (using function HAL_ADC_Init() ).
* @param hadc Master ADC handle
* @param multimode Structure of ADC multimode configuration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef *hadc, ADC_MultiModeTypeDef *multimode)
{
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
ADC_Common_TypeDef *tmpADC_Common;
ADC_HandleTypeDef tmphadcSlave;
uint32_t tmphadcSlave_conversion_on_going;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
assert_param(IS_ADC_MULTIMODE(multimode->Mode));
if (multimode->Mode != ADC_MODE_INDEPENDENT)
{
assert_param(IS_ADC_DMA_ACCESS_MULTIMODE(multimode->DMAAccessMode));
assert_param(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay));
}
/* Process locked */
__HAL_LOCK(hadc);
/* Temporary handle minimum initialization */
__HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave);
ADC_CLEAR_ERRORCODE(&tmphadcSlave);
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
if (tmphadcSlave.Instance == NULL)
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
/* Process unlocked */
__HAL_UNLOCK(hadc);
return HAL_ERROR;
}
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular group: */
/* - Multimode DMA configuration */
/* - Multimode DMA mode */
tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance);
if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
&& (tmphadcSlave_conversion_on_going == 0UL))
{
/* Pointer to the common control register */
tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance);
/* If multimode is selected, configure all multimode parameters. */
/* Otherwise, reset multimode parameters (can be used in case of */
/* transition from multimode to independent mode). */
if (multimode->Mode != ADC_MODE_INDEPENDENT)
{
MODIFY_REG(tmpADC_Common->CCR, ADC_CCR_MDMA | ADC_CCR_DMACFG,
multimode->DMAAccessMode |
ADC_CCR_MULTI_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests));
/* Parameters that can be updated only when ADC is disabled: */
/* - Multimode mode selection */
/* - Multimode delay */
/* Note: Delay range depends on selected resolution: */
/* from 1 to 12 clock cycles for 12 bits */
/* from 1 to 10 clock cycles for 10 bits, */
/* from 1 to 8 clock cycles for 8 bits */
/* from 1 to 6 clock cycles for 6 bits */
/* If a higher delay is selected, it will be clipped to maximum delay */
/* range */
if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
{
MODIFY_REG(tmpADC_Common->CCR,
ADC_CCR_DUAL |
ADC_CCR_DELAY,
multimode->Mode |
multimode->TwoSamplingDelay
);
}
}
else /* ADC_MODE_INDEPENDENT */
{
CLEAR_BIT(tmpADC_Common->CCR, ADC_CCR_MDMA | ADC_CCR_DMACFG);
/* Parameters that can be updated only when ADC is disabled: */
/* - Multimode mode selection */
/* - Multimode delay */
if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
{
CLEAR_BIT(tmpADC_Common->CCR, ADC_CCR_DUAL | ADC_CCR_DELAY);
}
}
}
/* If one of the ADC sharing the same common group is enabled, no update */
/* could be done on neither of the multimode structure parameters. */
else
{
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
tmp_hal_status = HAL_ERROR;
}
/* Process unlocked */
__HAL_UNLOCK(hadc);
/* Return function status */
return tmp_hal_status;
}
#endif /* ADC_MULTIMODE_SUPPORT */
/**
* @brief Enable Injected Queue
* @note This function resets CFGR register JQDIS bit in order to enable the
* Injected Queue. JQDIS can be written only when ADSTART and JDSTART
* are both equal to 0 to ensure that no regular nor injected
* conversion is ongoing.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_EnableInjectedQueue(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
/* Parameter can be set only if no conversion is on-going */
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS);
/* Update state, clear previous result related to injected queue overflow */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF);
tmp_hal_status = HAL_OK;
}
else
{
tmp_hal_status = HAL_ERROR;
}
return tmp_hal_status;
}
/**
* @brief Disable Injected Queue
* @note This function sets CFGR register JQDIS bit in order to disable the
* Injected Queue. JQDIS can be written only when ADSTART and JDSTART
* are both equal to 0 to ensure that no regular nor injected
* conversion is ongoing.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_DisableInjectedQueue(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
uint32_t tmp_adc_is_conversion_on_going_regular;
uint32_t tmp_adc_is_conversion_on_going_injected;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
/* Parameter can be set only if no conversion is on-going */
if ((tmp_adc_is_conversion_on_going_regular == 0UL)
&& (tmp_adc_is_conversion_on_going_injected == 0UL)
)
{
LL_ADC_INJ_SetQueueMode(hadc->Instance, LL_ADC_INJ_QUEUE_DISABLE);
tmp_hal_status = HAL_OK;
}
else
{
tmp_hal_status = HAL_ERROR;
}
return tmp_hal_status;
}
/**
* @brief Disable ADC voltage regulator.
* @note Disabling voltage regulator allows to save power. This operation can
* be carried out only when ADC is disabled.
* @note To enable again the voltage regulator, the user is expected to
* resort to HAL_ADC_Init() API.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_DisableVoltageRegulator(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Setting of this feature is conditioned to ADC state: ADC must be ADC disabled */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
LL_ADC_DisableInternalRegulator(hadc->Instance);
tmp_hal_status = HAL_OK;
}
else
{
tmp_hal_status = HAL_ERROR;
}
return tmp_hal_status;
}
/**
* @brief Enter ADC deep-power-down mode
* @note This mode is achieved in setting DEEPPWD bit and allows to save power
* in reducing leakage currents. It is particularly interesting before
* entering stop modes.
* @note Setting DEEPPWD automatically clears ADVREGEN bit and disables the
* ADC voltage regulator. This means that this API encompasses
* HAL_ADCEx_DisableVoltageRegulator(). Additionally, the internal
* calibration is lost.
* @note To exit the ADC deep-power-down mode, the user is expected to
* resort to HAL_ADC_Init() API as well as to relaunch a calibration
* with HAL_ADCEx_Calibration_Start() API or to re-apply a previously
* saved calibration factor.
* @param hadc ADC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ADCEx_EnterADCDeepPowerDownMode(ADC_HandleTypeDef *hadc)
{
HAL_StatusTypeDef tmp_hal_status;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Setting of this feature is conditioned to ADC state: ADC must be ADC disabled */
if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
{
LL_ADC_EnableDeepPowerDown(hadc->Instance);
tmp_hal_status = HAL_OK;
}
else
{
tmp_hal_status = HAL_ERROR;
}
return tmp_hal_status;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_ADC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 93,318 |
C
| 38.308762 | 157 | 0.606367 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_rtc.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 HAL_RTC_RegisterCallback() to register an interrupt callback.
[..]
Function HAL_RTC_RegisterCallback() allows to register following callbacks:
(+) AlarmAEventCallback : RTC Alarm A Event callback.
(+) AlarmBEventCallback : RTC Alarm B Event callback.
(+) TimeStampEventCallback : RTC TimeStamp Event callback.
(+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback.
(+) 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.
(+) InternalTamper8EventCallback : RTC InternalTamper 8 Event callback.
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
(+) AlarmAEventCallback_S : RTC Alarm A Event callback_S
(+) AlarmBEventCallback_S : RTC Alarm B Event callback_S.
(+) TimeStampEventCallback_S : RTC TimeStampEvent callback_S.
(+) WakeUpTimerEventCallback_S : RTC WakeUpTimerEvent callback_S.
(+) Tamper1EventCallback_S : RTC Tamper 1 Event callback_S.
(+) Tamper2EventCallback_S : RTC Tamper 2 Event callback_S.
(+) Tamper3EventCallback_S : RTC Tamper 3 Event callback_S.
(+) Tamper4EventCallback_S : RTC Tamper 4 Event callback_S.
(+) Tamper5EventCallback_S : RTC Tamper 5 Event callback_S.
(+) Tamper6EventCallback_S : RTC Tamper 6 Event callback_S.
(+) Tamper7EventCallback_S : RTC Tamper 7 Event callback_S.
(+) Tamper8EventCallback_S : RTC Tamper 8 Event callback_S.
(+) InternalTamper1EventCallback_S : RTC InternalTamper 1 Event callback_S.
(+) InternalTamper2EventCallback_S : RTC InternalTamper 2 Event callback_S.
(+) InternalTamper3EventCallback_S : RTC InternalTamper 3 Event callback_S.
(+) InternalTamper5EventCallback_S : RTC InternalTamper 5 Event callback_S.
(+) InternalTamper8EventCallback_S : RTC InternalTamper 8 Event callback_S.
#endif
(+) MspInitCallback : RTC MspInit callback.
(+) MspDeInitCallback : RTC MspDeInit callback.
[..]
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_RTC_UnRegisterCallback() to reset a callback to the default
weak function.
HAL_RTC_UnRegisterCallback() takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) AlarmAEventCallback : RTC Alarm A Event callback.
(+) AlarmBEventCallback : RTC Alarm B Event callback.
(+) TimeStampEventCallback : RTC TimeStamp Event callback.
(+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback.
(+) 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 Internal Tamper 1 Event callback.
(+) InternalTamper2EventCallback : RTC Internal Tamper 2 Event callback.
(+) InternalTamper3EventCallback : RTC Internal Tamper 3 Event callback.
(+) InternalTamper4EventCallback : RTC Internal Tamper 4 Event callback.
(+) InternalTamper5EventCallback : RTC Internal Tamper 5 Event callback.
(+) InternalTamper6EventCallback : RTC Internal Tamper 6 Event callback.
(+) InternalTamper8EventCallback : RTC Internal Tamper 8 Event callback.
#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)
(+) AlarmAEventCallback_S : RTC Alarm A Event callback secure.
(+) AlarmBEventCallback_S : RTC Alarm B Event callback secure.
(+) TimeStampEventCallback_S : RTC TimeStamp Event callback secure.
(+) WakeUpTimerEventCallback_S : RTC WakeUpTimer Event callback secure.
(+) Tamper1EventCallback_S : RTC Tamper 1 Event callback secure.
(+) Tamper2EventCallback_S : RTC Tamper 2 Event callback secure.
(+) Tamper3EventCallback_S : RTC Tamper 3 Event callback secure.
(+) Tamper4EventCallback_S : RTC Tamper 4 Event callback secure.
(+) Tamper5EventCallback_S : RTC Tamper 5 Event callback secure.
(+) Tamper6EventCallback_S : RTC Tamper 6 Event callback secure.
(+) Tamper7EventCallback_S : RTC Tamper 7 Event callback secure.
(+) Tamper8EventCallback_S : RTC Tamper 8 Event callback secure.
(+) InternalTamper1EventCallback_S : RTC Internal Tamper 1 Event callback secure.
(+) InternalTamper2EventCallback_S : RTC Internal Tamper 2 Event callback secure.
(+) InternalTamper3EventCallback_S : RTC Internal Tamper 3 Event callback secure.
(+) InternalTamper4EventCallback_S : RTC Internal Tamper 4 Event callback secure.
(+) InternalTamper5EventCallback_S : RTC Internal Tamper 5 Event callback secure.
(+) InternalTamper6EventCallback_S : RTC Internal Tamper 6 Event callback secure.
(+) InternalTamper8EventCallback_S : RTC Internal Tamper 8 Event callback secure.
#endif
(+) MspInitCallback : RTC MspInit callback.
(+) MspDeInitCallback : RTC MspDeInit callback.
[..]
By default, after the HAL_RTC_Init() and when the state is HAL_RTC_STATE_RESET,
all callbacks are set to the corresponding weak functions :
examples AlarmAEventCallback(), TimeStampEventCallback().
Exception done for MspInit and MspDeInit callbacks that are reset to the legacy weak function
in the HAL_RTC_Init()/HAL_RTC_DeInit() only when these callbacks are null
(not registered beforehand).
If not, MspInit or MspDeInit are not null, HAL_RTC_Init()/HAL_RTC_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
[..]
Callbacks can be registered/unregistered in HAL_RTC_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_RTC_STATE_READY or HAL_RTC_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_RTC_RegisterCallback() before calling HAL_RTC_DeInit()
or HAL_RTC_Init() function.
[..]
When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available and all callbacks
are set to the corresponding weak functions.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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_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));
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
if (hrtc->State == HAL_RTC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hrtc->Lock = HAL_UNLOCKED;
hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */
hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; /* Legacy weak AlarmBEventCallback */
hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */
hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; /* Legacy weak WakeUpTimerEventCallback */
hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; /* Legacy weak Tamper1EventCallback */
hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; /* Legacy weak Tamper2EventCallback */
#if (RTC_TAMP_NB == 3)
hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; /* Legacy weak Tamper3EventCallback */
#endif /* RTC_TAMP_NB */
#ifdef RTC_TAMP_INT_1_SUPPORT
hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; /*!< Legacy weak InternalTamper1EventCallback */
#endif /* RTC_TAMP_INT_1_SUPPORT */
#ifdef RTC_TAMP_INT_2_SUPPORT
hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; /*!< Legacy weak InternalTamper2EventCallback */
#endif /* RTC_TAMP_INT_2_SUPPORT */
hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; /*!< Legacy weak InternalTamper3EventCallback */
hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; /*!< Legacy weak InternalTamper4EventCallback */
hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; /*!< Legacy weak InternalTamper5EventCallback */
#ifdef RTC_TAMP_INT_6_SUPPORT
hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; /*!< Legacy weak InternalTamper6EventCallback */
#endif /* RTC_TAMP_INT_6_SUPPORT */
#ifdef RTC_TAMP_INT_7_SUPPORT
hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; /*!< Legacy weak InternalTamper7EventCallback */
#endif /* RTC_TAMP_INT_7_SUPPORT */
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(hrtc->Instance->CR, (RTC_CR_FMT | RTC_CR_POL | RTC_CR_OSEL | RTC_CR_TAMPOE));
/* Set RTC_CR register */
SET_BIT(hrtc->Instance->CR, (hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity));
/* Configure the RTC PRER */
WRITE_REG(hrtc->Instance->PRER, ((hrtc->Init.SynchPrediv) | (hrtc->Init.AsynchPrediv << RTC_PRER_PREDIV_A_Pos)));
/* Exit Initialization mode */
status = RTC_ExitInitMode(hrtc);
if (status == HAL_OK)
{
MODIFY_REG(hrtc->Instance->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);
status = RTC_EnterInitMode(hrtc);
/* Set Initialization mode */
if (status != HAL_OK)
{
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
}
else
{
/* Reset all RTC CR register bits */
CLEAR_REG(hrtc->Instance->CR);
WRITE_REG(hrtc->Instance->DR, (uint32_t)(RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0));
CLEAR_REG(hrtc->Instance->TR);
WRITE_REG(hrtc->Instance->WUTR, RTC_WUTR_WUT);
WRITE_REG(hrtc->Instance->PRER, ((uint32_t)(RTC_PRER_PREDIV_A | 0xFFU)));
CLEAR_REG(hrtc->Instance->ALRMAR);
CLEAR_REG(hrtc->Instance->ALRMBR);
CLEAR_REG(hrtc->Instance->SHIFTR);
CLEAR_REG(hrtc->Instance->CALR);
CLEAR_REG(hrtc->Instance->ALRMASSR);
CLEAR_REG(hrtc->Instance->ALRMBSSR);
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CITSF | RTC_SCR_CTSOVF | RTC_SCR_CTSF | RTC_SCR_CWUTF | RTC_SCR_CALRBF | RTC_SCR_CALRAF);
/* Exit initialization mode */
CLEAR_BIT(hrtc->Instance->ICSR, RTC_ICSR_INIT);
status = HAL_RTC_WaitForSynchro(hrtc);
if (status != HAL_OK)
{
hrtc->State = HAL_RTC_STATE_ERROR;
}
else
{
/* Reset TAMP registers */
WRITE_REG(TAMP->CR1, RTC_INT_TAMPER_ALL);
CLEAR_REG(TAMP->CR2);
CLEAR_REG(TAMP->FLTCR);
}
}
/* 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_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID
* @arg @ref HAL_RTC_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_TAMPER1_EVENT_CB_ID :
hrtc->Tamper1EventCallback = pCallback;
break;
case HAL_RTC_TAMPER2_EVENT_CB_ID :
hrtc->Tamper2EventCallback = pCallback;
break;
#if (RTC_TAMP_NB == 3)
case HAL_RTC_TAMPER3_EVENT_CB_ID :
hrtc->Tamper3EventCallback = pCallback;
break;
#endif /* RTC_TAMP_NB */
#ifdef RTC_TAMP_INT_1_SUPPORT
case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID :
hrtc->InternalTamper1EventCallback = pCallback;
break;
#endif /* RTC_TAMP_INT_1_SUPPORT */
#ifdef RTC_TAMP_INT_2_SUPPORT
case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID :
hrtc->InternalTamper2EventCallback = pCallback;
break;
#endif /* RTC_TAMP_INT_2_SUPPORT */
case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID :
hrtc->InternalTamper3EventCallback = pCallback;
break;
case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID :
hrtc->InternalTamper4EventCallback = pCallback;
break;
case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID :
hrtc->InternalTamper5EventCallback = pCallback;
break;
#ifdef RTC_TAMP_INT_6_SUPPORT
case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID :
hrtc->InternalTamper6EventCallback = pCallback;
break;
#endif /* RTC_TAMP_INT_6_SUPPORT */
#ifdef RTC_TAMP_INT_7_SUPPORT
case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID :
hrtc->InternalTamper7EventCallback = pCallback;
break;
#endif /* RTC_TAMP_INT_7_SUPPORT */
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:
* @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_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID
* @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID
* @arg @ref HAL_RTC_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 :
hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */
break;
case HAL_RTC_ALARM_B_EVENT_CB_ID :
hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; /* Legacy weak AlarmBEventCallback */
break;
case HAL_RTC_TIMESTAMP_EVENT_CB_ID :
hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */
break;
case HAL_RTC_WAKEUPTIMER_EVENT_CB_ID :
hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; /* Legacy weak WakeUpTimerEventCallback */
break;
case HAL_RTC_TAMPER1_EVENT_CB_ID :
hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; /* Legacy weak Tamper1EventCallback */
break;
case HAL_RTC_TAMPER2_EVENT_CB_ID :
hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; /* Legacy weak Tamper2EventCallback */
break;
#if (RTC_TAMP_NB == 3)
case HAL_RTC_TAMPER3_EVENT_CB_ID :
hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; /* Legacy weak Tamper3EventCallback */
break;
#endif /* RTC_TAMP_NB */
#ifdef RTC_TAMP_INT_1_SUPPORT
case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID :
hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; /* Legacy weak InternalTamper1EventCallback */
break;
#endif /* RTC_TAMP_INT_1_SUPPORT */
#ifdef RTC_TAMP_INT_2_SUPPORT
case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID :
hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; /* Legacy weak InternalTamper2EventCallback */
break;
#endif /* RTC_TAMP_INT_2_SUPPORT */
case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID :
hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; /* Legacy weak InternalTamper3EventCallback */
break;
case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID :
hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; /* Legacy weak InternalTamper4EventCallback */
break;
case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID :
hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; /* Legacy weak InternalTamper5EventCallback */
break;
#ifdef RTC_TAMP_INT_6_SUPPORT
case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID :
hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; /* Legacy weak InternalTamper6EventCallback */
break;
#endif /* RTC_TAMP_INT_6_SUPPORT */
#ifdef RTC_TAMP_INT_7_SUPPORT
case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID :
hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; /* Legacy weak InternalTamper7EventCallback */
break;
#endif /* RTC_TAMP_INT_7_SUPPORT */
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
* @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_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t tmpreg;
HAL_StatusTypeDef status;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
assert_param(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving));
assert_param(IS_RTC_STORE_OPERATION(sTime->StoreOperation));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Enter Initialization mode */
status = RTC_EnterInitMode(hrtc);
if (status == HAL_OK)
{
if (Format == RTC_FORMAT_BIN)
{
if (READ_BIT(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->TR, (tmpreg & RTC_TR_RESERVED_MASK));
/* This interface is deprecated. To manage Daylight Saving Time, please use HAL_RTC_DST_xxx functions */
CLEAR_BIT(hrtc->Instance->CR, RTC_CR_BKP);
/* This interface is deprecated. To manage Daylight Saving Time, please use HAL_RTC_DST_xxx functions */
SET_BIT(hrtc->Instance->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;
}
__HAL_UNLOCK(hrtc);
return status;
}
/**
* @brief Get RTC current time.
* @note You can use SubSeconds and SecondFraction (sTime structure fields returned) to convert SubSeconds
* value in second fraction ratio with time unit following generic formula:
* Second fraction ratio * time_unit= [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit
* This conversion can be performed only if no shift operation is pending (ie. SHFP=0) when PREDIV_S >= SS
* @note You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values
* in the higher-order calendar shadow registers to ensure consistency between the time and date values.
* Reading RTC current time locks the values in calendar shadow registers until Current date is read
* to ensure consistency between the time and date values.
* @param hrtc RTC handle
* @param sTime 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 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_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t tmpreg;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get subseconds structure field from the corresponding register*/
sTime->SubSeconds = READ_REG(hrtc->Instance->SSR);
/* Get SecondFraction structure field from the corresponding register field*/
sTime->SecondFraction = (uint32_t)(READ_REG(hrtc->Instance->PRER) & RTC_PRER_PREDIV_S);
/* Get the TR register */
tmpreg = (uint32_t)(READ_REG(hrtc->Instance->TR) & RTC_TR_RESERVED_MASK);
/* Fill the structure fields with the read parameters */
sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 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 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_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(hrtc->Instance->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 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_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
uint32_t datetmpreg;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get the DR register */
datetmpreg = (uint32_t)(READ_REG(hrtc->Instance->DR) & RTC_DR_RESERVED_MASK);
/* Fill the structure fields with the read parameters */
sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> 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
* @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_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
uint32_t tickstart;
uint32_t tmpreg;
uint32_t subsecondtmpreg;
/* Check the parameters */
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));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if (Format == RTC_FORMAT_BIN)
{
if (READ_BIT(hrtc->Instance->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));
#ifdef USE_FULL_ASSERT
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));
}
#endif /* USE_FULL_ASSERT*/
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(hrtc->Instance->CR, RTC_CR_FMT) != 0U)
{
assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
}
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
#ifdef USE_FULL_ASSERT
if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay)));
}
else
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay)));
}
#endif /* USE_FULL_ASSERT */
tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \
((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
/* Configure the Alarm A or Alarm B Sub Second registers */
subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Alarm register */
if (sAlarm->Alarm == RTC_ALARM_A)
{
/* Disable the Alarm A interrupt */
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_ALRAE | RTC_CR_ALRAIE));
/* Clear flag alarm A */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CALRAF);
tickstart = HAL_GetTick();
/* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRAWF) == 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;
}
}
WRITE_REG(hrtc->Instance->ALRMAR, tmpreg);
/* Configure the Alarm A Sub Second register */
WRITE_REG(hrtc->Instance->ALRMASSR, subsecondtmpreg);
/* Configure the Alarm state: Enable Alarm */
SET_BIT(hrtc->Instance->CR, RTC_CR_ALRAE);
}
else
{
/* Disable the Alarm B interrupt */
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_ALRBE | RTC_CR_ALRBIE));
/* Clear flag alarm B */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CALRBF);
tickstart = HAL_GetTick();
/* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRBWF) == 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;
}
}
WRITE_REG(hrtc->Instance->ALRMBR, tmpreg);
/* Configure the Alarm B Sub Second register */
WRITE_REG(hrtc->Instance->ALRMBSSR, subsecondtmpreg);
/* Configure the Alarm state: Enable Alarm */
SET_BIT(hrtc->Instance->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.
* @note The Alarm register can only be written when the corresponding Alarm
* is disabled (Use the HAL_RTC_DeactivateAlarm()).
* @note The HAL_RTC_SetTime() must be called before enabling the Alarm feature.
* @param hrtc RTC handle
* @param sAlarm Pointer to Alarm structure
* @param Format Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
uint32_t tickstart;
uint32_t tmpreg;
uint32_t subsecondtmpreg;
/* Check the parameters */
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));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if (Format == RTC_FORMAT_BIN)
{
if (READ_BIT(hrtc->Instance->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));
#ifdef USE_FULL_ASSERT
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));
}
#endif /* USE_FULL_ASSERT */
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(hrtc->Instance->CR, RTC_CR_FMT) != 0U)
{
assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
}
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
#ifdef USE_FULL_ASSERT
if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay)));
}
else
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay)));
}
#endif /* USE_FULL_ASSERT */
tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \
((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
/* Configure the Alarm A or Alarm B Sub Second registers */
subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Alarm register */
if (sAlarm->Alarm == RTC_ALARM_A)
{
/* Disable the Alarm A interrupt */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_ALRAE | RTC_CR_ALRAIE));
/* Clear flag alarm A */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CALRAF);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
tickstart = HAL_GetTick();
/* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRAWF) == 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;
}
}
WRITE_REG(hrtc->Instance->ALRMAR, tmpreg);
/* Configure the Alarm A Sub Second register */
WRITE_REG(hrtc->Instance->ALRMASSR, subsecondtmpreg);
/* Configure the Alarm interrupt : Enable Alarm */
SET_BIT(hrtc->Instance->CR, (RTC_CR_ALRAE | RTC_CR_ALRAIE));
}
else
{
/* Disable the Alarm B interrupt */
CLEAR_BIT(hrtc->Instance->CR, (RTC_CR_ALRBE | RTC_CR_ALRBIE));
/* Clear flag alarm B */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CALRBF);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
tickstart = HAL_GetTick();
/* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRBWF) == 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;
}
}
WRITE_REG(hrtc->Instance->ALRMBR, tmpreg);
/* Configure the Alarm B Sub Second register */
WRITE_REG(hrtc->Instance->ALRMBSSR, subsecondtmpreg);
/* Configure the Alarm B interrupt : Enable Alarm */
SET_BIT(hrtc->Instance->CR, (RTC_CR_ALRBE | RTC_CR_ALRBIE));
}
/* RTC Alarm Interrupt Configuration: EXTI configuration */
__HAL_RTC_ALARM_EXTI_ENABLE_IT();
__HAL_RTC_ALARM_EXTI_RISING_IT();
/* 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 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)
{
uint32_t tickstart;
/* 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);
if (Alarm == RTC_ALARM_A)
{
/* AlarmA */
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(hrtc->Instance->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
tickstart = HAL_GetTick();
/* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRAWF) == 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;
}
}
}
else
{
/* AlarmB */
/* In case of interrupt mode is used, the interrupt source must disabled */
CLEAR_BIT(hrtc->Instance->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
tickstart = HAL_GetTick();
/* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
while (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_ALRBWF) == 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 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 data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format)
{
uint32_t tmpreg, subsecondtmpreg;
/* 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(hrtc->Instance->ALRMAR);
subsecondtmpreg = (uint32_t)(READ_REG(hrtc->Instance->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(hrtc->Instance->ALRMBR);
subsecondtmpreg = (uint32_t)(READ_REG(hrtc->Instance->ALRMBSSR) & RTC_ALRMBSSR_SS);
/* Fill the structure with the read parameters */
sAlarm->AlarmTime.Hours = (uint8_t)((tmpreg & (RTC_ALRMBR_HT | RTC_ALRMBR_HU)) >> RTC_ALRMBR_HU_Pos);
sAlarm->AlarmTime.Minutes = (uint8_t)((tmpreg & (RTC_ALRMBR_MNT | RTC_ALRMBR_MNU)) >> RTC_ALRMBR_MNU_Pos);
sAlarm->AlarmTime.Seconds = (uint8_t)((tmpreg & (RTC_ALRMBR_ST | RTC_ALRMBR_SU)) >> RTC_ALRMBR_SU_Pos);
sAlarm->AlarmTime.TimeFormat = (uint8_t)((tmpreg & RTC_ALRMBR_PM) >> RTC_ALRMBR_PM_Pos);
sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg;
sAlarm->AlarmDateWeekDay = (uint8_t)((tmpreg & (RTC_ALRMBR_DT | RTC_ALRMBR_DU)) >> RTC_ALRMBR_DU_Pos);
sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMBR_WDSEL);
sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL);
}
if (Format == RTC_FORMAT_BIN)
{
sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes);
sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds);
sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
}
return HAL_OK;
}
/**
* @brief Handle Alarm interrupt request.
* @param hrtc RTC handle
* @retval None
*/
void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc)
{
/* Get interrupt status */
uint32_t tmp = READ_REG(hrtc->Instance->MISR);
if ((tmp & RTC_MISR_ALRAMF) != 0U)
{
/* Clear the AlarmA interrupt pending bit */
WRITE_REG(hrtc->Instance->SCR, RTC_SCR_CALRAF);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
#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(hrtc->Instance->SCR, RTC_SCR_CALRBF);
__HAL_RTC_ALARM_EXTI_CLEAR_IT();
#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
/* Call Compare Match registered Callback */
hrtc->AlarmBEventCallback(hrtc);
#else
HAL_RTCEx_AlarmBEventCallback(hrtc);
#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
}
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
/**
* @brief Alarm A callback.
* @param hrtc RTC handle
* @retval None
*/
__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTC_AlarmAEventCallback could be implemented in the user file
*/
}
/**
* @brief Handle 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(hrtc->Instance->SR, RTC_SR_ALRAF) == 0U)
{
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Clear the Alarm interrupt pending bit */
WRITE_REG(hrtc->Instance->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;
/* Clear RSF flag */
CLEAR_BIT(hrtc->Instance->ICSR, RTC_ICSR_RSF);
tickstart = HAL_GetTick();
/* Wait the registers to be synchronised */
while (READ_BIT(hrtc->Instance->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;
/* Check if the Initialization mode is set */
if (READ_BIT(hrtc->Instance->ICSR, RTC_ICSR_INITF) == 0U)
{
/* Set the Initialization mode */
SET_BIT(hrtc->Instance->ICSR, RTC_ICSR_INIT);
tickstart = HAL_GetTick();
/* Wait till RTC is in INIT state and if Time out is reached exit */
while ((READ_BIT(hrtc->Instance->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(hrtc->Instance->ICSR, RTC_ICSR_INIT);
/* If CR_BYPSHAD bit = 0, wait for synchro */
if (READ_BIT(hrtc->Instance->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(hrtc->Instance->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(hrtc->Instance->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));
}
/**
* @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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(hrtc->Instance->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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(hrtc->Instance->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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
SET_BIT(hrtc->Instance->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)
{
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
CLEAR_BIT(hrtc->Instance->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)
{
return READ_BIT(hrtc->Instance->CR, RTC_CR_BKP);
}
/**
* @}
*/
#endif /* HAL_RTC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 74,049 |
C
| 35.477832 | 144 | 0.632298 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_spi.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_spi.c
* @author MCD Application Team
* @brief SPI LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_spi.h"
#include "stm32g4xx_ll_bus.h"
#include "stm32g4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4)
/** @addtogroup SPI_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup SPI_LL_Private_Constants SPI Private Constants
* @{
*/
/* SPI registers Masks */
#define SPI_CR1_CLEAR_MASK (SPI_CR1_CPHA | SPI_CR1_CPOL | SPI_CR1_MSTR | \
SPI_CR1_BR | SPI_CR1_LSBFIRST | SPI_CR1_SSI | \
SPI_CR1_SSM | SPI_CR1_RXONLY | SPI_CR1_CRCL | \
SPI_CR1_CRCNEXT | SPI_CR1_CRCEN | SPI_CR1_BIDIOE | \
SPI_CR1_BIDIMODE)
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup SPI_LL_Private_Macros SPI Private Macros
* @{
*/
#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \
|| ((__VALUE__) == LL_SPI_SIMPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX))
#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \
|| ((__VALUE__) == LL_SPI_MODE_SLAVE))
#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))
#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \
|| ((__VALUE__) == LL_SPI_POLARITY_HIGH))
#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \
|| ((__VALUE__) == LL_SPI_PHASE_2EDGE))
#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_BAUDRATE(__VALUE__) (((__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_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \
|| ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE))
#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1U)
/**
* @}
*/
/* 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);
status = SUCCESS;
}
#endif /* SPI1 */
#if defined(SPI2)
if (SPIx == SPI2)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2);
status = SUCCESS;
}
#endif /* SPI2 */
#if defined(SPI3)
if (SPIx == SPI3)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3);
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);
status = SUCCESS;
}
#endif /* SPI4 */
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 peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param SPIx SPI Instance
* @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure
* @retval An ErrorStatus enumeration value. (Return always SUCCESS)
*/
ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct)
{
ErrorStatus status = ERROR;
/* 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_BAUDRATE(SPI_InitStruct->BaudRate));
assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder));
assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation));
if (LL_SPI_IsEnabled(SPIx) == 0x00000000U)
{
/*---------------------------- SPIx CR1 Configuration ------------------------
* Configure SPIx CR1 with parameters:
* - TransferDirection: SPI_CR1_BIDIMODE, SPI_CR1_BIDIOE and SPI_CR1_RXONLY bits
* - Master/Slave Mode: SPI_CR1_MSTR bit
* - ClockPolarity: SPI_CR1_CPOL bit
* - ClockPhase: SPI_CR1_CPHA bit
* - NSS management: SPI_CR1_SSM bit
* - BaudRate prescaler: SPI_CR1_BR[2:0] bits
* - BitOrder: SPI_CR1_LSBFIRST bit
* - CRCCalculation: SPI_CR1_CRCEN bit
*/
MODIFY_REG(SPIx->CR1,
SPI_CR1_CLEAR_MASK,
SPI_InitStruct->TransferDirection | SPI_InitStruct->Mode |
SPI_InitStruct->ClockPolarity | SPI_InitStruct->ClockPhase |
SPI_InitStruct->NSS | SPI_InitStruct->BaudRate |
SPI_InitStruct->BitOrder | SPI_InitStruct->CRCCalculation);
/*---------------------------- SPIx CR2 Configuration ------------------------
* Configure SPIx CR2 with parameters:
* - DataWidth: DS[3:0] bits
* - NSS management: SSOE bit
*/
MODIFY_REG(SPIx->CR2,
SPI_CR2_DS | SPI_CR2_SSOE,
SPI_InitStruct->DataWidth | (SPI_InitStruct->NSS >> 16U));
/* Set Rx FIFO to Quarter (1 Byte) in case of 8 Bits mode. No DataPacking by default */
if (SPI_InitStruct->DataWidth < LL_SPI_DATAWIDTH_9BIT)
{
LL_SPI_SetRxFIFOThreshold(SPIx, LL_SPI_RX_FIFO_TH_QUARTER);
}
/*---------------------------- SPIx CRCPR Configuration ----------------------
* Configure SPIx CRCPR with parameters:
* - CRCPoly: CRCPOLY[15: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;
}
#if defined (SPI_I2S_SUPPORT)
/* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */
CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD);
#endif /* SPI_I2S_SUPPORT */
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 = 7U;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#if defined(SPI_I2S_SUPPORT)
/** @addtogroup I2S_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Constants I2S Private Constants
* @{
*/
/* I2S registers Masks */
#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \
SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD | \
SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD )
#define I2S_I2SPR_CLEAR_MASK 0x0002U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Macros I2S Private Macros
* @{
*/
#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_32B))
#define IS_LL_I2S_CPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \
|| ((__VALUE__) == LL_I2S_POLARITY_HIGH))
#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \
|| ((__VALUE__) == LL_I2S_STANDARD_MSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_LSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG))
#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \
|| ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_RX))
#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \
|| ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE))
#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \
&& ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \
|| ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT))
#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) >= 0x2U)
#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \
|| ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup I2S_LL_Exported_Functions
* @{
*/
/** @addtogroup I2S_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the SPI/I2S registers to their default reset values.
* @param SPIx SPI Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are de-initialized
* - ERROR: SPI registers are not de-initialized
*/
ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx)
{
return LL_SPI_DeInit(SPIx);
}
/**
* @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct.
* @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0),
* SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param SPIx SPI Instance
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are Initialized
* - ERROR: SPI registers are not Initialized
*/
ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct)
{
uint32_t i2sdiv = 2U;
uint32_t i2sodd = 0U;
uint32_t packetlength = 1U;
uint32_t tmp;
uint32_t sourceclock;
ErrorStatus status = ERROR;
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode));
assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard));
assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat));
assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput));
assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq));
assert_param(IS_LL_I2S_CPOL(I2S_InitStruct->ClockPolarity));
if (LL_I2S_IsEnabled(SPIx) == 0x00000000U)
{
/*---------------------------- SPIx I2SCFGR Configuration --------------------
* Configure SPIx I2SCFGR with parameters:
* - Mode: SPI_I2SCFGR_I2SCFG[1:0] bit
* - Standard: SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits
* - DataFormat: SPI_I2SCFGR_CHLEN and SPI_I2SCFGR_DATLEN bits
* - ClockPolarity: SPI_I2SCFGR_CKPOL bit
*/
/* Write to SPIx I2SCFGR */
MODIFY_REG(SPIx->I2SCFGR,
I2S_I2SCFGR_CLEAR_MASK,
I2S_InitStruct->Mode | I2S_InitStruct->Standard |
I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity |
SPI_I2SCFGR_I2SMOD);
/*---------------------------- SPIx I2SPR Configuration ----------------------
* Configure SPIx I2SPR with parameters:
* - MCLKOutput: SPI_I2SPR_MCKOE bit
* - AudioFreq: SPI_I2SPR_I2SDIV[7:0] and SPI_I2SPR_ODD bits
*/
/* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv)
* else, default values are used: i2sodd = 0U, i2sdiv = 2U.
*/
if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT)
{
/* Check the frame length (For the Prescaler computing)
* Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U).
*/
if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B)
{
/* Packet length is 32 bits */
packetlength = 2U;
}
/* If an external I2S clock has to be used, the specific define should be set
in the project configuration or in the stm32g4xx_ll_rcc.h file */
/* Get the I2S source clock value */
sourceclock = LL_RCC_GetI2SClockFreq(LL_RCC_I2S_CLKSOURCE);
/* Compute the Real divider depending on the MCLK output state with a floating point */
if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE)
{
/* MCLK output is enabled */
tmp = (((((sourceclock / 256U) * 10U) / I2S_InitStruct->AudioFreq)) + 5U);
}
else
{
/* MCLK output is disabled */
tmp = (((((sourceclock / (32U * packetlength)) * 10U) / I2S_InitStruct->AudioFreq)) + 5U);
}
/* Remove the floating point */
tmp = tmp / 10U;
/* Check the parity of the divider */
i2sodd = (tmp & (uint16_t)0x0001U);
/* Compute the i2sdiv prescaler */
i2sdiv = ((tmp - i2sodd) / 2U);
/* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */
i2sodd = (i2sodd << 8U);
}
/* Test if the divider is 1 or 0 or greater than 0xFF */
if ((i2sdiv < 2U) || (i2sdiv > 0xFFU))
{
/* Set the default values */
i2sdiv = 2U;
i2sodd = 0U;
}
/* Write to SPIx I2SPR register the computed value */
WRITE_REG(SPIx->I2SPR, i2sdiv | i2sodd | I2S_InitStruct->MCLKOutput);
status = SUCCESS;
}
return status;
}
/**
* @brief Set each @ref LL_I2S_InitTypeDef field to default value.
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct)
{
/*--------------- Reset I2S init structure parameters values -----------------*/
I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX;
I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS;
I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B;
I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE;
I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT;
I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW;
}
/**
* @brief Set linear and parity prescaler.
* @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n
* Check Audio frequency table and formulas inside Reference Manual (SPI/I2S).
* @param SPIx SPI Instance
* @param PrescalerLinear value Min_Data=0x02 and Max_Data=0xFF.
* @param PrescalerParity This parameter can be one of the following values:
* @arg @ref LL_I2S_PRESCALER_PARITY_EVEN
* @arg @ref LL_I2S_PRESCALER_PARITY_ODD
* @retval None
*/
void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity)
{
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear));
assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity));
/* Write to SPIx I2SPR */
MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV | SPI_I2SPR_ODD, PrescalerLinear | (PrescalerParity << 8U));
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* SPI_I2S_SUPPORT */
#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 21,447 |
C
| 37.437276 | 125 | 0.528466 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_sai.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 SAI clock source is configured:
(+@) SYSCLK or
(+@) PLLQ output or
(+@) HSI or
(+@) External clock source which is configured after setting correctly
the define constant EXTERNAL_CLOCK_VALUE in the stm32g4xx_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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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;
}
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);
}
/* 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))
{
/* No need to check the returned value of HAL_DMA_Abort. */
/* Only HAL_DMA_ERROR_NO_XFER can be returned in case of error and it's not an error for SAI. */
(void) HAL_DMA_Abort(hsai->hdmatx);
}
/* Abort the SAI Rx DMA Stream */
if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL))
{
/* No need to check the returned value of HAL_DMA_Abort. */
/* Only HAL_DMA_ERROR_NO_XFER can be returned in case of error and it's not an error for SAI. */
(void) HAL_DMA_Abort(hsai->hdmarx);
}
/* 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))
{
/* No need to check the returned value of HAL_DMA_Abort. */
/* Only HAL_DMA_ERROR_NO_XFER can be returned in case of error and it's not an error for SAI. */
(void) HAL_DMA_Abort(hsai->hdmatx);
}
/* Abort the SAI Rx DMA Stream */
if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL))
{
/* No need to check the returned value of HAL_DMA_Abort. */
/* Only HAL_DMA_ERROR_NO_XFER can be returned in case of error and it's not an error for SAI. */
(void) HAL_DMA_Abort(hsai->hdmarx);
}
}
/* 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)
{
uint32_t tickstart = HAL_GetTick();
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;
/* 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;
/* Enable the Tx DMA Stream */
if (HAL_DMA_Start_IT(hsai->hdmatx, (uint32_t)hsai->pBuffPtr, (uint32_t)&hsai->Instance->DR, hsai->XferSize) != 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)
{
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;
/* 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;
/* Enable the Rx DMA Stream */
if (HAL_DMA_Start_IT(hsai->hdmarx, (uint32_t)&hsai->Instance->DR, (uint32_t)hsai->pBuffPtr, hsai->XferSize) != 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;
if (hdma->Init.Mode != DMA_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;
if (hdma->Init.Mode != DMA_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 */
/**
* @}
*/
/**
* @}
*/
| 88,484 |
C
| 30.944043 | 133 | 0.612981 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_iwdg.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_iwdg.c
* @author MCD Application Team
* @brief IWDG HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Independent Watchdog (IWDG) peripheral:
* + Initialization and Start functions
* + IO operation functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### IWDG Generic features #####
==============================================================================
[..]
(+) The IWDG can be started by either software or hardware (configurable
through option byte).
(+) The IWDG is clocked by the Low-Speed Internal clock (LSI) and thus stays
active even if the main clock fails.
(+) Once the IWDG is started, the LSI is forced ON and both cannot be
disabled. The counter starts counting down from the reset value (0xFFF).
When it reaches the end of count value (0x000) a reset signal is
generated (IWDG reset).
(+) Whenever the key value 0x0000 AAAA is written in the IWDG_KR register,
the IWDG_RLR value is reloaded into the counter and the watchdog reset
is prevented.
(+) The IWDG is implemented in the VDD voltage domain that is still functional
in STOP and STANDBY mode (IWDG reset can wake up the CPU from STANDBY).
IWDGRST flag in RCC_CSR register can be used to inform when an IWDG
reset occurs.
(+) Debug mode: When the microcontroller enters debug mode (core halted),
the IWDG counter either continues to work normally or stops, depending
on DBG_IWDG_STOP configuration bit in DBG module, accessible through
__HAL_DBGMCU_FREEZE_IWDG() and __HAL_DBGMCU_UNFREEZE_IWDG() macros.
[..] Min-max timeout value @32KHz (LSI): ~125us / ~32.7s
The IWDG timeout may vary due to LSI clock frequency dispersion.
STM32G4xx devices provide the capability to measure the LSI clock
frequency (LSI clock is internally connected to TIM16 CH1 input capture).
The measured value can be used to have an IWDG timeout with an
acceptable accuracy.
[..] Default timeout value (necessary for IWDG_SR status register update):
Constant LSI_VALUE is defined based on the nominal LSI clock frequency.
This frequency being subject to variations as mentioned above, the
default timeout value (defined through constant HAL_IWDG_DEFAULT_TIMEOUT
below) may become too short or too long.
In such cases, this default timeout value can be tuned by redefining
the constant LSI_VALUE at user-application level (based, for instance,
on the measured LSI clock frequency as explained above).
##### How to use this driver #####
==============================================================================
[..]
(#) Use IWDG using HAL_IWDG_Init() function to :
(++) Enable instance by writing Start keyword in IWDG_KEY register. LSI
clock is forced ON and IWDG counter starts counting down.
(++) Enable write access to configuration registers:
IWDG_PR, IWDG_RLR and IWDG_WINR.
(++) Configure the IWDG prescaler and counter reload value. This reload
value will be loaded in the IWDG counter each time the watchdog is
reloaded, then the IWDG will start counting down from this value.
(++) Depending on window parameter:
(+++) If Window Init parameter is same as Window register value,
nothing more is done but reload counter value in order to exit
function with exact time base.
(+++) Else modify Window register. This will automatically reload
watchdog counter.
(++) Wait for status flags to be reset.
(#) Then the application program must refresh the IWDG counter at regular
intervals during normal operation to prevent an MCU reset, using
HAL_IWDG_Refresh() function.
*** IWDG HAL driver macros list ***
====================================
[..]
Below the list of most used macros in IWDG HAL driver:
(+) __HAL_IWDG_START: Enable the IWDG peripheral
(+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in
the reload register
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_IWDG_MODULE_ENABLED
/** @addtogroup IWDG
* @brief IWDG HAL module driver.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IWDG_Private_Defines IWDG Private Defines
* @{
*/
/* Status register needs up to 5 LSI clock periods divided by the clock
prescaler to be updated. The number of LSI clock periods is upper-rounded to
6 for the timeout value calculation.
The timeout value is calculated using the highest prescaler (256) and
the LSI_VALUE constant. The value of this constant can be changed by the user
to take into account possible LSI clock period variations.
The timeout value is multiplied by 1000 to be converted in milliseconds.
LSI startup time is also considered here by adding LSI_STARTUP_TIME
converted in milliseconds. */
#define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL))
#define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_WVU | IWDG_SR_RVU | IWDG_SR_PVU)
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup IWDG_Exported_Functions
* @{
*/
/** @addtogroup IWDG_Exported_Functions_Group1
* @brief Initialization and Start functions.
*
@verbatim
===============================================================================
##### Initialization and Start functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize the IWDG according to the specified parameters in the
IWDG_InitTypeDef of associated handle.
(+) Manage Window option.
(+) Once initialization is performed in HAL_IWDG_Init function, Watchdog
is reloaded in order to exit function with correct time base.
@endverbatim
* @{
*/
/**
* @brief Initialize the IWDG according to the specified parameters in the
* IWDG_InitTypeDef and start watchdog. Before exiting function,
* watchdog is refreshed in order to have correct time base.
* @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
* the configuration information for the specified IWDG module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
{
uint32_t tickstart;
/* Check the IWDG handle allocation */
if (hiwdg == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance));
assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler));
assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload));
assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window));
/* Enable IWDG. LSI is turned on automatically */
__HAL_IWDG_START(hiwdg);
/* Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers by writing
0x5555 in KR */
IWDG_ENABLE_WRITE_ACCESS(hiwdg);
/* Write to IWDG registers the Prescaler & Reload values to work with */
hiwdg->Instance->PR = hiwdg->Init.Prescaler;
hiwdg->Instance->RLR = hiwdg->Init.Reload;
/* Check pending flag, if previous update not done, return timeout */
tickstart = HAL_GetTick();
/* Wait for register to be updated */
while ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
{
if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT)
{
if ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
{
return HAL_TIMEOUT;
}
}
}
/* If window parameter is different than current value, modify window
register */
if (hiwdg->Instance->WINR != hiwdg->Init.Window)
{
/* Write to IWDG WINR the IWDG_Window value to compare with. In any case,
even if window feature is disabled, Watchdog will be reloaded by writing
windows register */
hiwdg->Instance->WINR = hiwdg->Init.Window;
}
else
{
/* Reload IWDG counter with value defined in the reload register */
__HAL_IWDG_RELOAD_COUNTER(hiwdg);
}
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @addtogroup IWDG_Exported_Functions_Group2
* @brief IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Refresh the IWDG.
@endverbatim
* @{
*/
/**
* @brief Refresh the IWDG.
* @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
* the configuration information for the specified IWDG module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
{
/* Reload IWDG counter with value defined in the reload register */
__HAL_IWDG_RELOAD_COUNTER(hiwdg);
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_IWDG_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 10,515 |
C
| 36.15901 | 116 | 0.5864 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_i2c_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_i2c_ex.c
* @author MCD Application Team
* @brief I2C Extended HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of I2C Extended peripheral:
* + Filter Mode Functions
* + WakeUp Mode Functions
* + FastModePlus Functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### I2C peripheral Extended features #####
==============================================================================
[..] Comparing to other previous devices, the I2C interface for STM32G4xx
devices contains the following additional features
(+) Possibility to disable or enable Analog Noise Filter
(+) Use of a configured Digital Noise Filter
(+) Disable or enable wakeup from Stop mode(s)
(+) Disable or enable Fast Mode Plus
##### How to use this driver #####
==============================================================================
[..] This driver provides functions to configure Noise Filter and Wake Up Feature
(#) Configure I2C Analog noise filter using the function HAL_I2CEx_ConfigAnalogFilter()
(#) Configure I2C Digital noise filter using the function HAL_I2CEx_ConfigDigitalFilter()
(#) Configure the enable or disable of I2C Wake Up Mode using the functions :
(++) HAL_I2CEx_EnableWakeUp()
(++) HAL_I2CEx_DisableWakeUp()
(#) Configure the enable or disable of fast mode plus driving capability using the functions :
(++) HAL_I2CEx_EnableFastModePlus()
(++) HAL_I2CEx_DisableFastModePlus()
@endverbatim
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup I2CEx I2CEx
* @brief I2C Extended HAL module driver
* @{
*/
#ifdef HAL_I2C_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup I2CEx_Exported_Functions I2C Extended Exported Functions
* @{
*/
/** @defgroup I2CEx_Exported_Functions_Group1 Filter Mode Functions
* @brief Filter Mode Functions
*
@verbatim
===============================================================================
##### Filter Mode Functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure Noise Filters
@endverbatim
* @{
*/
/**
* @brief Configure I2C Analog noise filter.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2Cx peripheral.
* @param AnalogFilter New state of the Analog filter.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter)
{
/* Check the parameters */
assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the selected I2C peripheral */
__HAL_I2C_DISABLE(hi2c);
/* Reset I2Cx ANOFF bit */
hi2c->Instance->CR1 &= ~(I2C_CR1_ANFOFF);
/* Set analog filter bit*/
hi2c->Instance->CR1 |= AnalogFilter;
__HAL_I2C_ENABLE(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Configure I2C Digital noise filter.
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2Cx peripheral.
* @param DigitalFilter Coefficient of digital noise filter between Min_Data=0x00 and Max_Data=0x0F.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter)
{
uint32_t tmpreg;
/* Check the parameters */
assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance));
assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the selected I2C peripheral */
__HAL_I2C_DISABLE(hi2c);
/* Get the old register value */
tmpreg = hi2c->Instance->CR1;
/* Reset I2Cx DNF bits [11:8] */
tmpreg &= ~(I2C_CR1_DNF);
/* Set I2Cx DNF coefficient */
tmpreg |= DigitalFilter << 8U;
/* Store the new register value */
hi2c->Instance->CR1 = tmpreg;
__HAL_I2C_ENABLE(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @}
*/
/** @defgroup I2CEx_Exported_Functions_Group2 WakeUp Mode Functions
* @brief WakeUp Mode Functions
*
@verbatim
===============================================================================
##### WakeUp Mode Functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure Wake Up Feature
@endverbatim
* @{
*/
/**
* @brief Enable I2C wakeup from Stop mode(s).
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2Cx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp(I2C_HandleTypeDef *hi2c)
{
/* Check the parameters */
assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the selected I2C peripheral */
__HAL_I2C_DISABLE(hi2c);
/* Enable wakeup from stop mode */
hi2c->Instance->CR1 |= I2C_CR1_WUPEN;
__HAL_I2C_ENABLE(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Disable I2C wakeup from Stop mode(s).
* @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
* the configuration information for the specified I2Cx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c)
{
/* Check the parameters */
assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance));
if (hi2c->State == HAL_I2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->State = HAL_I2C_STATE_BUSY;
/* Disable the selected I2C peripheral */
__HAL_I2C_DISABLE(hi2c);
/* Enable wakeup from stop mode */
hi2c->Instance->CR1 &= ~(I2C_CR1_WUPEN);
__HAL_I2C_ENABLE(hi2c);
hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @}
*/
/** @defgroup I2CEx_Exported_Functions_Group3 Fast Mode Plus Functions
* @brief Fast Mode Plus Functions
*
@verbatim
===============================================================================
##### Fast Mode Plus Functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure Fast Mode Plus
@endverbatim
* @{
*/
/**
* @brief Enable the I2C fast mode plus driving capability.
* @param ConfigFastModePlus Selects the pin.
* This parameter can be one of the @ref I2CEx_FastModePlus values
* @note For I2C1, fast mode plus driving capability can be enabled on all selected
* I2C1 pins using I2C_FASTMODEPLUS_I2C1 parameter or independently
* on each one of the following pins PB6, PB7, PB8 and PB9.
* @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability
* can be enabled only by using I2C_FASTMODEPLUS_I2C1 parameter.
* @note For all I2C2 pins fast mode plus driving capability can be enabled
* only by using I2C_FASTMODEPLUS_I2C2 parameter.
* @note For all I2C3 pins fast mode plus driving capability can be enabled
* only by using I2C_FASTMODEPLUS_I2C3 parameter.
* @note For all I2C4 pins fast mode plus driving capability can be enabled
* only by using I2C_FASTMODEPLUS_I2C4 parameter.
* @retval None
*/
void HAL_I2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus)
{
/* Check the parameter */
assert_param(IS_I2C_FASTMODEPLUS(ConfigFastModePlus));
/* Enable SYSCFG clock */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* Enable fast mode plus driving capability for selected pin */
SET_BIT(SYSCFG->CFGR1, (uint32_t)ConfigFastModePlus);
}
/**
* @brief Disable the I2C fast mode plus driving capability.
* @param ConfigFastModePlus Selects the pin.
* This parameter can be one of the @ref I2CEx_FastModePlus values
* @note For I2C1, fast mode plus driving capability can be disabled on all selected
* I2C1 pins using I2C_FASTMODEPLUS_I2C1 parameter or independently
* on each one of the following pins PB6, PB7, PB8 and PB9.
* @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability
* can be disabled only by using I2C_FASTMODEPLUS_I2C1 parameter.
* @note For all I2C2 pins fast mode plus driving capability can be disabled
* only by using I2C_FASTMODEPLUS_I2C2 parameter.
* @note For all I2C3 pins fast mode plus driving capability can be disabled
* only by using I2C_FASTMODEPLUS_I2C3 parameter.
* @note For all I2C4 pins fast mode plus driving capability can be disabled
* only by using I2C_FASTMODEPLUS_I2C4 parameter.
* @retval None
*/
void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus)
{
/* Check the parameter */
assert_param(IS_I2C_FASTMODEPLUS(ConfigFastModePlus));
/* Enable SYSCFG clock */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* Disable fast mode plus driving capability for selected pin */
CLEAR_BIT(SYSCFG->CFGR1, (uint32_t)ConfigFastModePlus);
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_I2C_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 11,400 |
C
| 29.897019 | 102 | 0.577193 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_opamp.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_opamp.c
* @author MCD Application Team
* @brief OPAMP LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_opamp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) || defined (OPAMP5) || defined (OPAMP6)
/** @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_NORMALSPEED) \
|| ((__POWER_MODE__) == LL_OPAMP_POWERMODE_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) \
|| ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA_IO0) \
|| ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA_IO0_BIAS) \
|| ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA_IO0_IO1_BIAS) \
)
#define IS_LL_OPAMP_INPUT_NONINVERTING(__INPUT_NONINVERTING__) \
( ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO0) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO1) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO2) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO3) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_DAC) \
)
#define IS_LL_OPAMP_INPUT_INVERTING(__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.
* @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 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));
/* Note: Hardware constraint (refer to description of this function): */
/* OPAMP instance must not be locked. */
if (LL_OPAMP_IsLocked(OPAMPx) == 0UL)
{
LL_OPAMP_WriteReg(OPAMPx, CSR, 0x00000000UL);
}
else
{
/* OPAMP instance is locked: de-initialization by software is */
/* not possible. */
/* The only way to unlock the OPAMP is a device hardware reset. */
status = ERROR;
}
/* Timer controlled mux mode register reset */
if (LL_OPAMP_IsTimerMuxLocked(OPAMPx) == 0UL)
{
LL_OPAMP_WriteReg(OPAMPx, TCMR, 0x00000000UL);
}
else if (LL_OPAMP_ReadReg(OPAMPx, TCMR) != 0x80000000UL)
{
/* OPAMP instance timer controlled mux is locked configured, deinit error */
/* The only way to unlock the OPAMP is a device hardware reset. */
status = ERROR;
}
else
{
/* OPAMP instance timer controlled mux is locked unconfigured, deinit OK */
}
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.
* @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)
{
ErrorStatus status = SUCCESS;
/* 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(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(OPAMP_InitStruct->InputInverting));
}
/* Note: Hardware constraint (refer to description of this function): */
/* OPAMP instance must not be locked. */
if (LL_OPAMP_IsLocked(OPAMPx) == 0U)
{
/* 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_HIGHSPEEDEN
| OPAMP_CSR_CALON
| OPAMP_CSR_VMSEL
| OPAMP_CSR_VPSEL
| OPAMP_CSR_PGGAIN_4 | OPAMP_CSR_PGGAIN_3
,
OPAMP_InitStruct->PowerMode
| OPAMP_InitStruct->FunctionalMode
| OPAMP_InitStruct->InputNonInverting
| OPAMP_InitStruct->InputInverting
);
}
else
{
MODIFY_REG(OPAMPx->CSR,
OPAMP_CSR_HIGHSPEEDEN
| OPAMP_CSR_CALON
| OPAMP_CSR_VMSEL
| OPAMP_CSR_VPSEL
| OPAMP_CSR_PGGAIN_4 | OPAMP_CSR_PGGAIN_3
,
OPAMP_InitStruct->PowerMode
| LL_OPAMP_MODE_FOLLOWER
| OPAMP_InitStruct->InputNonInverting
);
}
}
else
{
/* Initialization error: OPAMP instance is locked. */
status = ERROR;
}
return status;
}
/**
* @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_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 || OPAMP3 || OPAMP4 || OPAMP5 || OPAMP6 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 9,611 |
C
| 35.687023 | 120 | 0.518885 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_dac_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_dac_ex.c
* @author MCD Application Team
* @brief Extended DAC HAL module driver.
* This file provides firmware functions to manage the extended
* functionalities of the DAC peripheral.
*
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 #####
==============================================================================
[..]
*** Dual mode IO operation ***
==============================
[..]
(+) Use HAL_DACEx_DualStart() to enable both channel and start conversion
for dual mode operation.
If software trigger is selected, using HAL_DACEx_DualStart() will start
the conversion of the value previously set by HAL_DACEx_DualSetValue().
(+) Use HAL_DACEx_DualStop() to disable both channel and stop conversion
for dual mode operation.
(+) Use HAL_DACEx_DualStart_DMA() to enable both channel and start conversion
for dual mode operation using DMA to feed DAC converters.
First issued trigger will start the conversion of the value previously
set by HAL_DACEx_DualSetValue().
The same callbacks that are used in single mode are called in dual mode to notify
transfer completion (half complete or complete), errors or underrun.
(+) Use HAL_DACEx_DualStop_DMA() to disable both channel and stop conversion
for dual mode operation using DMA to feed DAC converters.
(+) When Dual mode is enabled (i.e. DAC Channel1 and Channel2 are used simultaneously) :
Use HAL_DACEx_DualGetValue() to get digital data to be converted and use
HAL_DACEx_DualSetValue() to set digital value to converted simultaneously in
Channel 1 and Channel 2.
*** Signal generation operation ***
===================================
[..]
(+) Use HAL_DACEx_TriangleWaveGenerate() to generate Triangle signal.
(+) Use HAL_DACEx_NoiseWaveGenerate() to generate Noise signal.
(+) Use HAL_DACEx_SawtoothWaveGenerate() to generate sawtooth signal.
(+) Use HAL_DACEx_SawtoothWaveDataReset() to reset sawtooth wave.
(+) Use HAL_DACEx_SawtoothWaveDataStep() to step sawtooth wave.
(+) HAL_DACEx_SelfCalibrate to calibrate one DAC channel.
(+) HAL_DACEx_SetUserTrimming to set user trimming value.
(+) HAL_DACEx_GetTrimOffset to retrieve trimming value (factory setting
after reset, user setting if HAL_DACEx_SetUserTrimming have been used
at least one time after reset).
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_DAC_MODULE_ENABLED
#if defined(DAC1) || defined(DAC2) || defined(DAC3) ||defined (DAC4)
/** @defgroup DACEx DACEx
* @brief DAC Extended HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup DACEx_Exported_Functions DACEx Exported Functions
* @{
*/
/** @defgroup DACEx_Exported_Functions_Group2 IO operation functions
* @brief Extended IO operation functions
*
@verbatim
==============================================================================
##### Extended features functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Start conversion.
(+) Stop conversion.
(+) Start conversion and enable DMA transfer.
(+) Stop conversion and disable DMA transfer.
(+) Get result of conversion.
(+) Get result of dual mode conversion.
@endverbatim
* @{
*/
/**
* @brief Enables DAC and starts conversion of both channels.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_DualStart(DAC_HandleTypeDef *hdac)
{
uint32_t tmp_swtrig = 0UL;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, DAC_CHANNEL_2));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
/* Enable the Peripheral */
__HAL_DAC_ENABLE(hdac, DAC_CHANNEL_1);
__HAL_DAC_ENABLE(hdac, DAC_CHANNEL_2);
/* Ensure minimum wait before using peripheral after enabling it */
HAL_Delay(1);
/* Check if software trigger enabled */
if ((hdac->Instance->CR & (DAC_CR_TEN1 | DAC_CR_TSEL1)) == DAC_TRIGGER_SOFTWARE)
{
tmp_swtrig |= DAC_SWTRIGR_SWTRIG1;
}
if ((hdac->Instance->CR & (DAC_CR_TEN2 | DAC_CR_TSEL2)) == (DAC_TRIGGER_SOFTWARE << (DAC_CHANNEL_2 & 0x10UL)))
{
tmp_swtrig |= DAC_SWTRIGR_SWTRIG2;
}
/* Enable the selected DAC software conversion*/
SET_BIT(hdac->Instance->SWTRIGR, tmp_swtrig);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Disables DAC and stop conversion of both channels.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_DualStop(DAC_HandleTypeDef *hdac)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, DAC_CHANNEL_2));
/* Disable the Peripheral */
__HAL_DAC_DISABLE(hdac, DAC_CHANNEL_1);
__HAL_DAC_DISABLE(hdac, DAC_CHANNEL_2);
/* Ensure minimum wait before enabling peripheral after disabling it */
HAL_Delay(1);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Enables DAC and starts conversion of both channel 1 and 2 of the same DAC.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The DAC channel that will request data from DMA.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected
* @param pData The destination peripheral Buffer address.
* @param Length The length of data to be transferred from memory to DAC peripheral
* @param Alignment Specifies the data alignment for DAC channel.
* This parameter can be one of the following values:
* @arg DAC_ALIGN_8B_R: 8bit right data alignment selected
* @arg DAC_ALIGN_12B_L: 12bit left data alignment selected
* @arg DAC_ALIGN_12B_R: 12bit right data alignment selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_DualStart_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t *pData, uint32_t Length,
uint32_t Alignment)
{
HAL_StatusTypeDef status;
uint32_t tmpreg = 0UL;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Ensure Channel 2 exists for this particular DAC instance */
assert_param(IS_DAC_CHANNEL(hdac->Instance, DAC_CHANNEL_2));
assert_param(IS_DAC_ALIGN(Alignment));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
if (Channel == DAC_CHANNEL_1)
{
/* Set the DMA transfer complete callback for channel1 */
hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1;
/* Set the DMA half transfer complete callback for channel1 */
hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1;
/* Set the DMA error callback for channel1 */
hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1;
/* Enable the selected DAC channel1 DMA request */
SET_BIT(hdac->Instance->CR, DAC_CR_DMAEN1);
}
else
{
/* Set the DMA transfer complete callback for channel2 */
hdac->DMA_Handle2->XferCpltCallback = DAC_DMAConvCpltCh2;
/* Set the DMA half transfer complete callback for channel2 */
hdac->DMA_Handle2->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh2;
/* Set the DMA error callback for channel2 */
hdac->DMA_Handle2->XferErrorCallback = DAC_DMAErrorCh2;
/* Enable the selected DAC channel2 DMA request */
SET_BIT(hdac->Instance->CR, DAC_CR_DMAEN2);
}
switch (Alignment)
{
case DAC_ALIGN_12B_R:
/* Get DHR12R1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12RD;
break;
case DAC_ALIGN_12B_L:
/* Get DHR12L1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12LD;
break;
case DAC_ALIGN_8B_R:
/* Get DHR8R1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR8RD;
break;
default:
break;
}
/* Enable the DMA channel */
if (Channel == DAC_CHANNEL_1)
{
/* Enable the DAC DMA underrun interrupt */
__HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1);
/* Enable the DMA channel */
status = HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length);
}
else
{
/* Enable the DAC DMA underrun interrupt */
__HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR2);
/* Enable the DMA channel */
status = HAL_DMA_Start_IT(hdac->DMA_Handle2, (uint32_t)pData, tmpreg, Length);
}
/* Process Unlocked */
__HAL_UNLOCK(hdac);
if (status == HAL_OK)
{
/* Enable the Peripheral */
__HAL_DAC_ENABLE(hdac, DAC_CHANNEL_1);
__HAL_DAC_ENABLE(hdac, DAC_CHANNEL_2);
/* Ensure minimum wait before using peripheral after enabling it */
HAL_Delay(1);
}
else
{
hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
}
/* Return function status */
return status;
}
/**
* @brief Disables DAC and stop conversion both channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The DAC channel that requests data from DMA.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_DualStop_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
HAL_StatusTypeDef status;
/* Ensure Channel 2 exists for this particular DAC instance */
assert_param(IS_DAC_CHANNEL(hdac->Instance, DAC_CHANNEL_2));
/* Disable the selected DAC channel DMA request */
CLEAR_BIT(hdac->Instance->CR, DAC_CR_DMAEN2 | DAC_CR_DMAEN1);
/* Disable the Peripheral */
__HAL_DAC_DISABLE(hdac, DAC_CHANNEL_1);
__HAL_DAC_DISABLE(hdac, DAC_CHANNEL_2);
/* Ensure minimum wait before enabling peripheral after disabling it */
HAL_Delay(1);
/* Disable the DMA channel */
/* Channel1 is used */
if (Channel == DAC_CHANNEL_1)
{
/* Disable the DMA channel */
status = HAL_DMA_Abort(hdac->DMA_Handle1);
/* Disable the DAC DMA underrun interrupt */
__HAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR1);
}
else
{
/* Disable the DMA channel */
status = HAL_DMA_Abort(hdac->DMA_Handle2);
/* Disable the DAC DMA underrun interrupt */
__HAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR2);
}
/* Check if DMA Channel effectively disabled */
if (status != HAL_OK)
{
/* Update DAC state machine to error */
hdac->State = HAL_DAC_STATE_ERROR;
}
else
{
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
}
/* Return function status */
return status;
}
/**
* @brief Enable or disable the selected DAC channel wave generation.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param Amplitude Select max triangle amplitude.
* This parameter can be one of the following values:
* @arg DAC_TRIANGLEAMPLITUDE_1: Select max triangle amplitude of 1
* @arg DAC_TRIANGLEAMPLITUDE_3: Select max triangle amplitude of 3
* @arg DAC_TRIANGLEAMPLITUDE_7: Select max triangle amplitude of 7
* @arg DAC_TRIANGLEAMPLITUDE_15: Select max triangle amplitude of 15
* @arg DAC_TRIANGLEAMPLITUDE_31: Select max triangle amplitude of 31
* @arg DAC_TRIANGLEAMPLITUDE_63: Select max triangle amplitude of 63
* @arg DAC_TRIANGLEAMPLITUDE_127: Select max triangle amplitude of 127
* @arg DAC_TRIANGLEAMPLITUDE_255: Select max triangle amplitude of 255
* @arg DAC_TRIANGLEAMPLITUDE_511: Select max triangle amplitude of 511
* @arg DAC_TRIANGLEAMPLITUDE_1023: Select max triangle amplitude of 1023
* @arg DAC_TRIANGLEAMPLITUDE_2047: Select max triangle amplitude of 2047
* @arg DAC_TRIANGLEAMPLITUDE_4095: Select max triangle amplitude of 4095
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
/* Enable the triangle wave generation for the selected DAC channel */
MODIFY_REG(hdac->Instance->CR, ((DAC_CR_WAVE1) | (DAC_CR_MAMP1)) << (Channel & 0x10UL),
(DAC_CR_WAVE1_1 | Amplitude) << (Channel & 0x10UL));
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Enable or disable the selected DAC channel wave generation.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param Amplitude Unmask DAC channel LFSR for noise wave generation.
* This parameter can be one of the following values:
* @arg DAC_LFSRUNMASK_BIT0: Unmask DAC channel LFSR bit0 for noise wave generation
* @arg DAC_LFSRUNMASK_BITS1_0: Unmask DAC channel LFSR bit[1:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS2_0: Unmask DAC channel LFSR bit[2:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS3_0: Unmask DAC channel LFSR bit[3:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS4_0: Unmask DAC channel LFSR bit[4:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS5_0: Unmask DAC channel LFSR bit[5:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS6_0: Unmask DAC channel LFSR bit[6:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS7_0: Unmask DAC channel LFSR bit[7:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS8_0: Unmask DAC channel LFSR bit[8:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS9_0: Unmask DAC channel LFSR bit[9:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS10_0: Unmask DAC channel LFSR bit[10:0] for noise wave generation
* @arg DAC_LFSRUNMASK_BITS11_0: Unmask DAC channel LFSR bit[11:0] for noise wave generation
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
/* Enable the noise wave generation for the selected DAC channel */
MODIFY_REG(hdac->Instance->CR, ((DAC_CR_WAVE1) | (DAC_CR_MAMP1)) << (Channel & 0x10UL),
(DAC_CR_WAVE1_0 | Amplitude) << (Channel & 0x10UL));
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Enable or disable the selected DAC channel sawtooth wave generation.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param Polarity polarity to be used for wave generation.
* This parameter can be one of the following values:
* @arg DAC_SAWTOOTH_POLARITY_DECREMENT
* @arg DAC_SAWTOOTH_POLARITY_INCREMENT
* @param ResetData Sawtooth wave reset value.
* Range is from 0 to DAC full range 4095 (0xFFF)
* @param StepData Sawtooth wave step value.
* 12.4 bit format, unsigned: 12 bits exponent / 4 bits mantissa
* Step value step is 1/16 = 0.0625
* Step value range is 0.0000 to 4095.9375 (0xFFF.F)
* @note Sawtooth reset and step triggers are configured by calling @ref HAL_DAC_ConfigChannel
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_SawtoothWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Polarity,
uint32_t ResetData, uint32_t StepData)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_SAWTOOTH_POLARITY(Polarity));
assert_param(IS_DAC_RESET_DATA(ResetData));
assert_param(IS_DAC_STEP_DATA(StepData));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
if (Channel == DAC_CHANNEL_1)
{
/* Configure the sawtooth wave generation data parameters */
MODIFY_REG(hdac->Instance->STR1,
DAC_STR1_STINCDATA1 | DAC_STR1_STDIR1 | DAC_STR1_STRSTDATA1,
(StepData << DAC_STR1_STINCDATA1_Pos)
| Polarity
| (ResetData << DAC_STR1_STRSTDATA1_Pos));
}
else
{
/* Configure the sawtooth wave generation data parameters */
MODIFY_REG(hdac->Instance->STR2,
DAC_STR2_STINCDATA2 | DAC_STR2_STDIR2 | DAC_STR2_STRSTDATA2,
(StepData << DAC_STR2_STINCDATA2_Pos)
| Polarity
| (ResetData << DAC_STR2_STRSTDATA2_Pos));
}
/* Enable the sawtooth wave generation for the selected DAC channel */
MODIFY_REG(hdac->Instance->CR, (DAC_CR_WAVE1) << (Channel & 0x10UL), (uint32_t)(DAC_CR_WAVE1_1 | DAC_CR_WAVE1_0) << (Channel & 0x10UL));
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Trig sawtooth wave reset
* @note This function allows to reset sawtooth wave in case of SW trigger
* has been configured for this usage.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_SawtoothWaveDataReset(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Process locked */
__HAL_LOCK(hdac);
if (((hdac->Instance->STMODR >> (Channel & 0x10UL)) & DAC_STMODR_STRSTTRIGSEL1) == 0UL /* SW TRIGGER */)
{
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
if (Channel == DAC_CHANNEL_1)
{
/* Enable the selected DAC software conversion */
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIG1);
}
else
{
/* Enable the selected DAC software conversion */
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIG2);
}
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
}
else
{
status = HAL_ERROR;
}
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return status;
}
/**
* @brief Trig sawtooth wave step
* @note This function allows to generate step in sawtooth wave in case of
* SW trigger has been configured for this usage.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_SawtoothWaveDataStep(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Process locked */
__HAL_LOCK(hdac);
if (((hdac->Instance->STMODR >> (Channel & 0x10UL)) & DAC_STMODR_STINCTRIGSEL1) == 0UL /* SW TRIGGER */)
{
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
if (Channel == DAC_CHANNEL_1)
{
/* Enable the selected DAC software conversion */
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIGB1);
}
else
{
/* Enable the selected DAC software conversion */
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIGB2);
}
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
}
else
{
status = HAL_ERROR;
}
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return status;
}
/**
* @brief Set the specified data holding register value for dual DAC channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Alignment Specifies the data alignment for dual channel DAC.
* This parameter can be one of the following values:
* DAC_ALIGN_8B_R: 8bit right data alignment selected
* DAC_ALIGN_12B_L: 12bit left data alignment selected
* DAC_ALIGN_12B_R: 12bit right data alignment selected
* @param Data1 Data for DAC Channel1 to be loaded in the selected data holding register.
* @param Data2 Data for DAC Channel2 to be loaded in the selected data holding register.
* @note In dual mode, a unique register access is required to write in both
* DAC channels at the same time.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef *hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2)
{
uint32_t data;
uint32_t tmp;
/* Check the parameters */
assert_param(IS_DAC_ALIGN(Alignment));
assert_param(IS_DAC_DATA(Data1));
assert_param(IS_DAC_DATA(Data2));
/* Calculate and set dual DAC data holding register value */
if (Alignment == DAC_ALIGN_8B_R)
{
data = ((uint32_t)Data2 << 8U) | Data1;
}
else
{
data = ((uint32_t)Data2 << 16U) | Data1;
}
tmp = (uint32_t)hdac->Instance;
tmp += DAC_DHR12RD_ALIGNMENT(Alignment);
/* Set the dual DAC selected data holding register */
*(__IO uint32_t *)tmp = data;
/* Return function status */
return HAL_OK;
}
/**
* @brief Conversion complete callback in non-blocking mode for Channel2.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DACEx_ConvCpltCallbackCh2 could be implemented in the user file
*/
}
/**
* @brief Conversion half DMA transfer callback in non-blocking mode for Channel2.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DACEx_ConvHalfCpltCallbackCh2 could be implemented in the user file
*/
}
/**
* @brief Error DAC callback for Channel2.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DACEx_ErrorCallbackCh2 could be implemented in the user file
*/
}
/**
* @brief DMA underrun DAC callback for Channel2.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DACEx_DMAUnderrunCallbackCh2 could be implemented in the user file
*/
}
/**
* @brief Run the self calibration of one DAC channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param sConfig DAC channel configuration structure.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval Updates DAC_TrimmingValue. , DAC_UserTrimming set to DAC_UserTrimming
* @retval HAL status
* @note Calibration runs about 7 ms.
*/
HAL_StatusTypeDef HAL_DACEx_SelfCalibrate(DAC_HandleTypeDef *hdac, DAC_ChannelConfTypeDef *sConfig, uint32_t Channel)
{
HAL_StatusTypeDef status = HAL_OK;
__IO uint32_t tmp;
uint32_t trimmingvalue;
uint32_t delta;
/* store/restore channel configuration structure purpose */
uint32_t oldmodeconfiguration;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Check the DAC handle allocation */
/* Check if DAC running */
if (hdac == NULL)
{
status = HAL_ERROR;
}
else if (hdac->State == HAL_DAC_STATE_BUSY)
{
status = HAL_ERROR;
}
else
{
/* Process locked */
__HAL_LOCK(hdac);
/* Store configuration */
oldmodeconfiguration = (hdac->Instance->MCR & (DAC_MCR_MODE1 << (Channel & 0x10UL)));
/* Disable the selected DAC channel */
CLEAR_BIT((hdac->Instance->CR), (DAC_CR_EN1 << (Channel & 0x10UL)));
/* Wait for ready bit to be de-asserted */
HAL_Delay(1);
/* Set mode in MCR for calibration */
MODIFY_REG(hdac->Instance->MCR, (DAC_MCR_MODE1 << (Channel & 0x10UL)), 0U);
/* Set DAC Channel1 DHR register to the middle value */
tmp = (uint32_t)hdac->Instance;
if (Channel == DAC_CHANNEL_1)
{
tmp += DAC_DHR12R1_ALIGNMENT(DAC_ALIGN_12B_R);
}
else
{
tmp += DAC_DHR12R2_ALIGNMENT(DAC_ALIGN_12B_R);
}
*(__IO uint32_t *) tmp = 0x0800UL;
/* Enable the selected DAC channel calibration */
/* i.e. set DAC_CR_CENx bit */
SET_BIT((hdac->Instance->CR), (DAC_CR_CEN1 << (Channel & 0x10UL)));
/* Init trimming counter */
/* Medium value */
trimmingvalue = 16UL;
delta = 8UL;
while (delta != 0UL)
{
/* Set candidate trimming */
MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (trimmingvalue << (Channel & 0x10UL)));
/* tOFFTRIMmax delay x ms as per datasheet (electrical characteristics */
/* i.e. minimum time needed between two calibration steps */
HAL_Delay(1);
if ((hdac->Instance->SR & (DAC_SR_CAL_FLAG1 << (Channel & 0x10UL))) == (DAC_SR_CAL_FLAG1 << (Channel & 0x10UL)))
{
/* DAC_SR_CAL_FLAGx is HIGH try higher trimming */
trimmingvalue -= delta;
}
else
{
/* DAC_SR_CAL_FLAGx is LOW try lower trimming */
trimmingvalue += delta;
}
delta >>= 1UL;
}
/* Still need to check if right calibration is current value or one step below */
/* Indeed the first value that causes the DAC_SR_CAL_FLAGx bit to change from 0 to 1 */
/* Set candidate trimming */
MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (trimmingvalue << (Channel & 0x10UL)));
/* tOFFTRIMmax delay x ms as per datasheet (electrical characteristics */
/* i.e. minimum time needed between two calibration steps */
HAL_Delay(1U);
if ((hdac->Instance->SR & (DAC_SR_CAL_FLAG1 << (Channel & 0x10UL))) == 0UL)
{
/* Trimming is actually one value more */
trimmingvalue++;
/* Set right trimming */
MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (trimmingvalue << (Channel & 0x10UL)));
}
/* Disable the selected DAC channel calibration */
/* i.e. clear DAC_CR_CENx bit */
CLEAR_BIT((hdac->Instance->CR), (DAC_CR_CEN1 << (Channel & 0x10UL)));
sConfig->DAC_TrimmingValue = trimmingvalue;
sConfig->DAC_UserTrimming = DAC_TRIMMING_USER;
/* Restore configuration */
MODIFY_REG(hdac->Instance->MCR, (DAC_MCR_MODE1 << (Channel & 0x10UL)), oldmodeconfiguration);
/* Process unlocked */
__HAL_UNLOCK(hdac);
}
return status;
}
/**
* @brief Set the trimming mode and trimming value (user trimming mode applied).
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param sConfig DAC configuration structure updated with new DAC trimming value.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param NewTrimmingValue DAC new trimming value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DACEx_SetUserTrimming(DAC_HandleTypeDef *hdac, DAC_ChannelConfTypeDef *sConfig, uint32_t Channel,
uint32_t NewTrimmingValue)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_NEWTRIMMINGVALUE(NewTrimmingValue));
/* Check the DAC handle allocation */
if (hdac == NULL)
{
status = HAL_ERROR;
}
else
{
/* Process locked */
__HAL_LOCK(hdac);
/* Set new trimming */
MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (NewTrimmingValue << (Channel & 0x10UL)));
/* Update trimming mode */
sConfig->DAC_UserTrimming = DAC_TRIMMING_USER;
sConfig->DAC_TrimmingValue = NewTrimmingValue;
/* Process unlocked */
__HAL_UNLOCK(hdac);
}
return status;
}
/**
* @brief Return the DAC trimming value.
* @param hdac DAC handle
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval Trimming value : range: 0->31
*
*/
uint32_t HAL_DACEx_GetTrimOffset(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
/* Check the parameter */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Retrieve trimming */
return ((hdac->Instance->CCR & (DAC_CCR_OTRIM1 << (Channel & 0x10UL))) >> (Channel & 0x10UL));
}
/**
* @}
*/
/** @defgroup DACEx_Exported_Functions_Group3 Peripheral Control functions
* @brief Extended Peripheral Control functions
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Set the specified data holding register value for DAC channel.
@endverbatim
* @{
*/
/**
* @brief Return the last data output value of the selected DAC channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval The selected DAC channel data output value.
*/
uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef *hdac)
{
uint32_t tmp = 0UL;
tmp |= hdac->Instance->DOR1;
tmp |= hdac->Instance->DOR2 << 16UL;
/* Returns the DAC channel data output register value */
return tmp;
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup DACEx_Private_Functions DACEx private functions
* @brief Extended private functions
* @{
*/
/**
* @brief DMA conversion complete callback.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ConvCpltCallbackCh2(hdac);
#else
HAL_DACEx_ConvCpltCallbackCh2(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
hdac->State = HAL_DAC_STATE_READY;
}
/**
* @brief DMA half transfer complete callback.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Conversion complete callback */
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ConvHalfCpltCallbackCh2(hdac);
#else
HAL_DACEx_ConvHalfCpltCallbackCh2(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA error callback.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Set DAC error code to DMA error */
hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ErrorCallbackCh2(hdac);
#else
HAL_DACEx_ErrorCallbackCh2(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
hdac->State = HAL_DAC_STATE_READY;
}
/**
* @}
*/
/**
* @}
*/
#endif /* DAC1 || DAC2 || DAC3 || DAC4 */
#endif /* HAL_DAC_MODULE_ENABLED */
/**
* @}
*/
| 38,021 |
C
| 33.53406 | 138 | 0.633887 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_rng.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 HAL_RNG_RegisterCallback() to register a user callback.
Function 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 HAL_RNG_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function.
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 HAL_RNG_RegisterReadyDataCallback() , HAL_RNG_UnRegisterReadyDataCallback().
[..]
By default, after the HAL_RNG_Init() and when the state is HAL_RNG_STATE_RESET
all callbacks are set to the corresponding weak (surcharged) functions:
example HAL_RNG_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) functions in the HAL_RNG_Init()
and HAL_RNG_DeInit() only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_RNG_Init() and 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 HAL_RNG_RegisterCallback() before calling HAL_RNG_DeInit()
or 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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 2U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private functions prototypes ----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* 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)
{
/* 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;
/* Clock Error Detection Configuration */
MODIFY_REG(hrng->Instance->CR, RNG_CR_CED, hrng->Init.ClockErrorDetection);
/* Enable the RNG Peripheral */
__HAL_RNG_ENABLE(hrng);
/* 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)
{
/* Check the RNG handle allocation */
if (hrng == NULL)
{
return HAL_ERROR;
}
/* Clear Clock Error Detection bit */
CLEAR_BIT(hrng->Instance->CR, RNG_CR_CED);
/* 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 callabck 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;
/* 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;
*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)
{
/* Update the error code */
hrng->ErrorCode = HAL_RNG_ERROR_SEED;
rngclockerror = 1U;
}
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;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_RNG_MODULE_ENABLED */
/**
* @}
*/
#endif /* RNG */
/**
* @}
*/
| 25,836 |
C
| 29.758333 | 117 | 0.608337 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_fmac.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_fmac.c
* @author MCD Application Team
* @brief FMAC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the FMAC peripheral:
* + Initialization and de-initialization functions
* + Peripheral Control functions
* + Callback functions
* + IRQ handler management
* + Peripheral State and Error functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 FMAC HAL driver can be used as follows:
(#) Initialize the FMAC low level resources by implementing the HAL_FMAC_MspInit():
(++) Enable the FMAC interface clock using __HAL_RCC_FMAC_CLK_ENABLE().
(++) In case of using interrupts (e.g. access configured as FMAC_BUFFER_ACCESS_IT):
(+++) Configure the FMAC interrupt priority using HAL_NVIC_SetPriority().
(+++) Enable the FMAC IRQ handler using HAL_NVIC_EnableIRQ().
(+++) In FMAC IRQ handler, call HAL_FMAC_IRQHandler().
(++) In case of using DMA to control data transfer (e.g. access configured
as FMAC_BUFFER_ACCESS_DMA):
(+++) Enable the DMA interface clock using __HAL_RCC_DMA1_CLK_ENABLE()
or __HAL_RCC_DMA2_CLK_ENABLE() depending on the used DMA instance.
(+++) Enable the DMAMUX1 interface clock using __HAL_RCC_DMAMUX1_CLK_ENABLE().
(+++) If the initialization of the internal buffers (coefficients, input,
output) is done via DMA, configure and enable one DMA channel for
managing data transfer from memory to memory (preload channel).
(+++) If the input buffer is accessed via DMA, configure and enable one
DMA channel for managing data transfer from memory to peripheral
(input channel).
(+++) If the output buffer is accessed via DMA, configure and enable
one DMA channel for managing data transfer from peripheral to
memory (output channel).
(+++) Associate the initialized DMA handle(s) to the FMAC DMA handle(s)
using __HAL_LINKDMA().
(+++) Configure the priority and enable the NVIC for the transfer complete
interrupt on the enabled DMA channel(s) using HAL_NVIC_SetPriority()
and HAL_NVIC_EnableIRQ().
(#) Initialize the FMAC HAL using HAL_FMAC_Init(). This function
resorts to HAL_FMAC_MspInit() for low-level initialization.
(#) Configure the FMAC processing (filter) using HAL_FMAC_FilterConfig()
or HAL_FMAC_FilterConfig_DMA().
This function:
(++) Defines the memory area within the FMAC internal memory
(input, coefficients, output) and the associated threshold (input, output).
(++) Configures the filter and its parameters:
(+++) Finite Impulse Response (FIR) filter (also known as convolution).
(+++) Infinite Impulse Response (IIR) filter (direct form 1).
(++) Choose the way to access to the input and output buffers: none, polling,
DMA, IT. "none" means the input and/or output data will be handled by
another IP (ADC, DAC, etc.).
(++) Enable the error interruptions in the input access and/or the output
access is done through IT/DMA. If an error occurs, the interruption
will be triggered in loop. In order to recover, the user will have
to reset the IP with the sequence HAL_FMAC_DeInit / HAL_FMAC_Init.
Optionally, he can also disable the interrupt using __HAL_FMAC_DISABLE_IT;
the error status will be kept, but no more interrupt will be triggered.
(++) Write the provided coefficients into the internal memory using polling
mode ( HAL_FMAC_FilterConfig() ) or DMA ( HAL_FMAC_FilterConfig_DMA() ).
In the DMA case, HAL_FMAC_FilterConfigCallback() is called when
the handling is over.
(#) Optionally, the user can enable the error interruption related to
saturation by calling __HAL_FMAC_ENABLE_IT. This helps in debugging the
filter. If a saturation occurs, the interruption will be triggered in loop.
In order to recover, the user will have to:
(++) Disable the interruption by calling __HAL_FMAC_DISABLE_IT if
the user wishes to continue all the same.
(++) Reset the IP with the sequence HAL_FMAC_DeInit / HAL_FMAC_Init.
(#) Optionally, preload input (FIR, IIR) and output (IIR) data using
HAL_FMAC_FilterPreload() or HAL_FMAC_FilterPreload_DMA().
In the DMA case, HAL_FMAC_FilterPreloadCallback() is called when
the handling is over.
This step is optional as the filter can be started without preloaded
data.
(#) Start the FMAC processing (filter) using HAL_FMAC_FilterStart().
This function also configures the output buffer that will be filled from
the circular internal output buffer. The function returns immediately
without updating the provided buffer. The IP processing will be active until
HAL_FMAC_FilterStop() is called.
(#) If the input internal buffer is accessed via DMA, HAL_FMAC_HalfGetDataCallback()
will be called to indicate that half of the input buffer has been handled.
(#) If the input internal buffer is accessed via DMA or interrupt, HAL_FMAC_GetDataCallback()
will be called to require new input data. It will be provided through
HAL_FMAC_AppendFilterData() if the DMA isn't in circular mode.
(#) If the output internal buffer is accessed via DMA, HAL_FMAC_HalfOutputDataReadyCallback()
will be called to indicate that half of the output buffer has been handled.
(#) If the output internal buffer is accessed via DMA or interrupt,
HAL_FMAC_OutputDataReadyCallback() will be called to require a new output
buffer. It will be provided through HAL_FMAC_ConfigFilterOutputBuffer()
if the DMA isn't in circular mode.
(#) In all modes except none, provide new input data to be processed via HAL_FMAC_AppendFilterData().
This function should only be called once the previous input data has been handled
(the preloaded input data isn't concerned).
(#) In all modes except none, provide a new output buffer to be filled via
HAL_FMAC_ConfigFilterOutputBuffer(). This function should only be called once the previous
user's output buffer has been filled.
(#) In polling mode, handle the input and output data using HAL_FMAC_PollFilterData().
This function:
(++) Write the user's input data (provided via HAL_FMAC_AppendFilterData())
into the FMAC input memory area.
(++) Read the FMAC output memory area and write it into the user's output buffer.
It will return either when:
(++) the user's output buffer is filled.
(++) the user's input buffer has been handled.
The unused data (unread input data or free output data) will not be saved.
The user will have to use the updated input and output sizes to keep track
of them.
(#) Stop the FMAC processing (filter) using HAL_FMAC_FilterStop().
(#) Call HAL_FMAC_DeInit() to de-initialize the FMAC peripheral. This function
resorts to HAL_FMAC_MspDeInit() for low-level de-initialization.
##### Callback registration #####
==================================
[..]
The compilation define USE_HAL_FMAC_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
[..]
Use Function HAL_FMAC_RegisterCallback() to register a user callback.
Function HAL_FMAC_RegisterCallback() allows to register following callbacks:
(+) ErrorCallback : Error Callback.
(+) HalfGetDataCallback : Get Half Data Callback.
(+) GetDataCallback : Get Data Callback.
(+) HalfOutputDataReadyCallback : Half Output Data Ready Callback.
(+) OutputDataReadyCallback : Output Data Ready Callback.
(+) FilterConfigCallback : Filter Configuration Callback.
(+) FilterPreloadCallback : Filter Preload Callback.
(+) MspInitCallback : FMAC MspInit.
(+) MspDeInitCallback : FMAC MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function HAL_FMAC_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function.
HAL_FMAC_UnRegisterCallback() takes as parameters the HAL peripheral handle
and the Callback ID.
This function allows to reset following callbacks:
(+) ErrorCallback : Error Callback.
(+) HalfGetDataCallback : Get Half Data Callback.
(+) GetDataCallback : Get Data Callback.
(+) HalfOutputDataReadyCallback : Half Output Data Ready Callback.
(+) OutputDataReadyCallback : Output Data Ready Callback.
(+) FilterConfigCallback : Filter Configuration Callback.
(+) FilterPreloadCallback : Filter Preload Callback.
(+) MspInitCallback : FMAC MspInit.
(+) MspDeInitCallback : FMAC MspDeInit.
[..]
By default, after the HAL_FMAC_Init() and when the state is HAL_FMAC_STATE_RESET
all callbacks are set to the corresponding weak (surcharged) functions:
examples GetDataCallback(), OutputDataReadyCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) functions in the HAL_FMAC_Init()
and HAL_FMAC_DeInit() only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_FMAC_Init() and HAL_FMAC_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand).
[..]
Callbacks can be registered/unregistered in HAL_FMAC_STATE_READY state only.
Exception done MspInit/MspDeInit that can be registered/unregistered
in HAL_FMAC_STATE_READY or HAL_FMAC_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_FMAC_RegisterCallback() before calling HAL_FMAC_DeInit()
or HAL_FMAC_Init() function.
[..]
When the compilation define USE_HAL_FMAC_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 "stm32g4xx_hal.h"
#if defined(FMAC)
#ifdef HAL_FMAC_MODULE_ENABLED
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup FMAC FMAC
* @brief FMAC HAL driver module
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/** @defgroup FMAC_Private_Constants FMAC Private Constants
* @{
*/
#define MAX_FILTER_DATA_SIZE_TO_HANDLE ((uint16_t) 0xFFU)
#define MAX_PRELOAD_INDEX 0xFFU
#define PRELOAD_ACCESS_DMA 0x00U
#define PRELOAD_ACCESS_POLLING 0x01U
#define POLLING_DISABLED 0U
#define POLLING_ENABLED 1U
#define POLLING_NOT_STOPPED 0U
#define POLLING_STOPPED 1U
/* FMAC polling-based communications time-out value */
#define HAL_FMAC_TIMEOUT_VALUE 1000U
/* FMAC reset time-out value */
#define HAL_FMAC_RESET_TIMEOUT_VALUE 500U
/* DMA Read Requests Enable */
#define FMAC_DMA_REN FMAC_CR_DMAREN
/* DMA Write Channel Enable */
#define FMAC_DMA_WEN FMAC_CR_DMAWEN
/* FMAC Execution Enable */
#define FMAC_START FMAC_PARAM_START
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup FMAC_Private_Macros FMAC Private Macros
* @{
*/
/**
* @brief Get the X1 memory area size.
* @param __HANDLE__ FMAC handle.
* @retval X1_BUF_SIZE
*/
#define FMAC_GET_X1_SIZE(__HANDLE__) \
((((__HANDLE__)->Instance->X1BUFCFG) & (FMAC_X1BUFCFG_X1_BUF_SIZE)) >> (FMAC_X1BUFCFG_X1_BUF_SIZE_Pos))
/**
* @brief Get the X1 watermark.
* @param __HANDLE__ FMAC handle.
* @retval FULL_WM
*/
#define FMAC_GET_X1_FULL_WM(__HANDLE__) \
(((__HANDLE__)->Instance->X1BUFCFG) & (FMAC_X1BUFCFG_FULL_WM))
/**
* @brief Get the X2 memory area size.
* @param __HANDLE__ FMAC handle.
* @retval X2_BUF_SIZE
*/
#define FMAC_GET_X2_SIZE(__HANDLE__) \
((((__HANDLE__)->Instance->X2BUFCFG) & (FMAC_X2BUFCFG_X2_BUF_SIZE)) >> (FMAC_X2BUFCFG_X2_BUF_SIZE_Pos))
/**
* @brief Get the Y memory area size.
* @param __HANDLE__ FMAC handle.
* @retval Y_BUF_SIZE
*/
#define FMAC_GET_Y_SIZE(__HANDLE__) \
((((__HANDLE__)->Instance->YBUFCFG) & (FMAC_YBUFCFG_Y_BUF_SIZE)) >> (FMAC_YBUFCFG_Y_BUF_SIZE_Pos))
/**
* @brief Get the Y watermark.
* @param __HANDLE__ FMAC handle.
* @retval EMPTY_WM
*/
#define FMAC_GET_Y_EMPTY_WM(__HANDLE__) \
(((__HANDLE__)->Instance->YBUFCFG) & (FMAC_YBUFCFG_EMPTY_WM))
/**
* @brief Get the start bit state.
* @param __HANDLE__ FMAC handle.
* @retval START
*/
#define FMAC_GET_START_BIT(__HANDLE__) \
((((__HANDLE__)->Instance->PARAM) & (FMAC_PARAM_START)) >> (FMAC_PARAM_START_Pos))
/**
* @brief Get the threshold matching the watermark.
* @param __WM__ Watermark value.
* @retval THRESHOLD
*/
#define FMAC_GET_THRESHOLD_FROM_WM(__WM__) (((__WM__) == FMAC_THRESHOLD_1)? 1U: \
((__WM__) == FMAC_THRESHOLD_2)? 2U: \
((__WM__) == FMAC_THRESHOLD_4)? 4U:8U)
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Global variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static HAL_StatusTypeDef FMAC_Reset(FMAC_HandleTypeDef *hfmac);
static void FMAC_ResetDataPointers(FMAC_HandleTypeDef *hfmac);
static void FMAC_ResetOutputStateAndDataPointers(FMAC_HandleTypeDef *hfmac);
static void FMAC_ResetInputStateAndDataPointers(FMAC_HandleTypeDef *hfmac);
static HAL_StatusTypeDef FMAC_FilterConfig(FMAC_HandleTypeDef *hfmac, FMAC_FilterConfigTypeDef *pConfig,
uint8_t PreloadAccess);
static HAL_StatusTypeDef FMAC_FilterPreload(FMAC_HandleTypeDef *hfmac, int16_t *pInput, uint8_t InputSize,
int16_t *pOutput, uint8_t OutputSize, uint8_t PreloadAccess);
static void FMAC_WritePreloadDataIncrementPtr(FMAC_HandleTypeDef *hfmac, int16_t **ppData, uint8_t Size);
static HAL_StatusTypeDef FMAC_WaitOnStartUntilTimeout(FMAC_HandleTypeDef *hfmac, uint32_t Tickstart, uint32_t Timeout);
static HAL_StatusTypeDef FMAC_AppendFilterDataUpdateState(FMAC_HandleTypeDef *hfmac, int16_t *pInput,
uint16_t *pInputSize);
static HAL_StatusTypeDef FMAC_ConfigFilterOutputBufferUpdateState(FMAC_HandleTypeDef *hfmac, int16_t *pOutput,
uint16_t *pOutputSize);
static void FMAC_WriteDataIncrementPtr(FMAC_HandleTypeDef *hfmac, uint16_t MaxSizeToWrite);
static void FMAC_ReadDataIncrementPtr(FMAC_HandleTypeDef *hfmac, uint16_t MaxSizeToRead);
static void FMAC_DMAHalfGetData(DMA_HandleTypeDef *hdma);
static void FMAC_DMAGetData(DMA_HandleTypeDef *hdma);
static void FMAC_DMAHalfOutputDataReady(DMA_HandleTypeDef *hdma);
static void FMAC_DMAOutputDataReady(DMA_HandleTypeDef *hdma);
static void FMAC_DMAFilterConfig(DMA_HandleTypeDef *hdma);
static void FMAC_DMAFilterPreload(DMA_HandleTypeDef *hdma);
static void FMAC_DMAError(DMA_HandleTypeDef *hdma);
/* Functions Definition ------------------------------------------------------*/
/** @defgroup FMAC_Exported_Functions FMAC Exported Functions
* @{
*/
/** @defgroup FMAC_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize the FMAC peripheral and the associated handle
(+) DeInitialize the FMAC peripheral
(+) Initialize the FMAC MSP (MCU Specific Package)
(+) De-Initialize the FMAC MSP
(+) Register a User FMAC Callback
(+) Unregister a FMAC CallBack
[..]
@endverbatim
* @{
*/
/**
* @brief Initialize the FMAC peripheral and the associated handle.
* @param hfmac pointer to a FMAC_HandleTypeDef structure.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_Init(FMAC_HandleTypeDef *hfmac)
{
HAL_StatusTypeDef status;
/* Check the FMAC handle allocation */
if (hfmac == NULL)
{
return HAL_ERROR;
}
/* Check the instance */
assert_param(IS_FMAC_ALL_INSTANCE(hfmac->Instance));
if (hfmac->State == HAL_FMAC_STATE_RESET)
{
/* Initialize lock resource */
hfmac->Lock = HAL_UNLOCKED;
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
/* Register the default callback functions */
hfmac->ErrorCallback = HAL_FMAC_ErrorCallback;
hfmac->HalfGetDataCallback = HAL_FMAC_HalfGetDataCallback;
hfmac->GetDataCallback = HAL_FMAC_GetDataCallback;
hfmac->HalfOutputDataReadyCallback = HAL_FMAC_HalfOutputDataReadyCallback;
hfmac->OutputDataReadyCallback = HAL_FMAC_OutputDataReadyCallback;
hfmac->FilterConfigCallback = HAL_FMAC_FilterConfigCallback;
hfmac->FilterPreloadCallback = HAL_FMAC_FilterPreloadCallback;
if (hfmac->MspInitCallback == NULL)
{
hfmac->MspInitCallback = HAL_FMAC_MspInit;
}
/* Init the low level hardware */
hfmac->MspInitCallback(hfmac);
#else
/* Init the low level hardware */
HAL_FMAC_MspInit(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/* Reset pInput and pOutput */
hfmac->FilterParam = 0U;
FMAC_ResetDataPointers(hfmac);
/* Reset FMAC unit (internal pointers) */
if (FMAC_Reset(hfmac) == HAL_ERROR)
{
/* Update FMAC error code and FMAC peripheral state */
hfmac->ErrorCode |= HAL_FMAC_ERROR_RESET;
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
status = HAL_ERROR;
}
else
{
/* Update FMAC error code and FMAC peripheral state */
hfmac->ErrorCode = HAL_FMAC_ERROR_NONE;
hfmac->State = HAL_FMAC_STATE_READY;
status = HAL_OK;
}
__HAL_UNLOCK(hfmac);
return status;
}
/**
* @brief De-initialize the FMAC peripheral.
* @param hfmac pointer to a FMAC structure.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_DeInit(FMAC_HandleTypeDef *hfmac)
{
/* Check the FMAC handle allocation */
if (hfmac == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_FMAC_ALL_INSTANCE(hfmac->Instance));
/* Change FMAC peripheral state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* Set FMAC error code to none */
hfmac->ErrorCode = HAL_FMAC_ERROR_NONE;
/* Reset pInput and pOutput */
hfmac->FilterParam = 0U;
FMAC_ResetDataPointers(hfmac);
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
if (hfmac->MspDeInitCallback == NULL)
{
hfmac->MspDeInitCallback = HAL_FMAC_MspDeInit;
}
/* DeInit the low level hardware */
hfmac->MspDeInitCallback(hfmac);
#else
/* DeInit the low level hardware: CLOCK, NVIC, DMA */
HAL_FMAC_MspDeInit(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
/* Change FMAC peripheral state */
hfmac->State = HAL_FMAC_STATE_RESET;
/* Always release Lock in case of de-initialization */
__HAL_UNLOCK(hfmac);
return HAL_OK;
}
/**
* @brief Initialize the FMAC MSP.
* @param hfmac FMAC handle.
* @retval None
*/
__weak void HAL_FMAC_MspInit(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMAC_MspInit can be implemented in the user file
*/
}
/**
* @brief De-initialize the FMAC MSP.
* @param hfmac FMAC handle.
* @retval None
*/
__weak void HAL_FMAC_MspDeInit(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMAC_MspDeInit can be implemented in the user file
*/
}
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User FMAC Callback.
* @note The User FMAC Callback is to be used instead of the weak predefined callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param CallbackID ID of the callback to be registered.
* This parameter can be one of the following values:
* @arg @ref HAL_FMAC_ERROR_CB_ID Error Callback ID
* @arg @ref HAL_FMAC_HALF_GET_DATA_CB_ID Get Half Data Callback ID
* @arg @ref HAL_FMAC_GET_DATA_CB_ID Get Data Callback ID
* @arg @ref HAL_FMAC_HALF_OUTPUT_DATA_READY_CB_ID Half Output Data Ready Callback ID
* @arg @ref HAL_FMAC_OUTPUT_DATA_READY_CB_ID Output Data Ready Callback ID
* @arg @ref HAL_FMAC_FILTER_CONFIG_CB_ID Filter Configuration Callback ID
* @arg @ref HAL_FMAC_FILTER_PRELOAD_CB_ID Filter Preload Callback ID
* @arg @ref HAL_FMAC_MSPINIT_CB_ID FMAC MspInit ID
* @arg @ref HAL_FMAC_MSPDEINIT_CB_ID FMAC MspDeInit ID
* @param pCallback pointer to the Callback function.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_RegisterCallback(FMAC_HandleTypeDef *hfmac, HAL_FMAC_CallbackIDTypeDef CallbackID,
pFMAC_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the FMAC handle allocation */
if (hfmac == NULL)
{
return HAL_ERROR;
}
if (pCallback == NULL)
{
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
__HAL_LOCK(hfmac);
if (hfmac->State == HAL_FMAC_STATE_READY)
{
switch (CallbackID)
{
case HAL_FMAC_ERROR_CB_ID :
hfmac->ErrorCallback = pCallback;
break;
case HAL_FMAC_HALF_GET_DATA_CB_ID :
hfmac->HalfGetDataCallback = pCallback;
break;
case HAL_FMAC_GET_DATA_CB_ID :
hfmac->GetDataCallback = pCallback;
break;
case HAL_FMAC_HALF_OUTPUT_DATA_READY_CB_ID :
hfmac->HalfOutputDataReadyCallback = pCallback;
break;
case HAL_FMAC_OUTPUT_DATA_READY_CB_ID :
hfmac->OutputDataReadyCallback = pCallback;
break;
case HAL_FMAC_FILTER_CONFIG_CB_ID :
hfmac->FilterConfigCallback = pCallback;
break;
case HAL_FMAC_FILTER_PRELOAD_CB_ID :
hfmac->FilterPreloadCallback = pCallback;
break;
case HAL_FMAC_MSPINIT_CB_ID :
hfmac->MspInitCallback = pCallback;
break;
case HAL_FMAC_MSPDEINIT_CB_ID :
hfmac->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hfmac->State == HAL_FMAC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_FMAC_MSPINIT_CB_ID :
hfmac->MspInitCallback = pCallback;
break;
case HAL_FMAC_MSPDEINIT_CB_ID :
hfmac->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
__HAL_UNLOCK(hfmac);
return status;
}
/**
* @brief Unregister a FMAC CallBack.
* @note The FMAC callback is redirected to the weak predefined callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module
* @param CallbackID ID of the callback to be unregistered.
* This parameter can be one of the following values:
* @arg @ref HAL_FMAC_ERROR_CB_ID Error Callback ID
* @arg @ref HAL_FMAC_HALF_GET_DATA_CB_ID Get Half Data Callback ID
* @arg @ref HAL_FMAC_GET_DATA_CB_ID Get Data Callback ID
* @arg @ref HAL_FMAC_HALF_OUTPUT_DATA_READY_CB_ID Half Output Data Ready Callback ID
* @arg @ref HAL_FMAC_OUTPUT_DATA_READY_CB_ID Output Data Ready Callback ID
* @arg @ref HAL_FMAC_FILTER_CONFIG_CB_ID Filter Configuration Callback ID
* @arg @ref HAL_FMAC_FILTER_PRELOAD_CB_ID Filter Preload Callback ID
* @arg @ref HAL_FMAC_MSPINIT_CB_ID FMAC MspInit ID
* @arg @ref HAL_FMAC_MSPDEINIT_CB_ID FMAC MspDeInit ID
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_UnRegisterCallback(FMAC_HandleTypeDef *hfmac, HAL_FMAC_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the FMAC handle allocation */
if (hfmac == NULL)
{
return HAL_ERROR;
}
__HAL_LOCK(hfmac);
if (hfmac->State == HAL_FMAC_STATE_READY)
{
switch (CallbackID)
{
case HAL_FMAC_ERROR_CB_ID :
hfmac->ErrorCallback = HAL_FMAC_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_FMAC_HALF_GET_DATA_CB_ID :
hfmac->HalfGetDataCallback = HAL_FMAC_HalfGetDataCallback; /* Legacy weak HalfGetDataCallback */
break;
case HAL_FMAC_GET_DATA_CB_ID :
hfmac->GetDataCallback = HAL_FMAC_GetDataCallback; /* Legacy weak GetDataCallback */
break;
case HAL_FMAC_HALF_OUTPUT_DATA_READY_CB_ID :
hfmac->HalfOutputDataReadyCallback = HAL_FMAC_HalfOutputDataReadyCallback; /* Legacy weak
HalfOutputDataReadyCallback */
break;
case HAL_FMAC_OUTPUT_DATA_READY_CB_ID :
hfmac->OutputDataReadyCallback = HAL_FMAC_OutputDataReadyCallback; /* Legacy weak
OutputDataReadyCallback */
break;
case HAL_FMAC_FILTER_CONFIG_CB_ID :
hfmac->FilterConfigCallback = HAL_FMAC_FilterConfigCallback; /* Legacy weak
FilterConfigCallback */
break;
case HAL_FMAC_FILTER_PRELOAD_CB_ID :
hfmac->FilterPreloadCallback = HAL_FMAC_FilterPreloadCallback; /* Legacy weak FilterPreloadCallba */
break;
case HAL_FMAC_MSPINIT_CB_ID :
hfmac->MspInitCallback = HAL_FMAC_MspInit; /* Legacy weak MspInitCallback */
break;
case HAL_FMAC_MSPDEINIT_CB_ID :
hfmac->MspDeInitCallback = HAL_FMAC_MspDeInit; /* Legacy weak MspDeInitCallback */
break;
default :
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (hfmac->State == HAL_FMAC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_FMAC_MSPINIT_CB_ID :
hfmac->MspInitCallback = HAL_FMAC_MspInit;
break;
case HAL_FMAC_MSPDEINIT_CB_ID :
hfmac->MspDeInitCallback = HAL_FMAC_MspDeInit;
break;
default :
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hfmac->ErrorCode |= HAL_FMAC_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
__HAL_UNLOCK(hfmac);
return status;
}
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup FMAC_Exported_Functions_Group2 Peripheral Control functions
* @brief Control functions.
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Configure the FMAC peripheral: memory area, filter type and parameters,
way to access to the input and output memory area (none, polling, IT, DMA).
(+) Start the FMAC processing (filter).
(+) Handle the input data that will be provided into FMAC.
(+) Handle the output data provided by FMAC.
(+) Stop the FMAC processing (filter).
@endverbatim
* @{
*/
/**
* @brief Configure the FMAC filter.
* @note The configuration is done according to the parameters
* specified in the FMAC_FilterConfigTypeDef structure.
* The provided data will be loaded using polling mode.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pConfig pointer to a FMAC_FilterConfigTypeDef structure that
* contains the FMAC configuration information.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterConfig(FMAC_HandleTypeDef *hfmac, FMAC_FilterConfigTypeDef *pConfig)
{
return (FMAC_FilterConfig(hfmac, pConfig, PRELOAD_ACCESS_POLLING));
}
/**
* @brief Configure the FMAC filter.
* @note The configuration is done according to the parameters
* specified in the FMAC_FilterConfigTypeDef structure.
* The provided data will be loaded using DMA.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pConfig pointer to a FMAC_FilterConfigTypeDef structure that
* contains the FMAC configuration information.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterConfig_DMA(FMAC_HandleTypeDef *hfmac, FMAC_FilterConfigTypeDef *pConfig)
{
return (FMAC_FilterConfig(hfmac, pConfig, PRELOAD_ACCESS_DMA));
}
/**
* @brief Preload the input (FIR, IIR) and output data (IIR) of the FMAC filter.
* @note The set(s) of data will be used by FMAC as soon as @ref HAL_FMAC_FilterStart is called.
* The provided data will be loaded using polling mode.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pInput Preloading of the first elements of the input buffer (X1).
* If not needed (no data available when starting), it should be set to NULL.
* @param InputSize Size of the input vector.
* As pInput is used for preloading data, it cannot be bigger than the input memory area.
* @param pOutput [IIR] Preloading of the first elements of the output vector (Y).
* If not needed, it should be set to NULL.
* @param OutputSize Size of the output vector.
* As pOutput is used for preloading data, it cannot be bigger than the output memory area.
* @note The input and the output buffers can be filled by calling several times @ref HAL_FMAC_FilterPreload
* (each call filling partly the buffers). In case of overflow (too much data provided through
* all these calls), an error will be returned.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterPreload(FMAC_HandleTypeDef *hfmac, int16_t *pInput, uint8_t InputSize,
int16_t *pOutput, uint8_t OutputSize)
{
return (FMAC_FilterPreload(hfmac, pInput, InputSize, pOutput, OutputSize, PRELOAD_ACCESS_POLLING));
}
/**
* @brief Preload the input (FIR, IIR) and output data (IIR) of the FMAC filter.
* @note The set(s) of data will be used by FMAC as soon as @ref HAL_FMAC_FilterStart is called.
* The provided data will be loaded using DMA.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pInput Preloading of the first elements of the input buffer (X1).
* If not needed (no data available when starting), it should be set to NULL.
* @param InputSize Size of the input vector.
* As pInput is used for preloading data, it cannot be bigger than the input memory area.
* @param pOutput [IIR] Preloading of the first elements of the output vector (Y).
* If not needed, it should be set to NULL.
* @param OutputSize Size of the output vector.
* As pOutput is used for preloading data, it cannot be bigger than the output memory area.
* @note The input and the output buffers can be filled by calling several times @ref HAL_FMAC_FilterPreload
* (each call filling partly the buffers). In case of overflow (too much data provided through
* all these calls), an error will be returned.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterPreload_DMA(FMAC_HandleTypeDef *hfmac, int16_t *pInput, uint8_t InputSize,
int16_t *pOutput, uint8_t OutputSize)
{
return (FMAC_FilterPreload(hfmac, pInput, InputSize, pOutput, OutputSize, PRELOAD_ACCESS_DMA));
}
/**
* @brief Start the FMAC processing according to the existing FMAC configuration.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pOutput pointer to buffer where output data of FMAC processing will be stored
* in the next steps.
* If it is set to NULL, the output will not be read and it will be up to
* an external IP to empty the output buffer.
* @param pOutputSize pointer to the size of the output buffer. The number of read data will be written here.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterStart(FMAC_HandleTypeDef *hfmac, int16_t *pOutput, uint16_t *pOutputSize)
{
uint32_t tmpcr = 0U;
HAL_StatusTypeDef status;
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) != 0U)
{
return HAL_ERROR;
}
/* Check that a valid configuration was done previously */
if (hfmac->FilterParam == 0U)
{
return HAL_ERROR;
}
/* Check handle state is ready */
if (hfmac->State == HAL_FMAC_STATE_READY)
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* CR: Configure the input access (error interruptions enabled only for IT or DMA) */
if (hfmac->InputAccess == FMAC_BUFFER_ACCESS_DMA)
{
tmpcr |= FMAC_DMA_WEN;
}
else if (hfmac->InputAccess == FMAC_BUFFER_ACCESS_IT)
{
tmpcr |= FMAC_IT_WIEN;
}
else
{
/* nothing to do */
}
/* CR: Configure the output access (error interruptions enabled only for IT or DMA) */
if (hfmac->OutputAccess == FMAC_BUFFER_ACCESS_DMA)
{
tmpcr |= FMAC_DMA_REN;
}
else if (hfmac->OutputAccess == FMAC_BUFFER_ACCESS_IT)
{
tmpcr |= FMAC_IT_RIEN;
}
else
{
/* nothing to do */
}
/* CR: Write the configuration */
MODIFY_REG(hfmac->Instance->CR, \
FMAC_IT_RIEN | FMAC_IT_WIEN | FMAC_DMA_REN | FMAC_CR_DMAWEN, \
tmpcr);
/* Register the new output buffer */
status = FMAC_ConfigFilterOutputBufferUpdateState(hfmac, pOutput, pOutputSize);
if (status == HAL_OK)
{
/* PARAM: Start the filter ( this can generate interrupts before the end of the HAL_FMAC_FilterStart ) */
WRITE_REG(hfmac->Instance->PARAM, (uint32_t)(hfmac->FilterParam));
}
/* Reset the busy flag (do not overwrite the possible write and read flag) */
hfmac->State = HAL_FMAC_STATE_READY;
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @brief Provide a new input buffer that will be loaded into the FMAC input memory area.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pInput New input vector (additional input data).
* @param pInputSize Size of the input vector (if all the data can't be
* written, it will be updated with the number of data read from FMAC).
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_AppendFilterData(FMAC_HandleTypeDef *hfmac, int16_t *pInput, uint16_t *pInputSize)
{
HAL_StatusTypeDef status;
/* Check the function parameters */
if ((pInput == NULL) || (pInputSize == NULL))
{
return HAL_ERROR;
}
if (*pInputSize == 0U)
{
return HAL_ERROR;
}
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) == 0U)
{
return HAL_ERROR;
}
/* Check the FMAC configuration */
if (hfmac->InputAccess == FMAC_BUFFER_ACCESS_NONE)
{
return HAL_ERROR;
}
/* Check whether the previous input vector has been handled */
if ((hfmac->pInputSize != NULL) && (hfmac->InputCurrentSize < * (hfmac->pInputSize)))
{
return HAL_ERROR;
}
/* Check that FMAC was initialized and that no writing is already ongoing */
if (hfmac->WrState == HAL_FMAC_STATE_READY)
{
/* Register the new input buffer */
status = FMAC_AppendFilterDataUpdateState(hfmac, pInput, pInputSize);
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @brief Provide a new output buffer to be filled with the data computed by FMAC unit.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pOutput New output vector.
* @param pOutputSize Size of the output vector (if the vector can't
* be entirely filled, pOutputSize will be updated with the number
* of data read from FMAC).
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_ConfigFilterOutputBuffer(FMAC_HandleTypeDef *hfmac, int16_t *pOutput, uint16_t *pOutputSize)
{
HAL_StatusTypeDef status;
/* Check the function parameters */
if ((pOutput == NULL) || (pOutputSize == NULL))
{
return HAL_ERROR;
}
if (*pOutputSize == 0U)
{
return HAL_ERROR;
}
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) == 0U)
{
return HAL_ERROR;
}
/* Check the FMAC configuration */
if (hfmac->OutputAccess == FMAC_BUFFER_ACCESS_NONE)
{
return HAL_ERROR;
}
/* Check whether the previous output vector has been handled */
if ((hfmac->pOutputSize != NULL) && (hfmac->OutputCurrentSize < * (hfmac->pOutputSize)))
{
return HAL_ERROR;
}
/* Check that FMAC was initialized and that not reading is already ongoing */
if (hfmac->RdState == HAL_FMAC_STATE_READY)
{
/* Register the new output buffer */
status = FMAC_ConfigFilterOutputBufferUpdateState(hfmac, pOutput, pOutputSize);
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @brief Handle the input and/or output data in polling mode
* @note This function writes the previously provided user's input data and
* fills the previously provided user's output buffer,
* according to the existing FMAC configuration (polling mode only).
* The function returns when the input data has been handled or
* when the output data is filled. The possible unused data isn't
* kept. It will be up to the user to handle it. The previously
* provided pInputSize and pOutputSize will be used to indicate to the
* size of the read/written data to the user.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param Timeout timeout value.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_PollFilterData(FMAC_HandleTypeDef *hfmac, uint32_t Timeout)
{
uint32_t tickstart;
uint8_t inpolling;
uint8_t inpollingover = POLLING_NOT_STOPPED;
uint8_t outpolling;
uint8_t outpollingover = POLLING_NOT_STOPPED;
HAL_StatusTypeDef status;
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) == 0U)
{
return HAL_ERROR;
}
/* Check the configuration */
/* Get the input and output mode (if no buffer was previously provided, nothing will be read/written) */
if ((hfmac->InputAccess == FMAC_BUFFER_ACCESS_POLLING) && (hfmac->pInput != NULL))
{
inpolling = POLLING_ENABLED;
}
else
{
inpolling = POLLING_DISABLED;
}
if ((hfmac->OutputAccess == FMAC_BUFFER_ACCESS_POLLING) && (hfmac->pOutput != NULL))
{
outpolling = POLLING_ENABLED;
}
else
{
outpolling = POLLING_DISABLED;
}
/* Check the configuration */
if ((inpolling == POLLING_DISABLED) && (outpolling == POLLING_DISABLED))
{
return HAL_ERROR;
}
/* Check handle state is ready */
if (hfmac->State == HAL_FMAC_STATE_READY)
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Loop on reading and writing until timeout */
while ((HAL_GetTick() - tickstart) < Timeout)
{
/* X1: Check the mode: polling or none */
if (inpolling != POLLING_DISABLED)
{
FMAC_WriteDataIncrementPtr(hfmac, MAX_FILTER_DATA_SIZE_TO_HANDLE);
if (hfmac->InputCurrentSize == *(hfmac->pInputSize))
{
inpollingover = POLLING_STOPPED;
}
}
/* Y: Check the mode: polling or none */
if (outpolling != POLLING_DISABLED)
{
FMAC_ReadDataIncrementPtr(hfmac, MAX_FILTER_DATA_SIZE_TO_HANDLE);
if (hfmac->OutputCurrentSize == *(hfmac->pOutputSize))
{
outpollingover = POLLING_STOPPED;
}
}
/* Exit if there isn't data to handle anymore on one side or another */
if ((inpollingover != POLLING_NOT_STOPPED) || (outpollingover != POLLING_NOT_STOPPED))
{
break;
}
}
/* Change the FMAC state; update the input and output sizes; reset the indexes */
if (inpolling != POLLING_DISABLED)
{
(*(hfmac->pInputSize)) = hfmac->InputCurrentSize;
FMAC_ResetInputStateAndDataPointers(hfmac);
}
if (outpolling != POLLING_DISABLED)
{
(*(hfmac->pOutputSize)) = hfmac->OutputCurrentSize;
FMAC_ResetOutputStateAndDataPointers(hfmac);
}
/* Reset the busy flag (do not overwrite the possible write and read flag) */
hfmac->State = HAL_FMAC_STATE_READY;
if ((HAL_GetTick() - tickstart) >= Timeout)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
status = HAL_ERROR;
}
else
{
status = HAL_OK;
}
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @brief Stop the FMAC processing.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval HAL_StatusTypeDef HAL status
*/
HAL_StatusTypeDef HAL_FMAC_FilterStop(FMAC_HandleTypeDef *hfmac)
{
HAL_StatusTypeDef status;
/* Check handle state is ready */
if (hfmac->State == HAL_FMAC_STATE_READY)
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* Set the START bit to 0 (stop the previously configured filter) */
CLEAR_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START);
/* Disable the interrupts in order to avoid crossing cases */
CLEAR_BIT(hfmac->Instance->CR, FMAC_DMA_REN | FMAC_DMA_WEN | FMAC_IT_RIEN | FMAC_IT_WIEN);
/* In case of IT, update the sizes */
if ((hfmac->InputAccess == FMAC_BUFFER_ACCESS_IT) && (hfmac->pInput != NULL))
{
(*(hfmac->pInputSize)) = hfmac->InputCurrentSize;
}
if ((hfmac->OutputAccess == FMAC_BUFFER_ACCESS_IT) && (hfmac->pOutput != NULL))
{
(*(hfmac->pOutputSize)) = hfmac->OutputCurrentSize;
}
/* Reset FMAC unit (internal pointers) */
if (FMAC_Reset(hfmac) == HAL_ERROR)
{
/* Update FMAC error code and FMAC peripheral state */
hfmac->ErrorCode = HAL_FMAC_ERROR_RESET;
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
status = HAL_ERROR;
}
else
{
/* Reset the data pointers */
FMAC_ResetDataPointers(hfmac);
status = HAL_OK;
}
/* Reset the busy flag */
hfmac->State = HAL_FMAC_STATE_READY;
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @}
*/
/** @defgroup FMAC_Exported_Functions_Group3 Callback functions
* @brief Callback functions.
*
@verbatim
==============================================================================
##### Callback functions #####
==============================================================================
[..] This section provides Interruption and DMA callback functions:
(+) DMA or Interrupt: the user's input data is half written (DMA only)
or completely written.
(+) DMA or Interrupt: the user's output buffer is half filled (DMA only)
or completely filled.
(+) DMA or Interrupt: error handling.
@endverbatim
* @{
*/
/**
* @brief FMAC error callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_ErrorCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_ErrorCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC get half data callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_HalfGetDataCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_HalfGetDataCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC get data callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_GetDataCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_GetDataCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC half output data ready callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_HalfOutputDataReadyCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_HalfOutputDataReadyCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC output data ready callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_OutputDataReadyCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_OutputDataReadyCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC filter configuration callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_FilterConfigCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_FilterConfigCallback can be implemented in the user file.
*/
}
/**
* @brief FMAC filter preload callback.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
__weak void HAL_FMAC_FilterPreloadCallback(FMAC_HandleTypeDef *hfmac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmac);
/* NOTE : This function should not be modified; when the callback is needed,
the HAL_FMAC_FilterPreloadCallback can be implemented in the user file.
*/
}
/**
* @}
*/
/** @defgroup FMAC_Exported_Functions_Group4 IRQ handler management
* @brief IRQ handler.
*
@verbatim
==============================================================================
##### IRQ handler management #####
==============================================================================
[..] This section provides IRQ handler function.
@endverbatim
* @{
*/
/**
* @brief Handle FMAC interrupt request.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval None
*/
void HAL_FMAC_IRQHandler(FMAC_HandleTypeDef *hfmac)
{
uint32_t itsource;
/* Check if the read interrupt is enabled and if Y buffer empty flag isn't set */
itsource = __HAL_FMAC_GET_IT_SOURCE(hfmac, FMAC_IT_RIEN);
if ((__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_YEMPTY) == 0U) && (itsource != 0U))
{
/* Read some data if possible (Y size is used as a pseudo timeout in order
to not get stuck too long under IT if FMAC keeps on processing input
data reloaded via DMA for instance). */
if (hfmac->pOutput != NULL)
{
FMAC_ReadDataIncrementPtr(hfmac, (uint16_t)FMAC_GET_Y_SIZE(hfmac));
}
/* Indicate that data is ready to be read */
if ((hfmac->pOutput == NULL) || (hfmac->OutputCurrentSize == *(hfmac->pOutputSize)))
{
/* Reset the pointers to indicate new data will be needed */
FMAC_ResetOutputStateAndDataPointers(hfmac);
/* Call the output data ready callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->OutputDataReadyCallback(hfmac);
#else
HAL_FMAC_OutputDataReadyCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
}
/* Check if the write interrupt is enabled and if X1 buffer full flag isn't set */
itsource = __HAL_FMAC_GET_IT_SOURCE(hfmac, FMAC_IT_WIEN);
if ((__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_X1FULL) == 0U) && (itsource != 0U))
{
/* Write some data if possible (X1 size is used as a pseudo timeout in order
to not get stuck too long under IT if FMAC keep on processing input
data whereas its output emptied via DMA for instance). */
if (hfmac->pInput != NULL)
{
FMAC_WriteDataIncrementPtr(hfmac, (uint16_t)FMAC_GET_X1_SIZE(hfmac));
}
/* Indicate that new data will be needed */
if ((hfmac->pInput == NULL) || (hfmac->InputCurrentSize == *(hfmac->pInputSize)))
{
/* Reset the pointers to indicate new data will be needed */
FMAC_ResetInputStateAndDataPointers(hfmac);
/* Call the get data callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->GetDataCallback(hfmac);
#else
HAL_FMAC_GetDataCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
}
/* Check if the overflow error interrupt is enabled and if overflow error flag is raised */
itsource = __HAL_FMAC_GET_IT_SOURCE(hfmac, FMAC_IT_OVFLIEN);
if ((__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_OVFL) != 0U) && (itsource != 0U))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_OVFL;
}
/* Check if the underflow error interrupt is enabled and if underflow error flag is raised */
itsource = __HAL_FMAC_GET_IT_SOURCE(hfmac, FMAC_IT_UNFLIEN);
if ((__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_UNFL) != 0U) && (itsource != 0U))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_UNFL;
}
/* Check if the saturation error interrupt is enabled and if saturation error flag is raised */
itsource = __HAL_FMAC_GET_IT_SOURCE(hfmac, FMAC_IT_SATIEN);
if ((__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_SAT) != 0U) && (itsource != 0U))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_SAT;
}
/* Call the error callback if an error occurred */
if (hfmac->ErrorCode != HAL_FMAC_ERROR_NONE)
{
/* Call the error callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->ErrorCallback(hfmac);
#else
HAL_FMAC_ErrorCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
}
/**
* @}
*/
/** @defgroup FMAC_Exported_Functions_Group5 Peripheral State and Error functions
* @brief Peripheral State and Error functions.
*
@verbatim
==============================================================================
##### Peripheral State and Error functions #####
==============================================================================
[..] This subsection provides functions allowing to
(+) Check the FMAC state
(+) Get error code
@endverbatim
* @{
*/
/**
* @brief Return the FMAC state.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @retval HAL_FMAC_StateTypeDef FMAC state
*/
HAL_FMAC_StateTypeDef HAL_FMAC_GetState(FMAC_HandleTypeDef *hfmac)
{
/* Return FMAC state */
return hfmac->State;
}
/**
* @brief Return the FMAC peripheral error.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @note The returned error is a bit-map combination of possible errors.
* @retval uint32_t Error bit-map based on @ref FMAC_Error_Code
*/
uint32_t HAL_FMAC_GetError(FMAC_HandleTypeDef *hfmac)
{
/* Return FMAC error code */
return hfmac->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup FMAC_Private_Functions FMAC Private Functions
* @{
*/
/**
==============================================================================
##### FMAC Private Functions #####
==============================================================================
*/
/**
* @brief Perform a reset of the FMAC unit.
* @param hfmac FMAC handle.
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_Reset(FMAC_HandleTypeDef *hfmac)
{
uint32_t tickstart;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* Perform the reset */
SET_BIT(hfmac->Instance->CR, FMAC_CR_RESET);
/* Wait until flag is reset */
while (READ_BIT(hfmac->Instance->CR, FMAC_CR_RESET) != 0U)
{
if ((HAL_GetTick() - tickstart) > HAL_FMAC_RESET_TIMEOUT_VALUE)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
hfmac->ErrorCode = HAL_FMAC_ERROR_NONE;
return HAL_OK;
}
/**
* @brief Reset the data pointers of the FMAC unit.
* @param hfmac FMAC handle.
* @retval None
*/
static void FMAC_ResetDataPointers(FMAC_HandleTypeDef *hfmac)
{
FMAC_ResetInputStateAndDataPointers(hfmac);
FMAC_ResetOutputStateAndDataPointers(hfmac);
}
/**
* @brief Reset the input data pointers of the FMAC unit.
* @param hfmac FMAC handle.
* @retval None
*/
static void FMAC_ResetInputStateAndDataPointers(FMAC_HandleTypeDef *hfmac)
{
hfmac->pInput = NULL;
hfmac->pInputSize = NULL;
hfmac->InputCurrentSize = 0U;
hfmac->WrState = HAL_FMAC_STATE_READY;
}
/**
* @brief Reset the output data pointers of the FMAC unit.
* @param hfmac FMAC handle.
* @retval None
*/
static void FMAC_ResetOutputStateAndDataPointers(FMAC_HandleTypeDef *hfmac)
{
hfmac->pOutput = NULL;
hfmac->pOutputSize = NULL;
hfmac->OutputCurrentSize = 0U;
hfmac->RdState = HAL_FMAC_STATE_READY;
}
/**
* @brief Configure the FMAC filter.
* @note The configuration is done according to the parameters
* specified in the FMAC_FilterConfigTypeDef structure.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pConfig pointer to a FMAC_FilterConfigTypeDef structure that
* contains the FMAC configuration information.
* @param PreloadAccess access mode used for the preload (polling or DMA).
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_FilterConfig(FMAC_HandleTypeDef *hfmac, FMAC_FilterConfigTypeDef *pConfig,
uint8_t PreloadAccess)
{
uint32_t tickstart;
uint32_t tmpcr;
#if defined(USE_FULL_ASSERT)
uint32_t x2size;
#endif /* USE_FULL_ASSERT */
/* Check the parameters */
assert_param(IS_FMAC_THRESHOLD(pConfig->InputThreshold));
assert_param(IS_FMAC_THRESHOLD(pConfig->OutputThreshold));
assert_param(IS_FMAC_BUFFER_ACCESS(pConfig->InputAccess));
assert_param(IS_FMAC_BUFFER_ACCESS(pConfig->OutputAccess));
assert_param(IS_FMAC_CLIP_STATE(pConfig->Clip));
assert_param(IS_FMAC_FILTER_FUNCTION(pConfig->Filter));
assert_param(IS_FMAC_PARAM_P(pConfig->Filter, pConfig->P));
assert_param(IS_FMAC_PARAM_Q(pConfig->Filter, pConfig->Q));
assert_param(IS_FMAC_PARAM_R(pConfig->Filter, pConfig->R));
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) != 0U)
{
return HAL_ERROR;
}
/* Check handle state is ready */
if (hfmac->State != HAL_FMAC_STATE_READY)
{
return HAL_ERROR;
}
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Indicate that there is no valid configuration done */
hfmac->FilterParam = 0U;
/* FMAC_X1BUFCFG: Configure the input buffer within the internal memory if required */
if (pConfig->InputBufferSize != 0U)
{
MODIFY_REG(hfmac->Instance->X1BUFCFG, \
(FMAC_X1BUFCFG_X1_BASE | FMAC_X1BUFCFG_X1_BUF_SIZE), \
(((((uint32_t)(pConfig->InputBaseAddress)) << FMAC_X1BUFCFG_X1_BASE_Pos) & FMAC_X1BUFCFG_X1_BASE) | \
((((uint32_t)(pConfig->InputBufferSize)) << FMAC_X1BUFCFG_X1_BUF_SIZE_Pos) & \
FMAC_X1BUFCFG_X1_BUF_SIZE)));
}
/* FMAC_X1BUFCFG: Configure the input threshold if valid when compared to the configured X1 size */
if (pConfig->InputThreshold != FMAC_THRESHOLD_NO_VALUE)
{
/* Check the parameter */
assert_param(IS_FMAC_THRESHOLD_APPLICABLE(FMAC_GET_X1_SIZE(hfmac), pConfig->InputThreshold, pConfig->InputAccess));
MODIFY_REG(hfmac->Instance->X1BUFCFG, \
FMAC_X1BUFCFG_FULL_WM, \
((pConfig->InputThreshold) & FMAC_X1BUFCFG_FULL_WM));
}
/* FMAC_X2BUFCFG: Configure the coefficient buffer within the internal memory */
if (pConfig->CoeffBufferSize != 0U)
{
MODIFY_REG(hfmac->Instance->X2BUFCFG, \
(FMAC_X2BUFCFG_X2_BASE | FMAC_X2BUFCFG_X2_BUF_SIZE), \
(((((uint32_t)(pConfig->CoeffBaseAddress)) << FMAC_X2BUFCFG_X2_BASE_Pos) & FMAC_X2BUFCFG_X2_BASE) | \
((((uint32_t)(pConfig->CoeffBufferSize)) << FMAC_X2BUFCFG_X2_BUF_SIZE_Pos) &\
FMAC_X2BUFCFG_X2_BUF_SIZE)));
}
/* FMAC_YBUFCFG: Configure the output buffer within the internal memory if required */
if (pConfig->OutputBufferSize != 0U)
{
MODIFY_REG(hfmac->Instance->YBUFCFG, \
(FMAC_YBUFCFG_Y_BASE | FMAC_YBUFCFG_Y_BUF_SIZE), \
(((((uint32_t)(pConfig->OutputBaseAddress)) << FMAC_YBUFCFG_Y_BASE_Pos) & FMAC_YBUFCFG_Y_BASE) | \
((((uint32_t)(pConfig->OutputBufferSize)) << FMAC_YBUFCFG_Y_BUF_SIZE_Pos) & FMAC_YBUFCFG_Y_BUF_SIZE)));
}
/* FMAC_YBUFCFG: Configure the output threshold if valid when compared to the configured Y size */
if (pConfig->OutputThreshold != FMAC_THRESHOLD_NO_VALUE)
{
/* Check the parameter */
assert_param(IS_FMAC_THRESHOLD_APPLICABLE(FMAC_GET_Y_SIZE(hfmac), pConfig->OutputThreshold, pConfig->OutputAccess));
MODIFY_REG(hfmac->Instance->YBUFCFG, \
FMAC_YBUFCFG_EMPTY_WM, \
((pConfig->OutputThreshold) & FMAC_YBUFCFG_EMPTY_WM));
}
/* FMAC_CR: Configure the clip feature */
tmpcr = pConfig->Clip & FMAC_CR_CLIPEN;
/* FMAC_CR: If IT or DMA will be used, enable error interrupts.
* Being more a debugging feature, FMAC_CR_SATIEN isn't enabled by default. */
if ((pConfig->InputAccess == FMAC_BUFFER_ACCESS_DMA) || (pConfig->InputAccess == FMAC_BUFFER_ACCESS_IT) ||
(pConfig->OutputAccess == FMAC_BUFFER_ACCESS_DMA) || (pConfig->OutputAccess == FMAC_BUFFER_ACCESS_IT))
{
tmpcr |= FMAC_IT_UNFLIEN | FMAC_IT_OVFLIEN;
}
/* FMAC_CR: write the value */
WRITE_REG(hfmac->Instance->CR, tmpcr);
/* Save the input/output accesses in order to configure RIEN, WIEN, DMAREN and DMAWEN during filter start */
hfmac->InputAccess = pConfig->InputAccess;
hfmac->OutputAccess = pConfig->OutputAccess;
/* Check whether the configured X2 is big enough for the filter */
#if defined(USE_FULL_ASSERT)
x2size = FMAC_GET_X2_SIZE(hfmac);
#endif /* USE_FULL_ASSERT */
assert_param(((pConfig->Filter == FMAC_FUNC_CONVO_FIR) && (x2size >= pConfig->P)) || \
((pConfig->Filter == FMAC_FUNC_IIR_DIRECT_FORM_1) && \
(x2size >= ((uint32_t)pConfig->P + (uint32_t)pConfig->Q))));
/* Build the PARAM value that will be used when starting the filter */
hfmac->FilterParam = (FMAC_PARAM_START | pConfig->Filter | \
((((uint32_t)(pConfig->P)) << FMAC_PARAM_P_Pos) & FMAC_PARAM_P) | \
((((uint32_t)(pConfig->Q)) << FMAC_PARAM_Q_Pos) & FMAC_PARAM_Q) | \
((((uint32_t)(pConfig->R)) << FMAC_PARAM_R_Pos) & FMAC_PARAM_R));
/* Initialize the coefficient buffer if required (pCoeffA for FIR only) */
if ((pConfig->pCoeffB != NULL) && (pConfig->CoeffBSize != 0U))
{
/* FIR/IIR: The provided coefficients should match X2 size */
assert_param(((uint32_t)pConfig->CoeffASize + (uint32_t)pConfig->CoeffBSize) <= x2size);
/* FIR/IIR: The size of pCoeffB should match the parameter P */
assert_param(pConfig->CoeffBSize >= pConfig->P);
/* pCoeffA should be provided for IIR but not for FIR */
/* IIR : if pCoeffB is provided, pCoeffA should also be there */
/* IIR: The size of pCoeffA should match the parameter Q */
assert_param(((pConfig->Filter == FMAC_FUNC_CONVO_FIR) &&
(pConfig->pCoeffA == NULL) && (pConfig->CoeffASize == 0U)) ||
((pConfig->Filter == FMAC_FUNC_IIR_DIRECT_FORM_1) &&
(pConfig->pCoeffA != NULL) && (pConfig->CoeffASize != 0U) &&
(pConfig->CoeffASize >= pConfig->Q)));
/* Write number of values to be loaded, the data load function and start the operation */
WRITE_REG(hfmac->Instance->PARAM, \
(((uint32_t)(pConfig->CoeffBSize) << FMAC_PARAM_P_Pos) | \
((uint32_t)(pConfig->CoeffASize) << FMAC_PARAM_Q_Pos) | \
FMAC_FUNC_LOAD_X2 | FMAC_PARAM_START));
if (PreloadAccess == PRELOAD_ACCESS_POLLING)
{
/* Load the buffer into the internal memory */
FMAC_WritePreloadDataIncrementPtr(hfmac, &(pConfig->pCoeffB), pConfig->CoeffBSize);
/* Load pCoeffA if needed */
if ((pConfig->pCoeffA != NULL) && (pConfig->CoeffASize != 0U))
{
/* Load the buffer into the internal memory */
FMAC_WritePreloadDataIncrementPtr(hfmac, &(pConfig->pCoeffA), pConfig->CoeffASize);
}
/* Wait for the end of the writing */
if (FMAC_WaitOnStartUntilTimeout(hfmac, tickstart, HAL_FMAC_TIMEOUT_VALUE) != HAL_OK)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
return HAL_ERROR;
}
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_READY;
}
else
{
hfmac->pInput = pConfig->pCoeffA;
hfmac->InputCurrentSize = pConfig->CoeffASize;
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaPreload->XferHalfCpltCallback = NULL;
hfmac->hdmaPreload->XferCpltCallback = FMAC_DMAFilterConfig;
/* Set the DMA error callback */
hfmac->hdmaPreload->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC preload data write */
return (HAL_DMA_Start_IT(hfmac->hdmaPreload, (uint32_t)pConfig->pCoeffB, (uint32_t)&hfmac->Instance->WDATA,
pConfig->CoeffBSize));
}
}
else
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_READY;
}
return HAL_OK;
}
/**
* @brief Preload the input (FIR, IIR) and output data (IIR) of the FMAC filter.
* @note The set(s) of data will be used by FMAC as soon as @ref HAL_FMAC_FilterStart is called.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pInput Preloading of the first elements of the input buffer (X1).
* If not needed (no data available when starting), it should be set to NULL.
* @param InputSize Size of the input vector.
* As pInput is used for preloading data, it cannot be bigger than the input memory area.
* @param pOutput [IIR] Preloading of the first elements of the output vector (Y).
* If not needed, it should be set to NULL.
* @param OutputSize Size of the output vector.
* As pOutput is used for preloading data, it cannot be bigger than the output memory area.
* @param PreloadAccess access mode used for the preload (polling or DMA).
* @note The input and the output buffers can be filled by calling several times @ref HAL_FMAC_FilterPreload
* (each call filling partly the buffers). In case of overflow (too much data provided through
* all these calls), an error will be returned.
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_FilterPreload(FMAC_HandleTypeDef *hfmac, int16_t *pInput, uint8_t InputSize,
int16_t *pOutput, uint8_t OutputSize, uint8_t PreloadAccess)
{
uint32_t tickstart;
HAL_StatusTypeDef status;
/* Check the START bit state */
if (FMAC_GET_START_BIT(hfmac) != 0U)
{
return HAL_ERROR;
}
/* Check that a valid configuration was done previously */
if (hfmac->FilterParam == 0U)
{
return HAL_ERROR;
}
/* Check the preload input buffers isn't too big */
if ((InputSize > FMAC_GET_X1_SIZE(hfmac)) && (pInput != NULL))
{
return HAL_ERROR;
}
/* Check the preload output buffer isn't too big */
if ((OutputSize > FMAC_GET_Y_SIZE(hfmac)) && (pOutput != NULL))
{
return HAL_ERROR;
}
/* Check handle state is ready */
if (hfmac->State != HAL_FMAC_STATE_READY)
{
return HAL_ERROR;
}
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Preload the input buffer if required */
if ((pInput != NULL) && (InputSize != 0U))
{
/* Write number of values to be loaded, the data load function and start the operation */
WRITE_REG(hfmac->Instance->PARAM, \
(((uint32_t)InputSize << FMAC_PARAM_P_Pos) | FMAC_FUNC_LOAD_X1 | FMAC_PARAM_START));
if (PreloadAccess == PRELOAD_ACCESS_POLLING)
{
/* Load the buffer into the internal memory */
FMAC_WritePreloadDataIncrementPtr(hfmac, &pInput, InputSize);
/* Wait for the end of the writing */
if (FMAC_WaitOnStartUntilTimeout(hfmac, tickstart, HAL_FMAC_TIMEOUT_VALUE) != HAL_OK)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
return HAL_ERROR;
}
}
else
{
hfmac->pInput = pOutput;
hfmac->InputCurrentSize = OutputSize;
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaPreload->XferHalfCpltCallback = NULL;
hfmac->hdmaPreload->XferCpltCallback = FMAC_DMAFilterPreload;
/* Set the DMA error callback */
hfmac->hdmaPreload->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC preload data write */
return (HAL_DMA_Start_IT(hfmac->hdmaPreload, (uint32_t)pInput, (uint32_t)&hfmac->Instance->WDATA, InputSize));
}
}
/* Preload the output buffer if required */
if ((pOutput != NULL) && (OutputSize != 0U))
{
/* Write number of values to be loaded, the data load function and start the operation */
WRITE_REG(hfmac->Instance->PARAM, \
(((uint32_t)OutputSize << FMAC_PARAM_P_Pos) | FMAC_FUNC_LOAD_Y | FMAC_PARAM_START));
if (PreloadAccess == PRELOAD_ACCESS_POLLING)
{
/* Load the buffer into the internal memory */
FMAC_WritePreloadDataIncrementPtr(hfmac, &pOutput, OutputSize);
/* Wait for the end of the writing */
if (FMAC_WaitOnStartUntilTimeout(hfmac, tickstart, HAL_FMAC_TIMEOUT_VALUE) != HAL_OK)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
return HAL_ERROR;
}
}
else
{
hfmac->pInput = NULL;
hfmac->InputCurrentSize = 0U;
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaPreload->XferHalfCpltCallback = NULL;
hfmac->hdmaPreload->XferCpltCallback = FMAC_DMAFilterPreload;
/* Set the DMA error callback */
hfmac->hdmaPreload->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC preload data write */
return (HAL_DMA_Start_IT(hfmac->hdmaPreload, (uint32_t)pOutput, (uint32_t)&hfmac->Instance->WDATA, OutputSize));
}
}
/* Update the error codes */
if (__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_OVFL))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_OVFL;
}
if (__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_UNFL))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_UNFL;
}
if (__HAL_FMAC_GET_FLAG(hfmac, FMAC_FLAG_SAT))
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_SAT;
}
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_READY;
/* Return function status */
if (hfmac->ErrorCode == HAL_FMAC_ERROR_NONE)
{
status = HAL_OK;
}
else
{
status = HAL_ERROR;
}
return status;
}
/**
* @brief Write data into FMAC internal memory through WDATA and increment input buffer pointer.
* @note This function is only used with preload functions.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param ppData pointer to pointer to the data buffer.
* @param Size size of the data buffer.
* @retval None
*/
static void FMAC_WritePreloadDataIncrementPtr(FMAC_HandleTypeDef *hfmac, int16_t **ppData, uint8_t Size)
{
uint8_t index;
/* Load the buffer into the internal memory */
for (index = Size; index > 0U; index--)
{
WRITE_REG(hfmac->Instance->WDATA, (((uint32_t)(*(*ppData))) & FMAC_WDATA_WDATA));
(*ppData)++;
}
}
/**
* @brief Handle FMAC Function Timeout.
* @param hfmac FMAC handle.
* @param Tickstart Tick start value.
* @param Timeout Timeout duration.
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_WaitOnStartUntilTimeout(FMAC_HandleTypeDef *hfmac, uint32_t Tickstart, uint32_t Timeout)
{
/* Wait until flag changes */
while (READ_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START) != 0U)
{
if ((HAL_GetTick() - Tickstart) > Timeout)
{
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
return HAL_ERROR;
}
}
return HAL_OK;
}
/**
* @brief Register the new input buffer, update DMA configuration if needed and change the FMAC state.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pInput New input vector (additional input data).
* @param pInputSize Size of the input vector (if all the data can't be
* written, it will be updated with the number of data read from FMAC).
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_AppendFilterDataUpdateState(FMAC_HandleTypeDef *hfmac, int16_t *pInput,
uint16_t *pInputSize)
{
/* Change the FMAC state */
hfmac->WrState = HAL_FMAC_STATE_BUSY_WR;
/* Reset the current size */
hfmac->InputCurrentSize = 0U;
/* Handle the pointer depending on the input access */
if (hfmac->InputAccess == FMAC_BUFFER_ACCESS_DMA)
{
hfmac->pInput = NULL;
hfmac->pInputSize = NULL;
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaIn->XferHalfCpltCallback = FMAC_DMAHalfGetData;
hfmac->hdmaIn->XferCpltCallback = FMAC_DMAGetData;
/* Set the DMA error callback */
hfmac->hdmaIn->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC input data write */
return (HAL_DMA_Start_IT(hfmac->hdmaIn, (uint32_t)pInput, (uint32_t)&hfmac->Instance->WDATA, *pInputSize));
}
else
{
/* Update the input data information (polling, IT) */
hfmac->pInput = pInput;
hfmac->pInputSize = pInputSize;
}
return HAL_OK;
}
/**
* @brief Register the new output buffer, update DMA configuration if needed and change the FMAC state.
* @param hfmac pointer to a FMAC_HandleTypeDef structure that contains
* the configuration information for FMAC module.
* @param pOutput New output vector.
* @param pOutputSize Size of the output vector (if the vector can't
* be entirely filled, pOutputSize will be updated with the number
* of data read from FMAC).
* @retval HAL_StatusTypeDef HAL status
*/
static HAL_StatusTypeDef FMAC_ConfigFilterOutputBufferUpdateState(FMAC_HandleTypeDef *hfmac, int16_t *pOutput,
uint16_t *pOutputSize)
{
/* Reset the current size */
hfmac->OutputCurrentSize = 0U;
/* Check whether a valid pointer was provided */
if ((pOutput == NULL) || (pOutputSize == NULL) || (*pOutputSize == 0U))
{
/* The user will have to provide a valid configuration later */
hfmac->pOutput = NULL;
hfmac->pOutputSize = NULL;
hfmac->RdState = HAL_FMAC_STATE_READY;
}
/* Handle the pointer depending on the input access */
else if (hfmac->OutputAccess == FMAC_BUFFER_ACCESS_DMA)
{
hfmac->pOutput = NULL;
hfmac->pOutputSize = NULL;
hfmac->RdState = HAL_FMAC_STATE_BUSY_RD;
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaOut->XferHalfCpltCallback = FMAC_DMAHalfOutputDataReady;
hfmac->hdmaOut->XferCpltCallback = FMAC_DMAOutputDataReady;
/* Set the DMA error callback */
hfmac->hdmaOut->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC output data read */
return (HAL_DMA_Start_IT(hfmac->hdmaOut, (uint32_t)&hfmac->Instance->RDATA, (uint32_t)pOutput, *pOutputSize));
}
else if (hfmac->OutputAccess == FMAC_BUFFER_ACCESS_NONE)
{
hfmac->pOutput = NULL;
hfmac->pOutputSize = NULL;
hfmac->RdState = HAL_FMAC_STATE_READY;
}
else
{
/* Update the output data information (polling, IT) */
hfmac->pOutput = pOutput;
hfmac->pOutputSize = pOutputSize;
hfmac->RdState = HAL_FMAC_STATE_BUSY_RD;
}
return HAL_OK;
}
/**
* @brief Read available output data until Y EMPTY is set.
* @param hfmac FMAC handle.
* @param MaxSizeToRead Maximum number of data to read (this serves as a timeout
* if FMAC continuously writes into the output buffer).
* @retval None
*/
static void FMAC_ReadDataIncrementPtr(FMAC_HandleTypeDef *hfmac, uint16_t MaxSizeToRead)
{
uint16_t maxsize;
uint16_t threshold;
uint32_t tmpvalue;
/* Check if there is data to read */
if (READ_BIT(hfmac->Instance->SR, FMAC_SR_YEMPTY) != 0U)
{
return;
}
/* Get the maximum index (no wait allowed, no overstepping of the output buffer) */
if ((hfmac->OutputCurrentSize + MaxSizeToRead) > *(hfmac->pOutputSize))
{
maxsize = *(hfmac->pOutputSize);
}
else
{
maxsize = hfmac->OutputCurrentSize + MaxSizeToRead;
}
/* Read until there is no more room or no more data */
do
{
/* If there is no more room, return */
if (!(hfmac->OutputCurrentSize < maxsize))
{
return;
}
/* Read the available data */
tmpvalue = ((READ_REG(hfmac->Instance->RDATA))& FMAC_RDATA_RDATA);
*(hfmac->pOutput) = (int16_t)tmpvalue;
hfmac->pOutput++;
hfmac->OutputCurrentSize++;
} while (READ_BIT(hfmac->Instance->SR, FMAC_SR_YEMPTY) == 0U);
/* Y buffer empty flag has just be raised, read the threshold */
threshold = (uint16_t)FMAC_GET_THRESHOLD_FROM_WM(FMAC_GET_Y_EMPTY_WM(hfmac)) - 1U;
/* Update the maximum size if needed (limited data available) */
if ((hfmac->OutputCurrentSize + threshold) < maxsize)
{
maxsize = hfmac->OutputCurrentSize + threshold;
}
/* Read the available data */
while (hfmac->OutputCurrentSize < maxsize)
{
tmpvalue = ((READ_REG(hfmac->Instance->RDATA))& FMAC_RDATA_RDATA);
*(hfmac->pOutput) = (int16_t)tmpvalue;
hfmac->pOutput++;
hfmac->OutputCurrentSize++;
}
}
/**
* @brief Write available input data until X1 FULL is set.
* @param hfmac FMAC handle.
* @param MaxSizeToWrite Maximum number of data to write (this serves as a timeout
* if FMAC continuously empties the input buffer).
* @retval None
*/
static void FMAC_WriteDataIncrementPtr(FMAC_HandleTypeDef *hfmac, uint16_t MaxSizeToWrite)
{
uint16_t maxsize;
uint16_t threshold;
/* Check if there is room in FMAC */
if (READ_BIT(hfmac->Instance->SR, FMAC_SR_X1FULL) != 0U)
{
return;
}
/* Get the maximum index (no wait allowed, no overstepping of the output buffer) */
if ((hfmac->InputCurrentSize + MaxSizeToWrite) > *(hfmac->pInputSize))
{
maxsize = *(hfmac->pInputSize);
}
else
{
maxsize = hfmac->InputCurrentSize + MaxSizeToWrite;
}
/* Write until there is no more room or no more data */
do
{
/* If there is no more room, return */
if (!(hfmac->InputCurrentSize < maxsize))
{
return;
}
/* Write the available data */
WRITE_REG(hfmac->Instance->WDATA, (((uint32_t)(*(hfmac->pInput))) & FMAC_WDATA_WDATA));
hfmac->pInput++;
hfmac->InputCurrentSize++;
} while (READ_BIT(hfmac->Instance->SR, FMAC_SR_X1FULL) == 0U);
/* X1 buffer full flag has just be raised, read the threshold */
threshold = (uint16_t)FMAC_GET_THRESHOLD_FROM_WM(FMAC_GET_X1_FULL_WM(hfmac)) - 1U;
/* Update the maximum size if needed (limited data available) */
if ((hfmac->InputCurrentSize + threshold) < maxsize)
{
maxsize = hfmac->InputCurrentSize + threshold;
}
/* Write the available data */
while (hfmac->InputCurrentSize < maxsize)
{
WRITE_REG(hfmac->Instance->WDATA, (((uint32_t)(*(hfmac->pInput))) & FMAC_WDATA_WDATA));
hfmac->pInput++;
hfmac->InputCurrentSize++;
}
}
/**
* @brief DMA FMAC Input Data process half complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAHalfGetData(DMA_HandleTypeDef *hdma)
{
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Call half get data callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->HalfGetDataCallback(hfmac);
#else
HAL_FMAC_HalfGetDataCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA FMAC Input Data process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAGetData(DMA_HandleTypeDef *hdma)
{
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Reset the pointers to indicate new data will be needed */
FMAC_ResetInputStateAndDataPointers(hfmac);
/* Call get data callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->GetDataCallback(hfmac);
#else
HAL_FMAC_GetDataCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA FMAC Output Data process half complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAHalfOutputDataReady(DMA_HandleTypeDef *hdma)
{
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Call half output data ready callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->HalfOutputDataReadyCallback(hfmac);
#else
HAL_FMAC_HalfOutputDataReadyCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA FMAC Output Data process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAOutputDataReady(DMA_HandleTypeDef *hdma)
{
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Reset the pointers to indicate new data will be needed */
FMAC_ResetOutputStateAndDataPointers(hfmac);
/* Call output data ready callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->OutputDataReadyCallback(hfmac);
#else
HAL_FMAC_OutputDataReadyCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA FMAC Filter Configuration process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAFilterConfig(DMA_HandleTypeDef *hdma)
{
uint8_t index;
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* If needed, write CoeffA and exit */
if (hfmac->pInput != NULL)
{
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaPreload->XferHalfCpltCallback = NULL;
hfmac->hdmaPreload->XferCpltCallback = FMAC_DMAFilterConfig;
/* Set the DMA error callback */
hfmac->hdmaPreload->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC preload data write */
if (HAL_DMA_Start_IT(hfmac->hdmaPreload, (uint32_t)hfmac->pInput, (uint32_t)&hfmac->Instance->WDATA,
hfmac->InputCurrentSize) == HAL_OK)
{
hfmac->pInput = NULL;
hfmac->InputCurrentSize = 0U;
return;
}
/* If not exited, there was an error: set FMAC handle state to error */
hfmac->State = HAL_FMAC_STATE_ERROR;
}
else
{
/* Wait for the end of the writing */
for (index = 0U; index < MAX_PRELOAD_INDEX; index++)
{
if (READ_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START) == 0U)
{
break;
}
}
/* If 'START' is still set, there was a timeout: set FMAC handle state to timeout */
if (READ_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START) != 0U)
{
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
}
else
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_READY;
/* Call output data ready callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->FilterConfigCallback(hfmac);
#else
HAL_FMAC_FilterConfigCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
return;
}
}
/* If not exited, there was an error: set FMAC handle error code to DMA error */
hfmac->ErrorCode |= HAL_FMAC_ERROR_DMA;
/* Call user callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->ErrorCallback(hfmac);
#else
HAL_FMAC_ErrorCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA FMAC Filter Configuration process complete callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAFilterPreload(DMA_HandleTypeDef *hdma)
{
uint8_t index;
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Wait for the end of the X1 writing */
for (index = 0U; index < MAX_PRELOAD_INDEX; index++)
{
if (READ_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START) == 0U)
{
break;
}
}
/* If 'START' is still set, there was an error: set FMAC handle state to error */
if (READ_BIT(hfmac->Instance->PARAM, FMAC_PARAM_START) != 0U)
{
hfmac->State = HAL_FMAC_STATE_TIMEOUT;
hfmac->ErrorCode |= HAL_FMAC_ERROR_TIMEOUT;
}
/* If needed, preload Y buffer */
else if ((hfmac->pInput != NULL) && (hfmac->InputCurrentSize != 0U))
{
/* Write number of values to be loaded, the data load function and start the operation */
WRITE_REG(hfmac->Instance->PARAM, \
(((uint32_t)(hfmac->InputCurrentSize) << FMAC_PARAM_P_Pos) | FMAC_FUNC_LOAD_Y | FMAC_PARAM_START));
/* Set the FMAC DMA transfer complete callback */
hfmac->hdmaPreload->XferHalfCpltCallback = NULL;
hfmac->hdmaPreload->XferCpltCallback = FMAC_DMAFilterPreload;
/* Set the DMA error callback */
hfmac->hdmaPreload->XferErrorCallback = FMAC_DMAError;
/* Enable the DMA stream managing FMAC preload data write */
if (HAL_DMA_Start_IT(hfmac->hdmaPreload, (uint32_t)hfmac->pInput, (uint32_t)&hfmac->Instance->WDATA,
hfmac->InputCurrentSize) == HAL_OK)
{
hfmac->pInput = NULL;
hfmac->InputCurrentSize = 0U;
return;
}
/* If not exited, there was an error */
hfmac->ErrorCode = HAL_FMAC_ERROR_DMA;
hfmac->State = HAL_FMAC_STATE_ERROR;
}
else
{
/* nothing to do */
}
if (hfmac->ErrorCode == HAL_FMAC_ERROR_NONE)
{
/* Change the FMAC state */
hfmac->State = HAL_FMAC_STATE_READY;
/* Call output data ready callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->FilterPreloadCallback(hfmac);
#else
HAL_FMAC_FilterPreloadCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
else
{
/* Call user callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->ErrorCallback(hfmac);
#else
HAL_FMAC_ErrorCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
}
/**
* @brief DMA FMAC communication error callback.
* @param hdma DMA handle.
* @retval None
*/
static void FMAC_DMAError(DMA_HandleTypeDef *hdma)
{
FMAC_HandleTypeDef *hfmac = (FMAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Set FMAC handle state to error */
hfmac->State = HAL_FMAC_STATE_ERROR;
/* Set FMAC handle error code to DMA error */
hfmac->ErrorCode |= HAL_FMAC_ERROR_DMA;
/* Call user callback */
#if (USE_HAL_FMAC_REGISTER_CALLBACKS == 1)
hfmac->ErrorCallback(hfmac);
#else
HAL_FMAC_ErrorCallback(hfmac);
#endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_FMAC_MODULE_ENABLED */
#endif /* FMAC */
| 88,987 |
C
| 34.076074 | 120 | 0.634542 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_pcd_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_pcd_ex.c
* @author MCD Application Team
* @brief PCD Extended HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Extended features functions
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup PCDEx PCDEx
* @brief PCD Extended HAL module driver
* @{
*/
#ifdef HAL_PCD_MODULE_ENABLED
#if defined (USB)
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions
* @{
*/
/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions
* @brief PCDEx control functions
*
@verbatim
===============================================================================
##### Extended features functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Update FIFO configuration
@endverbatim
* @{
*/
/**
* @brief Configure PMA for EP
* @param hpcd Device instance
* @param ep_addr endpoint address
* @param ep_kind endpoint Kind
* USB_SNG_BUF: Single Buffer used
* USB_DBL_BUF: Double Buffer used
* @param pmaadress: EP address in The PMA: In case of single buffer endpoint
* this parameter is 16-bit value providing the address
* in PMA allocated to endpoint.
* In case of double buffer endpoint this parameter
* is a 32-bit value providing the endpoint buffer 0 address
* in the LSB part of 32-bit value and endpoint buffer 1 address
* in the MSB part of 32-bit value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr,
uint16_t ep_kind, uint32_t pmaadress)
{
PCD_EPTypeDef *ep;
/* initialize ep structure*/
if ((0x80U & ep_addr) == 0x80U)
{
ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK];
}
else
{
ep = &hpcd->OUT_ep[ep_addr];
}
/* Here we check if the endpoint is single or double Buffer*/
if (ep_kind == PCD_SNG_BUF)
{
/* Single Buffer */
ep->doublebuffer = 0U;
/* Configure the PMA */
ep->pmaadress = (uint16_t)pmaadress;
}
#if (USE_USB_DOUBLE_BUFFER == 1U)
else /* USB_DBL_BUF */
{
/* Double Buffer Endpoint */
ep->doublebuffer = 1U;
/* Configure the PMA */
ep->pmaaddr0 = (uint16_t)(pmaadress & 0xFFFFU);
ep->pmaaddr1 = (uint16_t)((pmaadress & 0xFFFF0000U) >> 16);
}
#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */
return HAL_OK;
}
/**
* @brief Activate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 1U;
/* Enable BCD feature */
USBx->BCDR |= USB_BCDR_BCDEN;
/* Enable DCD : Data Contact Detect */
USBx->BCDR &= ~(USB_BCDR_PDEN);
USBx->BCDR &= ~(USB_BCDR_SDEN);
USBx->BCDR |= USB_BCDR_DCDEN;
return HAL_OK;
}
/**
* @brief Deactivate BatteryCharging feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->battery_charging_active = 0U;
/* Disable BCD feature */
USBx->BCDR &= ~(USB_BCDR_BCDEN);
return HAL_OK;
}
/**
* @brief Handle BatteryCharging Process.
* @param hpcd PCD handle
* @retval HAL status
*/
void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
uint32_t tickstart = HAL_GetTick();
/* Wait Detect flag or a timeout is happen */
while ((USBx->BCDR & USB_BCDR_DCDET) == 0U)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > 1000U)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_ERROR);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
return;
}
}
HAL_Delay(200U);
/* Data Pin Contact ? Check Detect flag */
if ((USBx->BCDR & USB_BCDR_DCDET) == USB_BCDR_DCDET)
{
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Primary detection: checks if connected to Standard Downstream Port
(without charging capability) */
USBx->BCDR &= ~(USB_BCDR_DCDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_PDEN);
HAL_Delay(50U);
/* If Charger detect ? */
if ((USBx->BCDR & USB_BCDR_PDET) == USB_BCDR_PDET)
{
/* Start secondary detection to check connection to Charging Downstream
Port or Dedicated Charging Port */
USBx->BCDR &= ~(USB_BCDR_PDEN);
HAL_Delay(50U);
USBx->BCDR |= (USB_BCDR_SDEN);
HAL_Delay(50U);
/* If CDP ? */
if ((USBx->BCDR & USB_BCDR_SDET) == USB_BCDR_SDET)
{
/* Dedicated Downstream Port DCP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
else
{
/* Charging Downstream Port CDP */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
}
else /* NO */
{
/* Standard Downstream Port */
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/* Battery Charging capability discovery finished Start Enumeration */
(void)HAL_PCDEx_DeActivateBCD(hpcd);
#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U)
hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#else
HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED);
#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */
}
/**
* @brief Activate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 1U;
hpcd->LPM_State = LPM_L0;
USBx->LPMCSR |= USB_LPMCSR_LMPEN;
USBx->LPMCSR |= USB_LPMCSR_LPMACK;
return HAL_OK;
}
/**
* @brief Deactivate LPM feature.
* @param hpcd PCD handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd)
{
USB_TypeDef *USBx = hpcd->Instance;
hpcd->lpm_active = 0U;
USBx->LPMCSR &= ~(USB_LPMCSR_LMPEN);
USBx->LPMCSR &= ~(USB_LPMCSR_LPMACK);
return HAL_OK;
}
/**
* @brief Send LPM message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_LPM_Callback could be implemented in the user file
*/
}
/**
* @brief Send BatteryCharging message to user layer callback.
* @param hpcd PCD handle
* @param msg LPM message
* @retval HAL status
*/
__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpcd);
UNUSED(msg);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PCDEx_BCD_Callback could be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined (USB) */
#endif /* HAL_PCD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
| 9,188 |
C
| 26.348214 | 83 | 0.581084 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_dac.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_dac.c
* @author MCD Application Team
* @brief DAC LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_dac.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined(DAC1) || defined(DAC2) || defined(DAC3) ||defined (DAC4)
/** @addtogroup DAC_LL DAC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DAC_LL_Private_Macros
* @{
*/
#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx)
#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \
(((__DACX__) == DAC2) ? \
((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
: \
(((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
|| ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2)) \
)
#else
#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \
(((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
|| ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \
)
#endif
#if defined(STM32G474xx) || defined(STM32G484xx)
#define IS_LL_DAC_TRIGGER_SOURCE(__DACX__, __TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM3_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG1) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG2) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG3) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG4) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG5) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_RST_TRG6) \
|| (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \
: ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \
|| (((__DACX__) == DAC1) && ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_TRGO1))\
|| (((__DACX__) == DAC2) && ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_TRGO2))\
|| (((__DACX__) == DAC3) && ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_TRGO3))\
|| (((__DACX__) == DAC4) && ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_TRGO1))\
)
#else
#define IS_LL_DAC_TRIGGER_SOURCE(__DACX__, __TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM3_TRGO) \
|| (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \
: ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \
)
#endif
#if defined(STM32G474xx) || defined(STM32G484xx)
#define IS_LL_DAC_TRIGGER_SOURCE2(__DACX__, __TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE10) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM3_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG1) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG2) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG3) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG4) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG5) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_HRTIM_STEP_TRG6) \
|| (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \
: ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \
)
#else
#define IS_LL_DAC_TRIGGER_SOURCE2(__DACX__, __TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE10) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM3_TRGO) \
|| (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \
: ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \
)
#endif
#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) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_SAWTOOTH) \
)
#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)) \
) \
||(((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_SAWTOOTH) \
&& (((__WAVE_AUTO_GENERATION_CONFIG__) & ~(DAC_STR1_STINCDATA1|DAC_STR1_STDIR1|DAC_STR1_STRSTDATA1)) \
== 0UL) \
) \
)
#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
if (DACx == DAC1)
{
/* Force reset of DAC clock */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_DAC1);
/* Release reset of DAC clock */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_DAC1);
}
#endif
#ifdef DAC2
if (DACx == DAC2)
{
/* Force reset of DAC clock */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_DAC2);
/* Release reset of DAC clock */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_DAC2);
}
#endif
#ifdef DAC3
if (DACx == DAC3)
{
/* Force reset of DAC clock */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_DAC3);
/* Release reset of DAC clock */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_DAC3);
}
#endif
#ifdef DAC4
if (DACx == DAC4)
{
/* Force reset of DAC clock */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_DAC4);
/* Release reset of DAC clock */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_DAC4);
}
#endif
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 (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @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(DACx, DAC_Channel));
assert_param(IS_LL_DAC_TRIGGER_SOURCE(DACx, 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)
{
if (DAC_InitStruct->WaveAutoGeneration == LL_DAC_WAVE_AUTO_GENERATION_SAWTOOTH)
{
assert_param(IS_LL_DAC_TRIGGER_SOURCE2(DACx, DAC_InitStruct->TriggerSource2));
MODIFY_REG(DACx->CR,
DAC_CR_WAVE1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK),
DAC_InitStruct->WaveAutoGeneration << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
MODIFY_REG(DACx->STMODR,
(DAC_STMODR_STINCTRIGSEL1 | DAC_STMODR_STRSTTRIGSEL1) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK),
(
((DAC_InitStruct->TriggerSource >> DAC_CR_TSEL1_Pos) << DAC_STMODR_STRSTTRIGSEL1_Pos)
| ((DAC_InitStruct->TriggerSource2 >> DAC_CR_TSEL1_Pos) << DAC_STMODR_STINCTRIGSEL1_Pos)
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
WRITE_REG(*(__DAC_PTR_REG_OFFSET(DACx->STR1, (DAC_Channel >> DAC_REG_STRX_REGOFFSET_BITOFFSET_POS) & DAC_REG_STRX_REGOFFSET_MASK_POSBIT0)),
DAC_InitStruct->WaveAutoGenerationConfig);
}
else
{
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->TriggerSource2 = 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 || DAC2 || DAC3 || DAC4 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 20,763 |
C
| 47.627635 | 147 | 0.475991 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_crc.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_crc.c
* @author MCD Application Team
* @brief CRC LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_crc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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 */
| 2,460 |
C
| 22.663461 | 85 | 0.457724 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_nand.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_nand.c
* @author MCD Application Team
* @brief NAND HAL module driver.
* This file provides a generic firmware to drive NAND memories mounted
* as external device.
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
This driver is a generic layered driver which contains a set of APIs used to
control NAND flash memories. It uses the FMC layer functions to interface
with NAND devices. This driver is used as follows:
(+) NAND flash memory configuration sequence using the function HAL_NAND_Init()
with control and timing parameters for both common and attribute spaces.
(+) Read NAND flash memory maker and device IDs using the function
HAL_NAND_Read_ID(). The read information is stored in the NAND_ID_TypeDef
structure declared by the function caller.
(+) Access NAND flash memory by read/write operations using the functions
HAL_NAND_Read_Page_8b()/HAL_NAND_Read_SpareArea_8b(),
HAL_NAND_Write_Page_8b()/HAL_NAND_Write_SpareArea_8b(),
HAL_NAND_Read_Page_16b()/HAL_NAND_Read_SpareArea_16b(),
HAL_NAND_Write_Page_16b()/HAL_NAND_Write_SpareArea_16b()
to read/write page(s)/spare area(s). These functions use specific device
information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef
structure. The read/write address information is contained by the Nand_Address_Typedef
structure passed as parameter.
(+) Perform NAND flash Reset chip operation using the function HAL_NAND_Reset().
(+) Perform NAND flash erase block operation using the function HAL_NAND_Erase_Block().
The erase block address information is contained in the Nand_Address_Typedef
structure passed as parameter.
(+) Read the NAND flash status operation using the function HAL_NAND_Read_Status().
(+) You can also control the NAND device by calling the control APIs HAL_NAND_ECC_Enable()/
HAL_NAND_ECC_Disable() to respectively enable/disable the ECC code correction
feature or the function HAL_NAND_GetECC() to get the ECC correction code.
(+) You can monitor the NAND device HAL state by calling the function
HAL_NAND_GetState()
[..]
(@) This driver is a set of generic APIs which handle standard NAND flash operations.
If a NAND flash device contains different operations and/or implementations,
it should be implemented separately.
*** Callback registration ***
=============================================
[..]
The compilation define USE_HAL_NAND_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_NAND_RegisterCallback() to register a user callback,
it allows to register following callbacks:
(+) MspInitCallback : NAND MspInit.
(+) MspDeInitCallback : NAND MspDeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
Use function HAL_NAND_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function. It allows to reset following callbacks:
(+) MspInitCallback : NAND MspInit.
(+) MspDeInitCallback : NAND MspDeInit.
This function) takes as parameters the HAL peripheral handle and the Callback ID.
By default, after the HAL_NAND_Init and if the state is HAL_NAND_STATE_RESET
all callbacks are reset to the corresponding legacy weak (surcharged) functions.
Exception done for MspInit and MspDeInit callbacks that are respectively
reset to the legacy weak (surcharged) functions in the HAL_NAND_Init
and HAL_NAND_DeInit only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_NAND_Init and HAL_NAND_DeInit
keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
Callbacks can be registered/unregistered in READY state only.
Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered
in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used
during the Init/DeInit.
In that case first register the MspInit/MspDeInit user callbacks
using HAL_NAND_RegisterCallback before calling HAL_NAND_DeInit
or HAL_NAND_Init function.
When The compilation define USE_HAL_NAND_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registering feature is not available
and weak (surcharged) callbacks are used.
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
#if defined(FMC_BANK3)
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_NAND_MODULE_ENABLED
/** @defgroup NAND NAND
* @brief NAND HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private Constants ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup NAND_Exported_Functions NAND Exported Functions
* @{
*/
/** @defgroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### NAND Initialization and de-initialization functions #####
==============================================================================
[..]
This section provides functions allowing to initialize/de-initialize
the NAND memory
@endverbatim
* @{
*/
/**
* @brief Perform NAND memory Initialization sequence
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param ComSpace_Timing pointer to Common space timing structure
* @param AttSpace_Timing pointer to Attribute space timing structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing,
FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing)
{
/* Check the NAND handle state */
if (hnand == NULL)
{
return HAL_ERROR;
}
if (hnand->State == HAL_NAND_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hnand->Lock = HAL_UNLOCKED;
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
if (hnand->MspInitCallback == NULL)
{
hnand->MspInitCallback = HAL_NAND_MspInit;
}
hnand->ItCallback = HAL_NAND_ITCallback;
/* Init the low level hardware */
hnand->MspInitCallback(hnand);
#else
/* Initialize the low level hardware (MSP) */
HAL_NAND_MspInit(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
}
/* Initialize NAND control Interface */
(void)FMC_NAND_Init(hnand->Instance, &(hnand->Init));
/* Initialize NAND common space timing Interface */
(void)FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank);
/* Initialize NAND attribute space timing Interface */
(void)FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank);
/* Enable the NAND device */
__FMC_NAND_ENABLE(hnand->Instance);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
return HAL_OK;
}
/**
* @brief Perform NAND memory De-Initialization sequence
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand)
{
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
if (hnand->MspDeInitCallback == NULL)
{
hnand->MspDeInitCallback = HAL_NAND_MspDeInit;
}
/* DeInit the low level hardware */
hnand->MspDeInitCallback(hnand);
#else
/* Initialize the low level hardware (MSP) */
HAL_NAND_MspDeInit(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
/* Configure the NAND registers with their reset values */
(void)FMC_NAND_DeInit(hnand->Instance, hnand->Init.NandBank);
/* Reset the NAND controller state */
hnand->State = HAL_NAND_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief NAND MSP Init
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_MspInit could be implemented in the user file
*/
}
/**
* @brief NAND MSP DeInit
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_MspDeInit could be implemented in the user file
*/
}
/**
* @brief This function handles NAND device interrupt request.
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand)
{
/* Check NAND interrupt Rising edge flag */
if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE))
{
/* NAND interrupt callback*/
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
hnand->ItCallback(hnand);
#else
HAL_NAND_ITCallback(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
/* Clear NAND interrupt Rising edge pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_RISING_EDGE);
}
/* Check NAND interrupt Level flag */
if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL))
{
/* NAND interrupt callback*/
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
hnand->ItCallback(hnand);
#else
HAL_NAND_ITCallback(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
/* Clear NAND interrupt Level pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_LEVEL);
}
/* Check NAND interrupt Falling edge flag */
if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE))
{
/* NAND interrupt callback*/
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
hnand->ItCallback(hnand);
#else
HAL_NAND_ITCallback(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
/* Clear NAND interrupt Falling edge pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FALLING_EDGE);
}
/* Check NAND interrupt FIFO empty flag */
if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT))
{
/* NAND interrupt callback*/
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
hnand->ItCallback(hnand);
#else
HAL_NAND_ITCallback(hnand);
#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */
/* Clear NAND interrupt FIFO empty pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FEMPT);
}
}
/**
* @brief NAND interrupt feature callback
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_ITCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group2 Input and Output functions
* @brief Input Output and memory control functions
*
@verbatim
==============================================================================
##### NAND Input and Output functions #####
==============================================================================
[..]
This section provides functions allowing to use and control the NAND
memory
@endverbatim
* @{
*/
/**
* @brief Read the NAND memory electronic signature
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pNAND_ID NAND ID structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID)
{
__IO uint32_t data = 0;
__IO uint32_t data1 = 0;
uint32_t deviceaddress;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* Send Read ID command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_READID;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;
__DSB();
/* Read the electronic signature from NAND flash */
if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8)
{
data = *(__IO uint32_t *)deviceaddress;
/* Return the data read */
pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data);
pNAND_ID->Device_Id = ADDR_2ND_CYCLE(data);
pNAND_ID->Third_Id = ADDR_3RD_CYCLE(data);
pNAND_ID->Fourth_Id = ADDR_4TH_CYCLE(data);
}
else
{
data = *(__IO uint32_t *)deviceaddress;
data1 = *((__IO uint32_t *)deviceaddress + 4);
/* Return the data read */
pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data);
pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data);
pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1);
pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief NAND memory reset
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand)
{
uint32_t deviceaddress;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* Send NAND reset command */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = 0xFF;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Configure the device: Enter the physical parameters of the device
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig)
{
hnand->Config.PageSize = pDeviceConfig->PageSize;
hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize;
hnand->Config.BlockSize = pDeviceConfig->BlockSize;
hnand->Config.BlockNbr = pDeviceConfig->BlockNbr;
hnand->Config.PlaneSize = pDeviceConfig->PlaneSize;
hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr;
hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable;
return HAL_OK;
}
/**
* @brief Read Page(s) from NAND memory block (8-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to destination read buffer
* @param NumPageToRead number of pages to read from block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer,
uint32_t NumPageToRead)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numpagesread = 0U;
uint32_t nandaddress;
uint32_t nbpages = NumPageToRead;
uint8_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) read loop */
while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Send read page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if (hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00);
__DSB();
}
/* Get Data into Buffer */
for (index = 0U; index < hnand->Config.PageSize; index++)
{
*buff = *(uint8_t *)deviceaddress;
buff++;
}
/* Increment read pages number */
numpagesread++;
/* Decrement pages to read */
nbpages--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Read Page(s) from NAND memory block (16-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to destination read buffer. pBuffer should be 16bits aligned
* @param NumPageToRead number of pages to read from block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer,
uint32_t NumPageToRead)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numpagesread = 0U;
uint32_t nandaddress;
uint32_t nbpages = NumPageToRead;
uint16_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) read loop */
while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Send read page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if (hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00);
__DSB();
}
/* Calculate PageSize */
if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8)
{
hnand->Config.PageSize = hnand->Config.PageSize / 2U;
}
else
{
/* Do nothing */
/* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/
}
/* Get Data into Buffer */
for (index = 0U; index < hnand->Config.PageSize; index++)
{
*buff = *(uint16_t *)deviceaddress;
buff++;
}
/* Increment read pages number */
numpagesread++;
/* Decrement pages to read */
nbpages--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Write Page(s) to NAND memory block (8-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write
* @param NumPageToWrite number of pages to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer,
uint32_t NumPageToWrite)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numpageswritten = 0U;
uint32_t nandaddress;
uint32_t nbpages = NumPageToWrite;
uint8_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) write loop */
while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Send write page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
/* Write data to memory */
for (index = 0U; index < hnand->Config.PageSize; index++)
{
*(__IO uint8_t *)deviceaddress = *buff;
buff++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Increment written pages number */
numpageswritten++;
/* Decrement pages to write */
nbpages--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Write Page(s) to NAND memory block (16-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned
* @param NumPageToWrite number of pages to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer,
uint32_t NumPageToWrite)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numpageswritten = 0U;
uint32_t nandaddress;
uint32_t nbpages = NumPageToWrite;
uint16_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) write loop */
while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Send write page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
/* Calculate PageSize */
if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8)
{
hnand->Config.PageSize = hnand->Config.PageSize / 2U;
}
else
{
/* Do nothing */
/* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/
}
/* Write data to memory */
for (index = 0U; index < hnand->Config.PageSize; index++)
{
*(__IO uint16_t *)deviceaddress = *buff;
buff++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Increment written pages number */
numpageswritten++;
/* Decrement pages to write */
nbpages--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Read Spare area(s) from NAND memory (8-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write
* @param NumSpareAreaToRead Number of spare area to read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer,
uint32_t NumSpareAreaToRead)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numsparearearead = 0U;
uint32_t nandaddress;
uint32_t columnaddress;
uint32_t nbspare = NumSpareAreaToRead;
uint8_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnaddress = COLUMN_ADDRESS(hnand);
/* Spare area(s) read loop */
while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if (hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00);
__DSB();
}
/* Get Data into Buffer */
for (index = 0U; index < hnand->Config.SpareAreaSize; index++)
{
*buff = *(uint8_t *)deviceaddress;
buff++;
}
/* Increment read spare areas number */
numsparearearead++;
/* Decrement spare areas to read */
nbspare--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Read Spare area(s) from NAND memory (16-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned.
* @param NumSpareAreaToRead Number of spare area to read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress,
uint16_t *pBuffer, uint32_t NumSpareAreaToRead)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numsparearearead = 0U;
uint32_t nandaddress;
uint32_t columnaddress;
uint32_t nbspare = NumSpareAreaToRead;
uint16_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand));
/* Spare area(s) read loop */
while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if (hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00);
__DSB();
}
/* Get Data into Buffer */
for (index = 0U; index < hnand->Config.SpareAreaSize; index++)
{
*buff = *(uint16_t *)deviceaddress;
buff++;
}
/* Increment read spare areas number */
numsparearearead++;
/* Decrement spare areas to read */
nbspare--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Write Spare area(s) to NAND memory (8-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write
* @param NumSpareAreaTowrite number of spare areas to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress,
uint8_t *pBuffer, uint32_t NumSpareAreaTowrite)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numspareareawritten = 0U;
uint32_t nandaddress;
uint32_t columnaddress;
uint32_t nbspare = NumSpareAreaTowrite;
uint8_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* Page address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnaddress = COLUMN_ADDRESS(hnand);
/* Spare area(s) write loop */
while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
/* Write data to memory */
for (index = 0U; index < hnand->Config.SpareAreaSize; index++)
{
*(__IO uint8_t *)deviceaddress = *buff;
buff++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Increment written spare areas number */
numspareareawritten++;
/* Decrement spare areas to write */
nbspare--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Write Spare area(s) to NAND memory (16-bits addressing)
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned.
* @param NumSpareAreaTowrite number of spare areas to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress,
uint16_t *pBuffer, uint32_t NumSpareAreaTowrite)
{
uint32_t index;
uint32_t tickstart;
uint32_t deviceaddress;
uint32_t numspareareawritten = 0U;
uint32_t nandaddress;
uint32_t columnaddress;
uint32_t nbspare = NumSpareAreaTowrite;
uint16_t *buff = pBuffer;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* NAND raw address calculation */
nandaddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand));
/* Spare area(s) write loop */
while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* Cards with page size <= 512 bytes */
if ((hnand->Config.PageSize) <= 512U)
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U)
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress);
__DSB();
}
}
/* Write data to memory */
for (index = 0U; index < hnand->Config.SpareAreaSize; index++)
{
*(__IO uint16_t *)deviceaddress = *buff;
buff++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while (HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT)
{
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_ERROR;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_TIMEOUT;
}
}
/* Increment written spare areas number */
numspareareawritten++;
/* Decrement spare areas to write */
nbspare--;
/* Increment the NAND address */
nandaddress = (uint32_t)(nandaddress + 1U);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief NAND memory Block erase
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
uint32_t deviceaddress;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hnand);
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* Send Erase block command sequence */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1;
__DSB();
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Increment the NAND memory address
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress pointer to NAND address structure
* @retval The new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
uint32_t status = NAND_VALID_ADDRESS;
/* Increment page address */
pAddress->Page++;
/* Check NAND address is valid */
if (pAddress->Page == hnand->Config.BlockSize)
{
pAddress->Page = 0;
pAddress->Block++;
if (pAddress->Block == hnand->Config.PlaneSize)
{
pAddress->Block = 0;
pAddress->Plane++;
if (pAddress->Plane == (hnand->Config.PlaneNbr))
{
status = NAND_INVALID_ADDRESS;
}
}
}
return (status);
}
#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User NAND Callback
* To be used instead of the weak (surcharged) predefined callback
* @param hnand : NAND handle
* @param CallbackId : ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID
* @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID
* @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID
* @param pCallback : pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId,
pNAND_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hnand);
if (hnand->State == HAL_NAND_STATE_READY)
{
switch (CallbackId)
{
case HAL_NAND_MSP_INIT_CB_ID :
hnand->MspInitCallback = pCallback;
break;
case HAL_NAND_MSP_DEINIT_CB_ID :
hnand->MspDeInitCallback = pCallback;
break;
case HAL_NAND_IT_CB_ID :
hnand->ItCallback = pCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hnand->State == HAL_NAND_STATE_RESET)
{
switch (CallbackId)
{
case HAL_NAND_MSP_INIT_CB_ID :
hnand->MspInitCallback = pCallback;
break;
case HAL_NAND_MSP_DEINIT_CB_ID :
hnand->MspDeInitCallback = pCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hnand);
return status;
}
/**
* @brief Unregister a User NAND Callback
* NAND Callback is redirected to the weak (surcharged) predefined callback
* @param hnand : NAND handle
* @param CallbackId : ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID
* @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID
* @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID
* @retval status
*/
HAL_StatusTypeDef HAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hnand);
if (hnand->State == HAL_NAND_STATE_READY)
{
switch (CallbackId)
{
case HAL_NAND_MSP_INIT_CB_ID :
hnand->MspInitCallback = HAL_NAND_MspInit;
break;
case HAL_NAND_MSP_DEINIT_CB_ID :
hnand->MspDeInitCallback = HAL_NAND_MspDeInit;
break;
case HAL_NAND_IT_CB_ID :
hnand->ItCallback = HAL_NAND_ITCallback;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hnand->State == HAL_NAND_STATE_RESET)
{
switch (CallbackId)
{
case HAL_NAND_MSP_INIT_CB_ID :
hnand->MspInitCallback = HAL_NAND_MspInit;
break;
case HAL_NAND_MSP_DEINIT_CB_ID :
hnand->MspDeInitCallback = HAL_NAND_MspDeInit;
break;
default :
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hnand);
return status;
}
#endif /* USE_HAL_NAND_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group3 Peripheral Control functions
* @brief management functions
*
@verbatim
==============================================================================
##### NAND Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control dynamically
the NAND interface.
@endverbatim
* @{
*/
/**
* @brief Enables dynamically NAND ECC feature.
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand)
{
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Enable ECC feature */
(void)FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Disables dynamically FMC_NAND ECC feature.
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand)
{
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Disable ECC feature */
(void)FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
}
else
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Disables dynamically NAND ECC feature.
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param ECCval pointer to ECC value
* @param Timeout maximum timeout to wait
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout)
{
HAL_StatusTypeDef status;
/* Check the NAND controller state */
if (hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
else if (hnand->State == HAL_NAND_STATE_READY)
{
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Get NAND ECC value */
status = FMC_NAND_GetECC(hnand->Instance, ECCval, hnand->Init.NandBank, Timeout);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
}
else
{
return HAL_ERROR;
}
return status;
}
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions
*
@verbatim
==============================================================================
##### NAND State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the NAND controller
and the data flow.
@endverbatim
* @{
*/
/**
* @brief return the NAND state
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL state
*/
HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand)
{
return hnand->State;
}
/**
* @brief NAND memory read status
* @param hnand pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval NAND status
*/
uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand)
{
uint32_t data;
uint32_t deviceaddress;
UNUSED(hnand);
/* Identify the device address */
deviceaddress = NAND_DEVICE;
/* Send Read status operation command */
*(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_STATUS;
/* Read status register data */
data = *(__IO uint8_t *)deviceaddress;
/* Return the status */
if ((data & NAND_ERROR) == NAND_ERROR)
{
return NAND_ERROR;
}
else if ((data & NAND_READY) == NAND_READY)
{
return NAND_READY;
}
else
{
return NAND_BUSY;
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_NAND_MODULE_ENABLED */
/**
* @}
*/
#endif /* FMC_BANK3 */
| 72,429 |
C
| 31.305977 | 120 | 0.577034 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_crs.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_crs.h
* @author MCD Application Team
* @brief CRS LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2018 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 "stm32g4xx_ll_crs.h"
#include "stm32g4xx_ll_bus.h"
/** @addtogroup STM32G4xx_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 */
| 2,044 |
C
| 23.058823 | 82 | 0.424658 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_msp_template.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_msp_template.c
* @author MCD Application Team
* @brief HAL MSP module.
* This file template is located in the HAL folder and should be copied
* to the user folder.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @defgroup HAL_MSP HAL MSP module driver
* @brief HAL MSP module.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup HAL_MSP_Private_Functions
* @{
*/
/**
* @brief Initialize the Global MSP.
* @param None
* @retval None
*/
void HAL_MspInit(void)
{
/* NOTE : This function is generated automatically by STM32CubeMX and eventually
modified by the user
*/
}
/**
* @brief DeInitialize the Global MSP.
* @param None
* @retval None
*/
void HAL_MspDeInit(void)
{
/* NOTE : This function is generated automatically by STM32CubeMX and eventually
modified by the user
*/
}
/**
* @brief Initialize the PPP MSP.
* @param None
* @retval None
*/
void HAL_PPP_MspInit(void)
{
/* NOTE : This function is generated automatically by STM32CubeMX and eventually
modified by the user
*/
}
/**
* @brief DeInitialize the PPP MSP.
* @param None
* @retval None
*/
void HAL_PPP_MspDeInit(void)
{
/* NOTE : This function is generated automatically by STM32CubeMX and eventually
modified by the user
*/
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 2,545 |
C
| 23.480769 | 82 | 0.463654 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_cryp_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_cryp_ex.c
* @author MCD Application Team
* @brief CRYPEx HAL module driver.
* This file provides firmware functions to manage the extended
* functionalities of the Cryptography (CRYP) peripheral.
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
/** @addtogroup CRYPEx
* @{
*/
#if defined(AES)
#ifdef HAL_CRYP_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup CRYPEx_Private_Defines
* @{
*/
#define CRYP_PHASE_INIT 0x00000000U /*!< GCM/GMAC (or CCM) init phase */
#define CRYP_PHASE_HEADER AES_CR_GCMPH_0 /*!< GCM/GMAC or CCM header phase */
#define CRYP_PHASE_PAYLOAD AES_CR_GCMPH_1 /*!< GCM(/CCM) payload phase */
#define CRYP_PHASE_FINAL AES_CR_GCMPH /*!< GCM/GMAC or CCM final phase */
#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U /*!< Encryption mode */
#define CRYP_OPERATINGMODE_KEYDERIVATION AES_CR_MODE_0 /*!< Key derivation mode only used when performing ECB and CBC decryptions */
#define CRYP_OPERATINGMODE_DECRYPT AES_CR_MODE_1 /*!< Decryption */
#define CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT AES_CR_MODE /*!< Key derivation and decryption only used when performing ECB and CBC decryptions */
#define CRYPEx_PHASE_PROCESS 0x02U /*!< CRYP peripheral is in processing phase */
#define CRYPEx_PHASE_FINAL 0x03U /*!< CRYP peripheral is in final phase this is relevant only with CCM and GCM modes */
/* CTR0 information to use in CCM algorithm */
#define CRYP_CCM_CTR0_0 0x07FFFFFFU
#define CRYP_CCM_CTR0_3 0xFFFFFF00U
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions---------------------------------------------------------*/
/** @addtogroup CRYPEx_Exported_Functions
* @{
*/
/** @defgroup CRYPEx_Exported_Functions_Group1 Extended AES processing functions
* @brief Extended processing functions.
*
@verbatim
==============================================================================
##### Extended AES processing functions #####
==============================================================================
[..] This section provides functions allowing to generate the authentication
TAG in Polling mode
(#)HAL_CRYPEx_AESGCM_GenerateAuthTAG
(#)HAL_CRYPEx_AESCCM_GenerateAuthTAG
they should be used after Encrypt/Decrypt operation.
@endverbatim
* @{
*/
/**
* @brief generate the GCM authentication TAG.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param AuthTag Pointer to the authentication buffer
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYPEx_AESGCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout)
{
uint32_t tickstart;
/* Assume first Init.HeaderSize is in words */
uint64_t headerlength = (uint64_t)hcryp->Init.HeaderSize * 32U; /* Header length in bits */
uint64_t inputlength = (uint64_t)hcryp->SizesSum * 8U; /* Input length in bits */
uint32_t tagaddr = (uint32_t)AuthTag;
/* Correct headerlength if Init.HeaderSize is actually in bytes */
if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_BYTE)
{
headerlength /= 4U;
}
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process locked */
__HAL_LOCK(hcryp);
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if (hcryp->Phase == CRYPEx_PHASE_PROCESS)
{
/* Change the CRYP phase */
hcryp->Phase = CRYPEx_PHASE_FINAL;
}
else /* Initialization phase has not been performed*/
{
/* Disable the Peripheral */
__HAL_CRYP_DISABLE(hcryp);
/* Sequence error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_AUTH_TAG_SEQUENCE;
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Select final phase */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_FINAL);
/* Set the encrypt operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT);
/*TinyAES peripheral from V3.1.1 : data has to be inserted normally (no swapping)*/
/* Write into the AES_DINR register the number of bits in header (64 bits)
followed by the number of bits in the payload */
hcryp->Instance->DINR = 0U;
hcryp->Instance->DINR = (uint32_t)(headerlength);
hcryp->Instance->DINR = 0U;
hcryp->Instance->DINR = (uint32_t)(inputlength);
/* Wait for CCF flag to be raised */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF))
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout)||(Timeout == 0U))
{
/* Disable the CRYP peripheral clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
}
/* Read the authentication TAG in the output FIFO */
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
/* Clear CCF flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Disable the peripheral */
__HAL_CRYP_DISABLE(hcryp);
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
}
else
{
/* Busy error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_BUSY;
return HAL_ERROR;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief AES CCM Authentication TAG generation.
* @param hcryp pointer to a CRYP_HandleTypeDef structure that contains
* the configuration information for CRYP module
* @param AuthTag Pointer to the authentication buffer
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRYPEx_AESCCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout)
{
uint32_t tagaddr = (uint32_t)AuthTag;
uint32_t tickstart;
if (hcryp->State == HAL_CRYP_STATE_READY)
{
/* Process locked */
__HAL_LOCK(hcryp);
/* Disable interrupts in case they were kept enabled to proceed
a single message in several iterations */
__HAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE);
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_BUSY;
/* Check if initialization phase has already been performed */
if (hcryp->Phase == CRYPEx_PHASE_PROCESS)
{
/* Change the CRYP phase */
hcryp->Phase = CRYPEx_PHASE_FINAL;
}
else /* Initialization phase has not been performed*/
{
/* Disable the peripheral */
__HAL_CRYP_DISABLE(hcryp);
/* Sequence error code field */
hcryp->ErrorCode |= HAL_CRYP_ERROR_AUTH_TAG_SEQUENCE;
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
/* Select final phase */
MODIFY_REG(hcryp->Instance->CR, AES_CR_GCMPH, CRYP_PHASE_FINAL);
/* Set encrypt operating mode*/
MODIFY_REG(hcryp->Instance->CR, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT);
/* Wait for CCF flag to be raised */
tickstart = HAL_GetTick();
while (HAL_IS_BIT_CLR(hcryp->Instance->SR, AES_SR_CCF))
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - tickstart) > Timeout) ||(Timeout == 0U))
{
/* Disable the CRYP peripheral Clock */
__HAL_CRYP_DISABLE(hcryp);
/* Change state */
hcryp->ErrorCode |= HAL_CRYP_ERROR_TIMEOUT;
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
return HAL_ERROR;
}
}
}
/* Read the authentication TAG in the output FIFO */
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
tagaddr += 4U;
*(uint32_t *)(tagaddr) = hcryp->Instance->DOUTR;
/* Clear CCF Flag */
__HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR);
/* Change the CRYP peripheral state */
hcryp->State = HAL_CRYP_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hcryp);
/* Disable CRYP */
__HAL_CRYP_DISABLE(hcryp);
}
else
{
/* Busy error code field */
hcryp->ErrorCode = HAL_CRYP_ERROR_BUSY;
return HAL_ERROR;
}
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup CRYPEx_Exported_Functions_Group2 Extended AES Key Derivations functions
* @brief Extended Key Derivations functions.
*
@verbatim
==============================================================================
##### Key Derivation functions #####
==============================================================================
[..] This section provides functions allowing to Enable or Disable the
the AutoKeyDerivation parameter in CRYP_HandleTypeDef structure
These function are allowed only in TinyAES peripheral.
@endverbatim
* @{
*/
/**
* @brief AES enable key derivation functions
* @param hcryp pointer to a CRYP_HandleTypeDef structure.
*/
void HAL_CRYPEx_EnableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp)
{
if (hcryp->State == HAL_CRYP_STATE_READY)
{
hcryp->AutoKeyDerivation = ENABLE;
}
else
{
/* Busy error code field */
hcryp->ErrorCode = HAL_CRYP_ERROR_BUSY;
}
}
/**
* @brief AES disable key derivation functions
* @param hcryp pointer to a CRYP_HandleTypeDef structure.
*/
void HAL_CRYPEx_DisableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp)
{
if (hcryp->State == HAL_CRYP_STATE_READY)
{
hcryp->AutoKeyDerivation = DISABLE;
}
else
{
/* Busy error code field */
hcryp->ErrorCode = HAL_CRYP_ERROR_BUSY;
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_CRYP_MODULE_ENABLED */
#endif /* AES */
/**
* @}
*/
/**
* @}
*/
| 11,917 |
C
| 29.795866 | 165 | 0.568767 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_dac.c
|
/**
******************************************************************************
* @file stm32g4xx_hal_dac.c
* @author MCD Application Team
* @brief DAC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Digital to Analog Converter (DAC) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral Control functions
* + Peripheral State and Errors functions
*
*
******************************************************************************
* @attention
*
* Copyright (c) 2019 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
==============================================================================
##### DAC Peripheral features #####
==============================================================================
[..]
*** DAC Channels ***
====================
[..]
STM32G4 devices integrate up to seven 12-bit Digital Analog Converters,
up to six of them grouped by pair forming a DAC instance.
The 2 converters of an single instance (i.e. channel1 & channel2)
can be used independently or simultaneously (dual mode):
(#) DAC channel1 with DAC_OUT1 as output (not for all) or connected to on-chip
peripherals (ex. comparators, operational amplifier).
(#) DAC channel2 with DAC_OUT2 as output (not for all) or connected to on-chip
peripherals (ex. comparators, operational amplifier).
Note: when an instance only includes one converter, only independent mode is
supported by this converter.
STM32G4 instances & converters availability and output PIO mapping (DAC_OUTx):
----------------------------------------------------------------------------
| DAC1 | DAC2 | DAC3 | DAC4 |
----------------------------------------------------------------------------
Channel 1 | | YES | YES | YES | YES
| DAC_OUT1 | PA4 | PA6 | - | -
----------------------------------------------------------------------------
Channel 2 | | YES | NO | YES | YES
| DAC_OUT2 | PA5 | - | - | -
----------------------------------------------------------------------------
Note: On this STM32 series, all devices do not include each DAC instances listed
above. Refer to device datasheet for DACx instance availability.
*** DAC Triggers ***
====================
[..]
Digital to Analog conversion can be non-triggered using DAC_TRIGGER_NONE
and DAC_OUT1/DAC_OUT2 is available once writing to DHRx register.
[..]
Digital to Analog conversion can be triggered by:
(#) External event: EXTI Line 9 (any GPIOx_PIN_9) using DAC_TRIGGER_EXT_IT9.
The used pin (GPIOx_PIN_9) must be configured in input mode.
(#) Timers TRGO: TIM1, TIM2, TIM3, TIM4, TIM6, TIM7, TIM8 and TIM15
(DAC_TRIGGER_T2_TRGO, DAC_TRIGGER_T3_TRGO...)
(#) Software using DAC_TRIGGER_SOFTWARE
(#) HRTimer TRGO: HRTIM1 (1)
(DAC_TRIGGER_HRTIM_TRG01, DAC_TRIGGER_HRTIM_TRG02...)
[..]
Specific triggers for sawtooth generation:
(#) External event: EXTI Line 10 (any GPIOx_PIN_10) using DAC_TRIGGER_EXT_IT10.
The used pin (GPIOx_PIN_10) must be configured in input mode.
(#) HRTimer Step & Reset: HRTIM1 (1)
(DAC_TRIGGER_HRTIM_RST_TRG1, DAC_TRIGGER_HRTIM_STEP_TRG1...)
Note: On this STM32 series, parameter only available if HRTIM feature is
supported (refer to device datasheet for supported features list)
*** DAC Buffer mode feature ***
===============================
[..]
Each DAC channel integrates an output buffer that can be used to
reduce the output impedance, and to drive external loads directly
without having to add an external operational amplifier.
To enable, the output buffer use
sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
[..]
(@) Refer to the device datasheet for more details about output
impedance value with and without output buffer.
*** DAC connect feature ***
===============================
[..]
Each DAC channel can be connected internally.
To connect, use
sConfig.DAC_ConnectOnChipPeripheral = DAC_CHIPCONNECT_INTERNAL;
or
sConfig.DAC_ConnectOnChipPeripheral = DAC_CHIPCONNECT_BOTH;
*** GPIO configurations guidelines ***
=====================
[..]
When a DAC channel is used (ex channel1 on PA4) and the other is not
(ex channel2 on PA5 is configured in Analog and disabled).
Channel1 may disturb channel2 as coupling effect.
Note that there is no coupling on channel2 as soon as channel2 is turned on.
Coupling on adjacent channel could be avoided as follows:
when unused PA5 is configured as INPUT PULL-UP or DOWN.
PA5 is configured in ANALOG just before it is turned on.
*** DAC Sample and Hold feature ***
========================
[..]
For each converter, 2 modes are supported: normal mode and
"sample and hold" mode (i.e. low power mode).
In the sample and hold mode, the DAC core converts data, then holds the
converted voltage on a capacitor. When not converting, the DAC cores and
buffer are completely turned off between samples and the DAC output is
tri-stated, therefore reducing the overall power consumption. A new
stabilization period is needed before each new conversion.
The sample and hold allow setting internal or external voltage @
low power consumption cost (output value can be at any given rate either
by CPU or DMA).
The Sample and hold block and registers uses either LSI & run in
several power modes: run mode, sleep mode, low power run, low power sleep
mode & stop1 mode.
Low power stop1 mode allows only static conversion.
To enable Sample and Hold mode
Enable LSI using HAL_RCC_OscConfig with RCC_OSCILLATORTYPE_LSI &
RCC_LSI_ON parameters.
Use DAC_InitStructure.DAC_SampleAndHold = DAC_SAMPLEANDHOLD_ENABLE;
& DAC_ChannelConfTypeDef.DAC_SampleAndHoldConfig.DAC_SampleTime,
DAC_HoldTime & DAC_RefreshTime;
*** DAC calibration feature ***
===================================
[..]
(#) The 2 converters (channel1 & channel2) provide calibration capabilities.
(++) Calibration aims at correcting some offset of output buffer.
(++) The DAC uses either factory calibration settings OR user defined
calibration (trimming) settings (i.e. trimming mode).
(++) The user defined settings can be figured out using self calibration
handled by HAL_DACEx_SelfCalibrate.
(++) HAL_DACEx_SelfCalibrate:
(+++) Runs automatically the calibration.
(+++) Enables the user trimming mode
(+++) Updates a structure with trimming values with fresh calibration
results.
The user may store the calibration results for larger
(ex monitoring the trimming as a function of temperature
for instance)
*** DAC wave generation feature ***
===================================
[..]
Both DAC channels can be used to generate
(#) Noise wave
(#) Triangle wave
(#) Sawtooth wave
*** DAC data format ***
=======================
[..]
The DAC data format can be:
(#) 8-bit right alignment using DAC_ALIGN_8B_R
(#) 12-bit left alignment using DAC_ALIGN_12B_L
(#) 12-bit right alignment using DAC_ALIGN_12B_R
*** DAC data value to voltage correspondence ***
================================================
[..]
The analog output voltage on each DAC channel pin is determined
by the following equation:
[..]
DAC_OUTx = VREF+ * DOR / 4095
(+) with DOR is the Data Output Register
[..]
VREF+ is the input voltage reference (refer to the device datasheet)
[..]
e.g. To set DAC_OUT1 to 0.7V, use
(+) Assuming that VREF+ = 3.3V, DAC_OUT1 = (3.3 * 868) / 4095 = 0.7V
*** DMA requests ***
=====================
[..]
A DMAMUX request can be generated when an external trigger (but not a software trigger)
occurs if DMAMUX requests are enabled using HAL_DAC_Start_DMA().
DMAMUX requests are mapped as following:
----------------------------------------------------------------------------
| DAC1 | DAC2 | DAC3 | DAC4 |
----------------------------------------------------------------------------
Channel 1 | | 6 | 41 | 102 | 104
----------------------------------------------------------------------------
Channel 2 | | 7 | - | 103 | 105
----------------------------------------------------------------------------
Note: On this STM32 series, all devices do not include each DAC instances listed
above. Refer to device datasheet for DACx instance availability.
*** High frequency interface mode ***
=====================================
[..]
The high frequency interface informs DAC instance about the bus frequency in use.
It is mandatory information for DAC (as internal timing of DAC is bus frequency dependent)
provided thanks to parameter DAC_HighFrequency handled in HAL_DAC_ConfigChannel () function.
Use of DAC_HIGH_FREQUENCY_INTERFACE_MODE_AUTOMATIC value of DAC_HighFrequency is recommended
function figured out the correct setting.
The high frequency mode is same for all converters of a same DAC instance. Either same
parameter DAC_HighFrequency is used for all DAC converters or again self
DAC_HIGH_FREQUENCY_INTERFACE_MODE_AUTOMATIC detection parameter.
[..]
(@) For Dual mode and specific signal (Sawtooth, triangle and noise) generation
please refer to Extended Features Driver description
##### How to use this driver #####
==============================================================================
[..]
(+) DAC APB clock must be enabled to get write access to DAC
registers using HAL_DAC_Init()
(+) If available & needed, configure DAC_OUTx (DAC_OUT1, DAC_OUT2) in analog mode.
(+) Configure the DAC channel using HAL_DAC_ConfigChannel() function.
(+) Enable the DAC channel using HAL_DAC_Start() or HAL_DAC_Start_DMA() functions.
*** Calibration mode IO operation ***
======================================
[..]
(+) Retrieve the factory trimming (calibration settings) using HAL_DACEx_GetTrimOffset()
(+) Run the calibration using HAL_DACEx_SelfCalibrate()
(+) Update the trimming while DAC running using HAL_DACEx_SetUserTrimming()
*** Polling mode IO operation ***
=================================
[..]
(+) Start the DAC peripheral using HAL_DAC_Start()
(+) To read the DAC last data output value, use the HAL_DAC_GetValue() function.
(+) Stop the DAC peripheral using HAL_DAC_Stop()
*** DMA mode IO operation ***
==============================
[..]
(+) Start the DAC peripheral using HAL_DAC_Start_DMA(), at this stage the user specify the length
of data to be transferred at each end of conversion
First issued trigger will start the conversion of the value previously set by HAL_DAC_SetValue().
(+) At the middle of data transfer HAL_DAC_ConvHalfCpltCallbackCh1() or HAL_DACEx_ConvHalfCpltCallbackCh2()
function is executed and user can add his own code by customization of function pointer
HAL_DAC_ConvHalfCpltCallbackCh1() or HAL_DACEx_ConvHalfCpltCallbackCh2()
(+) At The end of data transfer HAL_DAC_ConvCpltCallbackCh1() or HAL_DACEx_ConvHalfCpltCallbackCh2()
function is executed and user can add his own code by customization of function pointer
HAL_DAC_ConvCpltCallbackCh1() or HAL_DACEx_ConvHalfCpltCallbackCh2()
(+) In case of transfer Error, HAL_DAC_ErrorCallbackCh1() function is executed and user can
add his own code by customization of function pointer HAL_DAC_ErrorCallbackCh1
(+) In case of DMA underrun, DAC interruption triggers and execute internal function HAL_DAC_IRQHandler.
HAL_DAC_DMAUnderrunCallbackCh1() or HAL_DACEx_DMAUnderrunCallbackCh2()
function is executed and user can add his own code by customization of function pointer
HAL_DAC_DMAUnderrunCallbackCh1() or HAL_DACEx_DMAUnderrunCallbackCh2() and
add his own code by customization of function pointer HAL_DAC_ErrorCallbackCh1()
(+) Stop the DAC peripheral using HAL_DAC_Stop_DMA()
*** Callback registration ***
=============================================
[..]
The compilation define USE_HAL_DAC_REGISTER_CALLBACKS when set to 1
allows the user to configure dynamically the driver callbacks.
Use Functions HAL_DAC_RegisterCallback() to register a user callback,
it allows to register following callbacks:
(+) ConvCpltCallbackCh1 : callback when a half transfer is completed on Ch1.
(+) ConvHalfCpltCallbackCh1 : callback when a transfer is completed on Ch1.
(+) ErrorCallbackCh1 : callback when an error occurs on Ch1.
(+) DMAUnderrunCallbackCh1 : callback when an underrun error occurs on Ch1.
(+) ConvCpltCallbackCh2 : callback when a half transfer is completed on Ch2.
(+) ConvHalfCpltCallbackCh2 : callback when a transfer is completed on Ch2.
(+) ErrorCallbackCh2 : callback when an error occurs on Ch2.
(+) DMAUnderrunCallbackCh2 : callback when an underrun error occurs on Ch2.
(+) MspInitCallback : DAC MspInit.
(+) MspDeInitCallback : DAC MspdeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
Use function HAL_DAC_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function. It allows to reset following callbacks:
(+) ConvCpltCallbackCh1 : callback when a half transfer is completed on Ch1.
(+) ConvHalfCpltCallbackCh1 : callback when a transfer is completed on Ch1.
(+) ErrorCallbackCh1 : callback when an error occurs on Ch1.
(+) DMAUnderrunCallbackCh1 : callback when an underrun error occurs on Ch1.
(+) ConvCpltCallbackCh2 : callback when a half transfer is completed on Ch2.
(+) ConvHalfCpltCallbackCh2 : callback when a transfer is completed on Ch2.
(+) ErrorCallbackCh2 : callback when an error occurs on Ch2.
(+) DMAUnderrunCallbackCh2 : callback when an underrun error occurs on Ch2.
(+) MspInitCallback : DAC MspInit.
(+) MspDeInitCallback : DAC MspdeInit.
(+) All Callbacks
This function) takes as parameters the HAL peripheral handle and the Callback ID.
By default, after the HAL_DAC_Init and if the state is HAL_DAC_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_DAC_Init
and HAL_DAC_DeInit only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the HAL_DAC_Init and HAL_DAC_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_DAC_RegisterCallback before calling HAL_DAC_DeInit
or HAL_DAC_Init function.
When The compilation define USE_HAL_DAC_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registering feature is not available
and weak (surcharged) callbacks are used.
*** DAC HAL driver macros list ***
=============================================
[..]
Below the list of most used macros in DAC HAL driver.
(+) __HAL_DAC_ENABLE : Enable the DAC peripheral
(+) __HAL_DAC_DISABLE : Disable the DAC peripheral
(+) __HAL_DAC_CLEAR_FLAG: Clear the DAC's pending flags
(+) __HAL_DAC_GET_FLAG: Get the selected DAC's flag status
[..]
(@) You can refer to the DAC HAL driver header file for more useful macros
@endverbatim
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_HAL_Driver
* @{
*/
#ifdef HAL_DAC_MODULE_ENABLED
#if defined(DAC1) || defined(DAC2) || defined(DAC3) ||defined (DAC4)
/** @defgroup DAC DAC
* @brief DAC driver modules
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup DAC_Private_Constants DAC Private Constants
* @{
*/
#define TIMEOUT_DAC_CALIBCONFIG 1U /* 1 ms */
#define HFSEL_ENABLE_THRESHOLD_80MHZ 80000000U /* 80 MHz */
#define HFSEL_ENABLE_THRESHOLD_160MHZ 160000000U /* 160 MHz */
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions -------------------------------------------------------*/
/** @defgroup DAC_Exported_Functions DAC Exported Functions
* @{
*/
/** @defgroup DAC_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 DAC.
(+) De-initialize the DAC.
@endverbatim
* @{
*/
/**
* @brief Initialize the DAC peripheral according to the specified parameters
* in the DAC_InitStruct and initialize the associated handle.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef *hdac)
{
/* Check DAC handle */
if (hdac == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance));
if (hdac->State == HAL_DAC_STATE_RESET)
{
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
/* Init the DAC Callback settings */
hdac->ConvCpltCallbackCh1 = HAL_DAC_ConvCpltCallbackCh1;
hdac->ConvHalfCpltCallbackCh1 = HAL_DAC_ConvHalfCpltCallbackCh1;
hdac->ErrorCallbackCh1 = HAL_DAC_ErrorCallbackCh1;
hdac->DMAUnderrunCallbackCh1 = HAL_DAC_DMAUnderrunCallbackCh1;
hdac->ConvCpltCallbackCh2 = HAL_DACEx_ConvCpltCallbackCh2;
hdac->ConvHalfCpltCallbackCh2 = HAL_DACEx_ConvHalfCpltCallbackCh2;
hdac->ErrorCallbackCh2 = HAL_DACEx_ErrorCallbackCh2;
hdac->DMAUnderrunCallbackCh2 = HAL_DACEx_DMAUnderrunCallbackCh2;
if (hdac->MspInitCallback == NULL)
{
hdac->MspInitCallback = HAL_DAC_MspInit;
}
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
/* Allocate lock resource and initialize it */
hdac->Lock = HAL_UNLOCKED;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
/* Init the low level hardware */
hdac->MspInitCallback(hdac);
#else
/* Init the low level hardware */
HAL_DAC_MspInit(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
}
/* Initialize the DAC state*/
hdac->State = HAL_DAC_STATE_BUSY;
/* Set DAC error code to none */
hdac->ErrorCode = HAL_DAC_ERROR_NONE;
/* Initialize the DAC state*/
hdac->State = HAL_DAC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Deinitialize the DAC peripheral registers to their default reset values.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef *hdac)
{
/* Check DAC handle */
if (hdac == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance));
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
if (hdac->MspDeInitCallback == NULL)
{
hdac->MspDeInitCallback = HAL_DAC_MspDeInit;
}
/* DeInit the low level hardware */
hdac->MspDeInitCallback(hdac);
#else
/* DeInit the low level hardware */
HAL_DAC_MspDeInit(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
/* Set DAC error code to none */
hdac->ErrorCode = HAL_DAC_ERROR_NONE;
/* Change DAC state */
hdac->State = HAL_DAC_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initialize the DAC MSP.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_MspInit(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize the DAC MSP.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_MspDeInit(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup DAC_Exported_Functions_Group2 IO operation functions
* @brief IO operation functions
*
@verbatim
==============================================================================
##### IO operation functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Start conversion.
(+) Stop conversion.
(+) Start conversion and enable DMA transfer.
(+) Stop conversion and disable DMA transfer.
(+) Get result of conversion.
@endverbatim
* @{
*/
/**
* @brief Enables DAC and starts conversion of channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
/* Enable the Peripheral */
__HAL_DAC_ENABLE(hdac, Channel);
/* Ensure minimum wait before using peripheral after enabling it */
HAL_Delay(1);
if (Channel == DAC_CHANNEL_1)
{
/* Check if software trigger enabled */
if ((hdac->Instance->CR & (DAC_CR_TEN1 | DAC_CR_TSEL1)) == DAC_TRIGGER_SOFTWARE)
{
/* Enable the selected DAC software conversion */
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIG1);
}
}
else
{
/* Check if software trigger enabled */
if ((hdac->Instance->CR & (DAC_CR_TEN2 | DAC_CR_TSEL2)) == (DAC_TRIGGER_SOFTWARE << (Channel & 0x10UL)))
{
/* Enable the selected DAC software conversion*/
SET_BIT(hdac->Instance->SWTRIGR, DAC_SWTRIGR_SWTRIG2);
}
}
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @brief Disables DAC and stop conversion of channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Disable the Peripheral */
__HAL_DAC_DISABLE(hdac, Channel);
/* Ensure minimum wait before enabling peripheral after disabling it */
HAL_Delay(1);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Enables DAC and starts conversion of channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param pData The source Buffer address.
* @param Length The length of data to be transferred from memory to DAC peripheral
* @param Alignment Specifies the data alignment for DAC channel.
* This parameter can be one of the following values:
* @arg DAC_ALIGN_8B_R: 8bit right data alignment selected
* @arg DAC_ALIGN_12B_L: 12bit left data alignment selected
* @arg DAC_ALIGN_12B_R: 12bit right data alignment selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t *pData, uint32_t Length,
uint32_t Alignment)
{
HAL_StatusTypeDef status;
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_ALIGN(Alignment));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
if (Channel == DAC_CHANNEL_1)
{
/* Set the DMA transfer complete callback for channel1 */
hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1;
/* Set the DMA half transfer complete callback for channel1 */
hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1;
/* Set the DMA error callback for channel1 */
hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1;
/* Enable the selected DAC channel1 DMA request */
SET_BIT(hdac->Instance->CR, DAC_CR_DMAEN1);
/* Case of use of channel 1 */
switch (Alignment)
{
case DAC_ALIGN_12B_R:
/* Get DHR12R1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12R1;
break;
case DAC_ALIGN_12B_L:
/* Get DHR12L1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12L1;
break;
case DAC_ALIGN_8B_R:
/* Get DHR8R1 address */
tmpreg = (uint32_t)&hdac->Instance->DHR8R1;
break;
default:
break;
}
}
else
{
/* Set the DMA transfer complete callback for channel2 */
hdac->DMA_Handle2->XferCpltCallback = DAC_DMAConvCpltCh2;
/* Set the DMA half transfer complete callback for channel2 */
hdac->DMA_Handle2->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh2;
/* Set the DMA error callback for channel2 */
hdac->DMA_Handle2->XferErrorCallback = DAC_DMAErrorCh2;
/* Enable the selected DAC channel2 DMA request */
SET_BIT(hdac->Instance->CR, DAC_CR_DMAEN2);
/* Case of use of channel 2 */
switch (Alignment)
{
case DAC_ALIGN_12B_R:
/* Get DHR12R2 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12R2;
break;
case DAC_ALIGN_12B_L:
/* Get DHR12L2 address */
tmpreg = (uint32_t)&hdac->Instance->DHR12L2;
break;
case DAC_ALIGN_8B_R:
/* Get DHR8R2 address */
tmpreg = (uint32_t)&hdac->Instance->DHR8R2;
break;
default:
break;
}
}
/* Enable the DMA channel */
if (Channel == DAC_CHANNEL_1)
{
/* Enable the DAC DMA underrun interrupt */
__HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1);
/* Enable the DMA channel */
status = HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length);
}
else
{
/* Enable the DAC DMA underrun interrupt */
__HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR2);
/* Enable the DMA channel */
status = HAL_DMA_Start_IT(hdac->DMA_Handle2, (uint32_t)pData, tmpreg, Length);
}
/* Process Unlocked */
__HAL_UNLOCK(hdac);
if (status == HAL_OK)
{
/* Enable the Peripheral */
__HAL_DAC_ENABLE(hdac, Channel);
/* Ensure minimum wait before using peripheral after enabling it */
HAL_Delay(1);
}
else
{
hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
}
/* Return function status */
return status;
}
/**
* @brief Disables DAC and stop conversion of channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
/* Disable the selected DAC channel DMA request */
hdac->Instance->CR &= ~(DAC_CR_DMAEN1 << (Channel & 0x10UL));
/* Disable the Peripheral */
__HAL_DAC_DISABLE(hdac, Channel);
/* Ensure minimum wait before enabling peripheral after disabling it */
HAL_Delay(1);
/* Disable the DMA channel */
/* Channel1 is used */
if (Channel == DAC_CHANNEL_1)
{
/* Disable the DMA channel */
(void)HAL_DMA_Abort(hdac->DMA_Handle1);
/* Disable the DAC DMA underrun interrupt */
__HAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR1);
}
else /* Channel2 is used for */
{
/* Disable the DMA channel */
(void)HAL_DMA_Abort(hdac->DMA_Handle2);
/* Disable the DAC DMA underrun interrupt */
__HAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR2);
}
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Handles DAC interrupt request
* This function uses the interruption of DMA
* underrun.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
void HAL_DAC_IRQHandler(DAC_HandleTypeDef *hdac)
{
if (__HAL_DAC_GET_IT_SOURCE(hdac, DAC_IT_DMAUDR1))
{
/* Check underrun flag of DAC channel 1 */
if (__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1))
{
/* Change DAC state to error state */
hdac->State = HAL_DAC_STATE_ERROR;
/* Set DAC error code to channel1 DMA underrun error */
SET_BIT(hdac->ErrorCode, HAL_DAC_ERROR_DMAUNDERRUNCH1);
/* Clear the underrun flag */
__HAL_DAC_CLEAR_FLAG(hdac, DAC_FLAG_DMAUDR1);
/* Disable the selected DAC channel1 DMA request */
CLEAR_BIT(hdac->Instance->CR, DAC_CR_DMAEN1);
/* Error callback */
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->DMAUnderrunCallbackCh1(hdac);
#else
HAL_DAC_DMAUnderrunCallbackCh1(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
}
}
if (__HAL_DAC_GET_IT_SOURCE(hdac, DAC_IT_DMAUDR2))
{
/* Check underrun flag of DAC channel 2 */
if (__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR2))
{
/* Change DAC state to error state */
hdac->State = HAL_DAC_STATE_ERROR;
/* Set DAC error code to channel2 DMA underrun error */
SET_BIT(hdac->ErrorCode, HAL_DAC_ERROR_DMAUNDERRUNCH2);
/* Clear the underrun flag */
__HAL_DAC_CLEAR_FLAG(hdac, DAC_FLAG_DMAUDR2);
/* Disable the selected DAC channel2 DMA request */
CLEAR_BIT(hdac->Instance->CR, DAC_CR_DMAEN2);
/* Error callback */
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->DMAUnderrunCallbackCh2(hdac);
#else
HAL_DACEx_DMAUnderrunCallbackCh2(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
}
}
}
/**
* @brief Set the specified data holding register value for DAC channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @param Alignment Specifies the data alignment.
* This parameter can be one of the following values:
* @arg DAC_ALIGN_8B_R: 8bit right data alignment selected
* @arg DAC_ALIGN_12B_L: 12bit left data alignment selected
* @arg DAC_ALIGN_12B_R: 12bit right data alignment selected
* @param Data Data to be loaded in the selected data holding register.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data)
{
__IO uint32_t tmp = 0UL;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_DAC_ALIGN(Alignment));
/* In case DMA Double data mode is activated, DATA range is almost full uin32_t one: no check */
if ((hdac->Instance->MCR & (DAC_MCR_DMADOUBLE1 << (Channel & 0x10UL))) == 0UL)
{
assert_param(IS_DAC_DATA(Data));
}
tmp = (uint32_t)hdac->Instance;
if (Channel == DAC_CHANNEL_1)
{
tmp += DAC_DHR12R1_ALIGNMENT(Alignment);
}
else
{
tmp += DAC_DHR12R2_ALIGNMENT(Alignment);
}
/* Set the DAC channel selected data holding register */
*(__IO uint32_t *) tmp = Data;
/* Return function status */
return HAL_OK;
}
/**
* @brief Conversion complete callback in non-blocking mode for Channel1
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_ConvCpltCallbackCh1 could be implemented in the user file
*/
}
/**
* @brief Conversion half DMA transfer callback in non-blocking mode for Channel1
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_ConvHalfCpltCallbackCh1 could be implemented in the user file
*/
}
/**
* @brief Error DAC callback for Channel1.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_ErrorCallbackCh1 could be implemented in the user file
*/
}
/**
* @brief DMA underrun DAC callback for channel1.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval None
*/
__weak void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdac);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_DAC_DMAUnderrunCallbackCh1 could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup DAC_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..] This section provides functions allowing to:
(+) Configure channels.
(+) Set the specified data holding register value for DAC channel.
@endverbatim
* @{
*/
/**
* @brief Returns the last data output value of the selected DAC channel.
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval The selected DAC channel data output value.
*/
uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef *hdac, uint32_t Channel)
{
uint32_t result;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
if (Channel == DAC_CHANNEL_1)
{
result = hdac->Instance->DOR1;
}
else
{
result = hdac->Instance->DOR2;
}
/* Returns the DAC channel data output register value */
return result;
}
/**
* @brief Configures the selected DAC channel.
* @note By calling this function, the high frequency interface mode (HFSEL bits)
* will be set. This parameter scope is the DAC instance. As the function
* is called for each channel, the @ref DAC_HighFrequency of @arg sConfig
* must be the same at each call.
* (or DAC_HIGH_FREQUENCY_INTERFACE_MODE_AUTOMATIC self detect).
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @param sConfig DAC configuration structure.
* @param Channel The selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_CHANNEL_1: DAC Channel1 selected
* @arg DAC_CHANNEL_2: DAC Channel2 selected (1)
*
* (1) On this STM32 series, parameter not available on all instances.
* Refer to device datasheet for channels availability.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef *hdac, DAC_ChannelConfTypeDef *sConfig, uint32_t Channel)
{
uint32_t tmpreg1;
uint32_t tmpreg2;
uint32_t tickstart;
uint32_t hclkfreq;
uint32_t connectOnChip;
/* Check the DAC parameters */
assert_param(IS_DAC_HIGH_FREQUENCY_MODE(sConfig->DAC_HighFrequency));
assert_param(IS_DAC_TRIGGER(hdac->Instance, sConfig->DAC_Trigger));
assert_param(IS_DAC_TRIGGER(hdac->Instance, sConfig->DAC_Trigger2));
assert_param(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer));
assert_param(IS_DAC_CHIP_CONNECTION(sConfig->DAC_ConnectOnChipPeripheral));
assert_param(IS_DAC_TRIMMING(sConfig->DAC_UserTrimming));
if ((sConfig->DAC_UserTrimming) == DAC_TRIMMING_USER)
{
assert_param(IS_DAC_TRIMMINGVALUE(sConfig->DAC_TrimmingValue));
}
assert_param(IS_DAC_SAMPLEANDHOLD(sConfig->DAC_SampleAndHold));
if ((sConfig->DAC_SampleAndHold) == DAC_SAMPLEANDHOLD_ENABLE)
{
assert_param(IS_DAC_SAMPLETIME(sConfig->DAC_SampleAndHoldConfig.DAC_SampleTime));
assert_param(IS_DAC_HOLDTIME(sConfig->DAC_SampleAndHoldConfig.DAC_HoldTime));
assert_param(IS_DAC_REFRESHTIME(sConfig->DAC_SampleAndHoldConfig.DAC_RefreshTime));
}
assert_param(IS_DAC_CHANNEL(hdac->Instance, Channel));
assert_param(IS_FUNCTIONAL_STATE(sConfig->DAC_DMADoubleDataMode));
assert_param(IS_FUNCTIONAL_STATE(sConfig->DAC_SignedFormat));
/* Process locked */
__HAL_LOCK(hdac);
/* Change DAC state */
hdac->State = HAL_DAC_STATE_BUSY;
/* Sample and hold configuration */
if (sConfig->DAC_SampleAndHold == DAC_SAMPLEANDHOLD_ENABLE)
{
/* Get timeout */
tickstart = HAL_GetTick();
if (Channel == DAC_CHANNEL_1)
{
/* SHSR1 can be written when BWST1 is cleared */
while (((hdac->Instance->SR) & DAC_SR_BWST1) != 0UL)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > TIMEOUT_DAC_CALIBCONFIG)
{
/* Update error code */
SET_BIT(hdac->ErrorCode, HAL_DAC_ERROR_TIMEOUT);
/* Change the DMA state */
hdac->State = HAL_DAC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
HAL_Delay(1);
hdac->Instance->SHSR1 = sConfig->DAC_SampleAndHoldConfig.DAC_SampleTime;
}
else /* Channel 2 */
{
/* SHSR2 can be written when BWST2 is cleared */
while (((hdac->Instance->SR) & DAC_SR_BWST2) != 0UL)
{
/* Check for the Timeout */
if ((HAL_GetTick() - tickstart) > TIMEOUT_DAC_CALIBCONFIG)
{
/* Update error code */
SET_BIT(hdac->ErrorCode, HAL_DAC_ERROR_TIMEOUT);
/* Change the DMA state */
hdac->State = HAL_DAC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
HAL_Delay(1U);
hdac->Instance->SHSR2 = sConfig->DAC_SampleAndHoldConfig.DAC_SampleTime;
}
/* HoldTime */
MODIFY_REG(hdac->Instance->SHHR, DAC_SHHR_THOLD1 << (Channel & 0x10UL),
(sConfig->DAC_SampleAndHoldConfig.DAC_HoldTime) << (Channel & 0x10UL));
/* RefreshTime */
MODIFY_REG(hdac->Instance->SHRR, DAC_SHRR_TREFRESH1 << (Channel & 0x10UL),
(sConfig->DAC_SampleAndHoldConfig.DAC_RefreshTime) << (Channel & 0x10UL));
}
if (sConfig->DAC_UserTrimming == DAC_TRIMMING_USER)
/* USER TRIMMING */
{
/* Get the DAC CCR value */
tmpreg1 = hdac->Instance->CCR;
/* Clear trimming value */
tmpreg1 &= ~(((uint32_t)(DAC_CCR_OTRIM1)) << (Channel & 0x10UL));
/* Configure for the selected trimming offset */
tmpreg2 = sConfig->DAC_TrimmingValue;
/* Calculate CCR register value depending on DAC_Channel */
tmpreg1 |= tmpreg2 << (Channel & 0x10UL);
/* Write to DAC CCR */
hdac->Instance->CCR = tmpreg1;
}
/* else factory trimming is used (factory setting are available at reset)*/
/* SW Nothing has nothing to do */
/* Get the DAC MCR value */
tmpreg1 = hdac->Instance->MCR;
/* Clear DAC_MCR_MODEx bits */
tmpreg1 &= ~(((uint32_t)(DAC_MCR_MODE1)) << (Channel & 0x10UL));
/* Configure for the selected DAC channel: mode, buffer output & on chip peripheral connect */
if (sConfig->DAC_ConnectOnChipPeripheral == DAC_CHIPCONNECT_EXTERNAL)
{
connectOnChip = 0x00000000UL;
}
else if (sConfig->DAC_ConnectOnChipPeripheral == DAC_CHIPCONNECT_INTERNAL)
{
connectOnChip = DAC_MCR_MODE1_0;
}
else /* (sConfig->DAC_ConnectOnChipPeripheral == DAC_CHIPCONNECT_BOTH) */
{
if (sConfig->DAC_OutputBuffer == DAC_OUTPUTBUFFER_ENABLE)
{
connectOnChip = DAC_MCR_MODE1_0;
}
else
{
connectOnChip = 0x00000000UL;
}
}
tmpreg2 = (sConfig->DAC_SampleAndHold | sConfig->DAC_OutputBuffer | connectOnChip);
/* Clear DAC_MCR_DMADOUBLEx */
tmpreg1 &= ~(((uint32_t)(DAC_MCR_DMADOUBLE1)) << (Channel & 0x10UL));
/* Configure for the selected DAC channel: DMA double data mode */
tmpreg2 |= (sConfig->DAC_DMADoubleDataMode == ENABLE) ? DAC_MCR_DMADOUBLE1 : 0UL;
/* Clear DAC_MCR_SINFORMATx */
tmpreg1 &= ~(((uint32_t)(DAC_MCR_SINFORMAT1)) << (Channel & 0x10UL));
/* Configure for the selected DAC channel: Signed format */
tmpreg2 |= (sConfig->DAC_SignedFormat == ENABLE) ? DAC_MCR_SINFORMAT1 : 0UL;
/* Clear DAC_MCR_HFSEL bits */
tmpreg1 &= ~(DAC_MCR_HFSEL);
/* Configure for both DAC channels: high frequency mode */
if (DAC_HIGH_FREQUENCY_INTERFACE_MODE_AUTOMATIC == sConfig->DAC_HighFrequency)
{
hclkfreq = HAL_RCC_GetHCLKFreq();
if (hclkfreq > HFSEL_ENABLE_THRESHOLD_160MHZ)
{
tmpreg1 |= DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_160MHZ;
}
else if (hclkfreq > HFSEL_ENABLE_THRESHOLD_80MHZ)
{
tmpreg1 |= DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_80MHZ;
}
else
{
tmpreg1 |= DAC_HIGH_FREQUENCY_INTERFACE_MODE_DISABLE;
}
}
else
{
tmpreg1 |= sConfig->DAC_HighFrequency;
}
/* Calculate MCR register value depending on DAC_Channel */
tmpreg1 |= tmpreg2 << (Channel & 0x10UL);
/* Write to DAC MCR */
hdac->Instance->MCR = tmpreg1;
/* DAC in normal operating mode hence clear DAC_CR_CENx bit */
CLEAR_BIT(hdac->Instance->CR, DAC_CR_CEN1 << (Channel & 0x10UL));
/* Get the DAC CR value */
tmpreg1 = hdac->Instance->CR;
/* Clear TENx, TSELx, WAVEx and MAMPx bits */
tmpreg1 &= ~(((uint32_t)(DAC_CR_MAMP1 | DAC_CR_WAVE1 | DAC_CR_TSEL1 | DAC_CR_TEN1)) << (Channel & 0x10UL));
/* Configure for the selected DAC channel: trigger */
/* Set TSELx and TENx bits according to DAC_Trigger value */
tmpreg2 = sConfig->DAC_Trigger;
/* Calculate CR register value depending on DAC_Channel */
tmpreg1 |= tmpreg2 << (Channel & 0x10UL);
/* Write to DAC CR */
hdac->Instance->CR = tmpreg1;
/* Disable wave generation */
CLEAR_BIT(hdac->Instance->CR, (DAC_CR_WAVE1 << (Channel & 0x10UL)));
/* Set STRSTTRIGSELx and STINCTRIGSELx bits according to DAC_Trigger & DAC_Trigger2 values */
tmpreg2 = ((sConfig->DAC_Trigger & DAC_CR_TSEL1) >> DAC_CR_TSEL1_Pos) << DAC_STMODR_STRSTTRIGSEL1_Pos;
tmpreg2 |= ((sConfig->DAC_Trigger2 & DAC_CR_TSEL1) >> DAC_CR_TSEL1_Pos) << DAC_STMODR_STINCTRIGSEL1_Pos;
/* Modify STMODR register value depending on DAC_Channel */
MODIFY_REG(hdac->Instance->STMODR, (DAC_STMODR_STINCTRIGSEL1 | DAC_STMODR_STRSTTRIGSEL1) << (Channel & 0x10UL), tmpreg2 << (Channel & 0x10UL));
/* Change DAC state */
hdac->State = HAL_DAC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hdac);
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup DAC_Exported_Functions_Group4 Peripheral State and Errors functions
* @brief Peripheral State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Errors functions #####
==============================================================================
[..]
This subsection provides functions allowing to
(+) Check the DAC state.
(+) Check the DAC Errors.
@endverbatim
* @{
*/
/**
* @brief return the DAC handle state
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval HAL state
*/
HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef *hdac)
{
/* Return DAC handle state */
return hdac->State;
}
/**
* @brief Return the DAC error code
* @param hdac pointer to a DAC_HandleTypeDef structure that contains
* the configuration information for the specified DAC.
* @retval DAC Error Code
*/
uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac)
{
return hdac->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup DAC_Exported_Functions
* @{
*/
/** @addtogroup DAC_Exported_Functions_Group1
* @{
*/
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User DAC Callback
* To be used instead of the weak (surcharged) predefined callback
* @param hdac DAC handle
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_DAC_ERROR_INVALID_CALLBACK DAC Error Callback ID
* @arg @ref HAL_DAC_CH1_COMPLETE_CB_ID DAC CH1 Complete Callback ID
* @arg @ref HAL_DAC_CH1_HALF_COMPLETE_CB_ID DAC CH1 Half Complete Callback ID
* @arg @ref HAL_DAC_CH1_ERROR_ID DAC CH1 Error Callback ID
* @arg @ref HAL_DAC_CH1_UNDERRUN_CB_ID DAC CH1 UnderRun Callback ID
* @arg @ref HAL_DAC_CH2_COMPLETE_CB_ID DAC CH2 Complete Callback ID
* @arg @ref HAL_DAC_CH2_HALF_COMPLETE_CB_ID DAC CH2 Half Complete Callback ID
* @arg @ref HAL_DAC_CH2_ERROR_ID DAC CH2 Error Callback ID
* @arg @ref HAL_DAC_CH2_UNDERRUN_CB_ID DAC CH2 UnderRun Callback ID
* @arg @ref HAL_DAC_MSPINIT_CB_ID DAC MSP Init Callback ID
* @arg @ref HAL_DAC_MSPDEINIT_CB_ID DAC MSP DeInit Callback ID
*
* @param pCallback pointer to the Callback function
* @retval status
*/
HAL_StatusTypeDef HAL_DAC_RegisterCallback(DAC_HandleTypeDef *hdac, HAL_DAC_CallbackIDTypeDef CallbackID,
pDAC_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hdac);
if (hdac->State == HAL_DAC_STATE_READY)
{
switch (CallbackID)
{
case HAL_DAC_CH1_COMPLETE_CB_ID :
hdac->ConvCpltCallbackCh1 = pCallback;
break;
case HAL_DAC_CH1_HALF_COMPLETE_CB_ID :
hdac->ConvHalfCpltCallbackCh1 = pCallback;
break;
case HAL_DAC_CH1_ERROR_ID :
hdac->ErrorCallbackCh1 = pCallback;
break;
case HAL_DAC_CH1_UNDERRUN_CB_ID :
hdac->DMAUnderrunCallbackCh1 = pCallback;
break;
case HAL_DAC_CH2_COMPLETE_CB_ID :
hdac->ConvCpltCallbackCh2 = pCallback;
break;
case HAL_DAC_CH2_HALF_COMPLETE_CB_ID :
hdac->ConvHalfCpltCallbackCh2 = pCallback;
break;
case HAL_DAC_CH2_ERROR_ID :
hdac->ErrorCallbackCh2 = pCallback;
break;
case HAL_DAC_CH2_UNDERRUN_CB_ID :
hdac->DMAUnderrunCallbackCh2 = pCallback;
break;
case HAL_DAC_MSPINIT_CB_ID :
hdac->MspInitCallback = pCallback;
break;
case HAL_DAC_MSPDEINIT_CB_ID :
hdac->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hdac->State == HAL_DAC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_DAC_MSPINIT_CB_ID :
hdac->MspInitCallback = pCallback;
break;
case HAL_DAC_MSPDEINIT_CB_ID :
hdac->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hdac);
return status;
}
/**
* @brief Unregister a User DAC Callback
* DAC Callback is redirected to the weak (surcharged) predefined callback
* @param hdac DAC handle
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_DAC_CH1_COMPLETE_CB_ID DAC CH1 transfer Complete Callback ID
* @arg @ref HAL_DAC_CH1_HALF_COMPLETE_CB_ID DAC CH1 Half Complete Callback ID
* @arg @ref HAL_DAC_CH1_ERROR_ID DAC CH1 Error Callback ID
* @arg @ref HAL_DAC_CH1_UNDERRUN_CB_ID DAC CH1 UnderRun Callback ID
* @arg @ref HAL_DAC_CH2_COMPLETE_CB_ID DAC CH2 Complete Callback ID
* @arg @ref HAL_DAC_CH2_HALF_COMPLETE_CB_ID DAC CH2 Half Complete Callback ID
* @arg @ref HAL_DAC_CH2_ERROR_ID DAC CH2 Error Callback ID
* @arg @ref HAL_DAC_CH2_UNDERRUN_CB_ID DAC CH2 UnderRun Callback ID
* @arg @ref HAL_DAC_MSPINIT_CB_ID DAC MSP Init Callback ID
* @arg @ref HAL_DAC_MSPDEINIT_CB_ID DAC MSP DeInit Callback ID
* @arg @ref HAL_DAC_ALL_CB_ID DAC All callbacks
* @retval status
*/
HAL_StatusTypeDef HAL_DAC_UnRegisterCallback(DAC_HandleTypeDef *hdac, HAL_DAC_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hdac);
if (hdac->State == HAL_DAC_STATE_READY)
{
switch (CallbackID)
{
case HAL_DAC_CH1_COMPLETE_CB_ID :
hdac->ConvCpltCallbackCh1 = HAL_DAC_ConvCpltCallbackCh1;
break;
case HAL_DAC_CH1_HALF_COMPLETE_CB_ID :
hdac->ConvHalfCpltCallbackCh1 = HAL_DAC_ConvHalfCpltCallbackCh1;
break;
case HAL_DAC_CH1_ERROR_ID :
hdac->ErrorCallbackCh1 = HAL_DAC_ErrorCallbackCh1;
break;
case HAL_DAC_CH1_UNDERRUN_CB_ID :
hdac->DMAUnderrunCallbackCh1 = HAL_DAC_DMAUnderrunCallbackCh1;
break;
case HAL_DAC_CH2_COMPLETE_CB_ID :
hdac->ConvCpltCallbackCh2 = HAL_DACEx_ConvCpltCallbackCh2;
break;
case HAL_DAC_CH2_HALF_COMPLETE_CB_ID :
hdac->ConvHalfCpltCallbackCh2 = HAL_DACEx_ConvHalfCpltCallbackCh2;
break;
case HAL_DAC_CH2_ERROR_ID :
hdac->ErrorCallbackCh2 = HAL_DACEx_ErrorCallbackCh2;
break;
case HAL_DAC_CH2_UNDERRUN_CB_ID :
hdac->DMAUnderrunCallbackCh2 = HAL_DACEx_DMAUnderrunCallbackCh2;
break;
case HAL_DAC_MSPINIT_CB_ID :
hdac->MspInitCallback = HAL_DAC_MspInit;
break;
case HAL_DAC_MSPDEINIT_CB_ID :
hdac->MspDeInitCallback = HAL_DAC_MspDeInit;
break;
case HAL_DAC_ALL_CB_ID :
hdac->ConvCpltCallbackCh1 = HAL_DAC_ConvCpltCallbackCh1;
hdac->ConvHalfCpltCallbackCh1 = HAL_DAC_ConvHalfCpltCallbackCh1;
hdac->ErrorCallbackCh1 = HAL_DAC_ErrorCallbackCh1;
hdac->DMAUnderrunCallbackCh1 = HAL_DAC_DMAUnderrunCallbackCh1;
hdac->ConvCpltCallbackCh2 = HAL_DACEx_ConvCpltCallbackCh2;
hdac->ConvHalfCpltCallbackCh2 = HAL_DACEx_ConvHalfCpltCallbackCh2;
hdac->ErrorCallbackCh2 = HAL_DACEx_ErrorCallbackCh2;
hdac->DMAUnderrunCallbackCh2 = HAL_DACEx_DMAUnderrunCallbackCh2;
hdac->MspInitCallback = HAL_DAC_MspInit;
hdac->MspDeInitCallback = HAL_DAC_MspDeInit;
break;
default :
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else if (hdac->State == HAL_DAC_STATE_RESET)
{
switch (CallbackID)
{
case HAL_DAC_MSPINIT_CB_ID :
hdac->MspInitCallback = HAL_DAC_MspInit;
break;
case HAL_DAC_MSPDEINIT_CB_ID :
hdac->MspDeInitCallback = HAL_DAC_MspDeInit;
break;
default :
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hdac->ErrorCode |= HAL_DAC_ERROR_INVALID_CALLBACK;
/* update return status */
status = HAL_ERROR;
}
/* Release Lock */
__HAL_UNLOCK(hdac);
return status;
}
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
/**
* @}
*/
/**
* @}
*/
/** @addtogroup DAC_Private_Functions
* @{
*/
/**
* @brief DMA conversion complete callback.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ConvCpltCallbackCh1(hdac);
#else
HAL_DAC_ConvCpltCallbackCh1(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
hdac->State = HAL_DAC_STATE_READY;
}
/**
* @brief DMA half transfer complete callback.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Conversion complete callback */
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ConvHalfCpltCallbackCh1(hdac);
#else
HAL_DAC_ConvHalfCpltCallbackCh1(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
}
/**
* @brief DMA error callback
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma)
{
DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Set DAC error code to DMA error */
hdac->ErrorCode |= HAL_DAC_ERROR_DMA;
#if (USE_HAL_DAC_REGISTER_CALLBACKS == 1)
hdac->ErrorCallbackCh1(hdac);
#else
HAL_DAC_ErrorCallbackCh1(hdac);
#endif /* USE_HAL_DAC_REGISTER_CALLBACKS */
hdac->State = HAL_DAC_STATE_READY;
}
/**
* @}
*/
/**
* @}
*/
#endif /* DAC1 || DAC2 || DAC3 || DAC4 */
#endif /* HAL_DAC_MODULE_ENABLED */
/**
* @}
*/
| 60,465 |
C
| 35.077566 | 145 | 0.616985 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_adc.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_adc.c
* @author MCD Application Team
* @brief ADC LL module driver
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_adc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (ADC1) || defined (ADC2) || defined (ADC3) || defined (ADC4) || defined (ADC5)
/** @addtogroup ADC_LL ADC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup ADC_LL_Private_Constants
* @{
*/
/* Definitions of ADC hardware constraints delays */
/* Note: Only ADC peripheral HW delays are defined in ADC LL driver driver, */
/* not timeout values: */
/* Timeout values for ADC operations are dependent to device clock */
/* configuration (system clock versus ADC clock), */
/* and therefore must be defined in user application. */
/* Refer to @ref ADC_LL_EC_HW_DELAYS for description of ADC timeout */
/* values definition. */
/* Note: ADC timeout values are defined here in CPU cycles to be independent */
/* of device clock setting. */
/* In user application, ADC timeout values should be defined with */
/* temporal values, in function of device clock settings. */
/* Highest ratio CPU clock frequency vs ADC clock frequency: */
/* - ADC clock from synchronous clock with AHB prescaler 512, */
/* ADC prescaler 4. */
/* Ratio max = 512 *4 = 2048 */
/* - ADC clock from asynchronous clock (PLLP) with prescaler 256. */
/* Highest CPU clock PLL (PLLR). */
/* Ratio max = PLLRmax /PPLPmin * 256 = (VCO/2) / (VCO/31) * 256 */
/* = 3968 */
/* Unit: CPU cycles. */
#define ADC_CLOCK_RATIO_VS_CPU_HIGHEST (3968UL)
#define ADC_TIMEOUT_DISABLE_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL)
#define ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL)
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup ADC_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of ADC hierarchical scope: */
/* common to several ADC instances. */
#define IS_LL_ADC_COMMON_CLOCK(__CLOCK__) \
(((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV1) \
|| ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV2) \
|| ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV4) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV1) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV2) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV4) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV6) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV8) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV10) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV12) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV16) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV32) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV64) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV128) \
|| ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV256) \
)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC instance. */
#define IS_LL_ADC_RESOLUTION(__RESOLUTION__) \
(((__RESOLUTION__) == LL_ADC_RESOLUTION_12B) \
|| ((__RESOLUTION__) == LL_ADC_RESOLUTION_10B) \
|| ((__RESOLUTION__) == LL_ADC_RESOLUTION_8B) \
|| ((__RESOLUTION__) == LL_ADC_RESOLUTION_6B) \
)
#define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \
(((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \
|| ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \
)
#define IS_LL_ADC_LOW_POWER(__LOW_POWER__) \
(((__LOW_POWER__) == LL_ADC_LP_MODE_NONE) \
|| ((__LOW_POWER__) == LL_ADC_LP_AUTOWAIT) \
)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC group regular */
#if defined(STM32G474xx) || defined(STM32G484xx)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
(((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM15_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG5) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG6) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG7) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG8) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG9) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG10) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__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_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3) || ((__ADC_INSTANCE__) == ADC4) || ((__ADC_INSTANCE__) == ADC5)) \
&& ( \
((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_HRTIM_TRG4) \
) \
) \
)
#elif defined(STM32G473xx) || defined(STM32G483xx)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
(((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \
|| ((__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_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM15_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__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_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3) || ((__ADC_INSTANCE__) == ADC4) || ((__ADC_INSTANCE__) == ADC5)) \
&& ( \
((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE2) \
) \
) \
)
#elif defined(STM32G471xx)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
(((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \
|| ((__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_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM15_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__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_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
) \
) \
|| (((__ADC_INSTANCE__) == ADC3) \
&& ( \
((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE2) \
) \
) \
)
#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
(((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \
|| ((__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_TRGO) \
|| ((__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_TIM3_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM15_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM_OUT) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
)
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
(((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM15_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_TRGO2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__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_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM20_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
) \
) \
|| (((__ADC_INSTANCE__) == ADC3) \
&& ( \
((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE2) \
) \
) \
)
#endif
#define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \
(((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \
|| ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \
)
#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \
(((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \
|| ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_LIMITED) \
|| ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \
)
#define IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(__REG_OVR_DATA_BEHAVIOR__) \
(((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_PRESERVED) \
|| ((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_OVERWRITTEN) \
)
#define IS_LL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \
(((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_DISABLE) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \
)
#define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \
(((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_2RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_3RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_4RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_5RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_6RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_7RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_8RANKS) \
)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC group injected */
#if defined(STM32G474xx) || defined(STM32G484xx)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
(((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG5) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG6) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG7) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG8) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG9) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG10) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM16_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3) || ((__ADC_INSTANCE__) == ADC4) || ((__ADC_INSTANCE__) == ADC5)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_HRTIM_TRG3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE3) \
) \
) \
)
#elif defined(STM32G473xx) || defined(STM32G483xx)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
(((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM16_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3) || ((__ADC_INSTANCE__) == ADC4) || ((__ADC_INSTANCE__) == ADC5)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE3) \
) \
) \
)
#elif defined(STM32G471xx)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
(((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM16_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE3) \
) \
) \
)
#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
(((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \
|| ((__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_TIM6_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM16_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
)
#elif defined(STM32G491xx) || defined(STM32G4A1xx)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
(((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) \
|| ((__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_TIM8_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_TRGO2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) \
|| ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM16_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
) \
) \
|| ((((__ADC_INSTANCE__) == ADC3)) \
&& ( \
((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM20_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE3) \
) \
) \
)
#endif
#define IS_LL_ADC_INJ_TRIG_EXT_EDGE(__INJ_TRIG_EXT_EDGE__) \
(((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISING) \
|| ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_FALLING) \
|| ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISINGFALLING) \
)
#define IS_LL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \
(((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_INDEPENDENT) \
|| ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \
)
#define IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \
(((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_DISABLE) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \
)
#define IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \
(((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_DISABLE) \
|| ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_1RANK) \
)
#if defined(ADC_MULTIMODE_SUPPORT)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* multimode. */
#define IS_LL_ADC_MULTI_MODE(__MULTI_MODE__) \
(((__MULTI_MODE__) == LL_ADC_MULTI_INDEPENDENT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIMULT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_SIMULT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_ALTERN) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) \
)
#define IS_LL_ADC_MULTI_DMA_TRANSFER(__MULTI_DMA_TRANSFER__) \
(((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_EACH_ADC) \
|| ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES12_10B) \
|| ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES8_6B) \
|| ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES12_10B) \
|| ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES8_6B) \
)
#define IS_LL_ADC_MULTI_TWOSMP_DELAY(__MULTI_TWOSMP_DELAY__) \
(((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_2CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_3CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_4CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_5CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_6CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_7CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_8CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_9CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_10CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_11CYCLES) \
|| ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_12CYCLES) \
)
#define IS_LL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \
(((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER) \
|| ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_SLAVE) \
|| ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER_SLAVE) \
)
#endif /* ADC_MULTIMODE_SUPPORT */
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup ADC_LL_Exported_Functions
* @{
*/
/** @addtogroup ADC_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of all ADC instances belonging to
* the same ADC common instance to their default reset values.
* @note This function is performing a hard reset, using high level
* clock source RCC ADC reset.
* Caution: On this STM32 series, if several ADC instances are available
* on the selected device, RCC ADC reset will reset
* all ADC instances belonging to the common ADC instance.
* To de-initialize only 1 ADC instance, use
* function @ref LL_ADC_DeInit().
* @param ADCxy_COMMON ADC common instance
* (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() )
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC common registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON)
{
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON));
if (ADCxy_COMMON == 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);
}
#if defined(ADC345_COMMON)
else
{
/* Force reset of ADC clock (core clock) */
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_ADC345);
/* Release reset of ADC clock (core clock) */
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_ADC345);
}
#endif
return SUCCESS;
}
/**
* @brief Initialize some features of ADC common parameters
* (all ADC instances belonging to the same ADC common instance)
* and multimode (for devices with several ADC instances available).
* @note The setting of ADC common parameters is conditioned to
* ADC instances state:
* All ADC instances belonging to the same ADC common instance
* must be disabled.
* @param ADCxy_COMMON ADC common instance
* (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() )
* @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC common registers are initialized
* - ERROR: ADC common registers are not initialized
*/
ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON));
assert_param(IS_LL_ADC_COMMON_CLOCK(ADC_CommonInitStruct->CommonClock));
#if defined(ADC_MULTIMODE_SUPPORT)
assert_param(IS_LL_ADC_MULTI_MODE(ADC_CommonInitStruct->Multimode));
if (ADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT)
{
assert_param(IS_LL_ADC_MULTI_DMA_TRANSFER(ADC_CommonInitStruct->MultiDMATransfer));
assert_param(IS_LL_ADC_MULTI_TWOSMP_DELAY(ADC_CommonInitStruct->MultiTwoSamplingDelay));
}
#endif /* ADC_MULTIMODE_SUPPORT */
/* Note: Hardware constraint (refer to description of functions */
/* "LL_ADC_SetCommonXXX()" and "LL_ADC_SetMultiXXX()"): */
/* On this STM32 series, setting of these features is conditioned to */
/* ADC state: */
/* All ADC instances of the ADC common group must be disabled. */
if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0UL)
{
/* Configuration of ADC hierarchical scope: */
/* - common to several ADC */
/* (all ADC instances belonging to the same ADC common instance) */
/* - Set ADC clock (conversion clock) */
/* - multimode (if several ADC instances available on the */
/* selected device) */
/* - Set ADC multimode configuration */
/* - Set ADC multimode DMA transfer */
/* - Set ADC multimode: delay between 2 sampling phases */
#if defined(ADC_MULTIMODE_SUPPORT)
if (ADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT)
{
MODIFY_REG(ADCxy_COMMON->CCR,
ADC_CCR_CKMODE
| ADC_CCR_PRESC
| ADC_CCR_DUAL
| ADC_CCR_MDMA
| ADC_CCR_DELAY
,
ADC_CommonInitStruct->CommonClock
| ADC_CommonInitStruct->Multimode
| ADC_CommonInitStruct->MultiDMATransfer
| ADC_CommonInitStruct->MultiTwoSamplingDelay
);
}
else
{
MODIFY_REG(ADCxy_COMMON->CCR,
ADC_CCR_CKMODE
| ADC_CCR_PRESC
| ADC_CCR_DUAL
| ADC_CCR_MDMA
| ADC_CCR_DELAY
,
ADC_CommonInitStruct->CommonClock
| LL_ADC_MULTI_INDEPENDENT
);
}
#else
LL_ADC_SetCommonClock(ADCxy_COMMON, ADC_CommonInitStruct->CommonClock);
#endif
}
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 ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct)
{
/* Set ADC_CommonInitStruct fields to default values */
/* Set fields of ADC common */
/* (all ADC instances belonging to the same ADC common instance) */
ADC_CommonInitStruct->CommonClock = LL_ADC_CLOCK_SYNC_PCLK_DIV2;
#if defined(ADC_MULTIMODE_SUPPORT)
/* Set fields of ADC multimode */
ADC_CommonInitStruct->Multimode = LL_ADC_MULTI_INDEPENDENT;
ADC_CommonInitStruct->MultiDMATransfer = LL_ADC_MULTI_REG_DMA_EACH_ADC;
ADC_CommonInitStruct->MultiTwoSamplingDelay = LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE;
#endif /* ADC_MULTIMODE_SUPPORT */
}
/**
* @brief De-initialize registers of the selected ADC instance
* to their default reset values.
* @note To reset all ADC instances quickly (perform a hard reset),
* use function @ref LL_ADC_CommonDeInit().
* @note If this functions returns error status, it means that ADC instance
* is in an unknown state.
* In this case, perform a hard reset using high level
* clock source RCC ADC reset.
* Caution: On this STM32 series, if several ADC instances are available
* on the selected device, RCC ADC reset will reset
* all ADC instances belonging to the common ADC instance.
* Refer to function @ref LL_ADC_CommonDeInit().
* @param ADCx ADC instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are de-initialized
* - ERROR: ADC registers are not de-initialized
*/
ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx)
{
ErrorStatus status = SUCCESS;
__IO uint32_t timeout_cpu_cycles = 0UL;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
/* Disable ADC instance if not already disabled. */
if (LL_ADC_IsEnabled(ADCx) == 1UL)
{
/* 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(ADCx, LL_ADC_REG_TRIG_SOFTWARE);
/* Stop potential ADC conversion on going on ADC group regular. */
if (LL_ADC_REG_IsConversionOngoing(ADCx) != 0UL)
{
if (LL_ADC_REG_IsStopConversionOngoing(ADCx) == 0UL)
{
LL_ADC_REG_StopConversion(ADCx);
}
}
/* Set ADC group injected trigger source to SW start to ensure to not */
/* have an external trigger event occurring during the conversion stop */
/* ADC disable process. */
LL_ADC_INJ_SetTriggerSource(ADCx, LL_ADC_INJ_TRIG_SOFTWARE);
/* Stop potential ADC conversion on going on ADC group injected. */
if (LL_ADC_INJ_IsConversionOngoing(ADCx) != 0UL)
{
if (LL_ADC_INJ_IsStopConversionOngoing(ADCx) == 0UL)
{
LL_ADC_INJ_StopConversion(ADCx);
}
}
/* Wait for ADC conversions are effectively stopped */
timeout_cpu_cycles = ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES;
while ((LL_ADC_REG_IsStopConversionOngoing(ADCx)
| LL_ADC_INJ_IsStopConversionOngoing(ADCx)) == 1UL)
{
timeout_cpu_cycles--;
if (timeout_cpu_cycles == 0UL)
{
/* Time-out error */
status = ERROR;
break;
}
}
/* Flush group injected contexts queue (register JSQR): */
/* Note: Bit JQM must be set to empty the contexts queue (otherwise */
/* contexts queue is maintained with the last active context). */
LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY);
/* Disable the ADC instance */
LL_ADC_Disable(ADCx);
/* Wait for ADC instance is effectively disabled */
timeout_cpu_cycles = ADC_TIMEOUT_DISABLE_CPU_CYCLES;
while (LL_ADC_IsDisableOngoing(ADCx) == 1UL)
{
timeout_cpu_cycles--;
if (timeout_cpu_cycles == 0UL)
{
/* Time-out error */
status = ERROR;
break;
}
}
}
/* Check whether ADC state is compliant with expected state */
if (READ_BIT(ADCx->CR,
(ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART
| ADC_CR_ADDIS | ADC_CR_ADEN)
)
== 0UL)
{
/* ========== Reset ADC registers ========== */
/* Reset register IER */
CLEAR_BIT(ADCx->IER,
(LL_ADC_IT_ADRDY
| LL_ADC_IT_EOC
| LL_ADC_IT_EOS
| LL_ADC_IT_OVR
| LL_ADC_IT_EOSMP
| LL_ADC_IT_JEOC
| LL_ADC_IT_JEOS
| LL_ADC_IT_JQOVF
| LL_ADC_IT_AWD1
| LL_ADC_IT_AWD2
| LL_ADC_IT_AWD3
)
);
/* Reset register ISR */
SET_BIT(ADCx->ISR,
(LL_ADC_FLAG_ADRDY
| LL_ADC_FLAG_EOC
| LL_ADC_FLAG_EOS
| LL_ADC_FLAG_OVR
| LL_ADC_FLAG_EOSMP
| LL_ADC_FLAG_JEOC
| LL_ADC_FLAG_JEOS
| LL_ADC_FLAG_JQOVF
| LL_ADC_FLAG_AWD1
| LL_ADC_FLAG_AWD2
| LL_ADC_FLAG_AWD3
)
);
/* Reset register CR */
/* - Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART, */
/* ADC_CR_ADCAL, ADC_CR_ADDIS, ADC_CR_ADEN are in */
/* access mode "read-set": no direct reset applicable. */
/* - Reset Calibration mode to default setting (single ended). */
/* - Disable ADC internal voltage regulator. */
/* - Enable ADC deep power down. */
/* Note: ADC internal voltage regulator disable and ADC deep power */
/* down enable are conditioned to ADC state disabled: */
/* already done above. */
CLEAR_BIT(ADCx->CR, ADC_CR_ADVREGEN | ADC_CR_ADCALDIF);
SET_BIT(ADCx->CR, ADC_CR_DEEPPWD);
/* Reset register CFGR */
MODIFY_REG(ADCx->CFGR,
(ADC_CFGR_AWD1CH | ADC_CFGR_JAUTO | ADC_CFGR_JAWD1EN
| ADC_CFGR_AWD1EN | ADC_CFGR_AWD1SGL | ADC_CFGR_JQM
| ADC_CFGR_JDISCEN | ADC_CFGR_DISCNUM | ADC_CFGR_DISCEN
| ADC_CFGR_AUTDLY | ADC_CFGR_CONT | ADC_CFGR_OVRMOD
| ADC_CFGR_EXTEN | ADC_CFGR_EXTSEL | ADC_CFGR_ALIGN
| ADC_CFGR_RES | ADC_CFGR_DMACFG | ADC_CFGR_DMAEN),
ADC_CFGR_JQDIS
);
/* Reset register CFGR2 */
CLEAR_BIT(ADCx->CFGR2,
(ADC_CFGR2_ROVSM | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS
| ADC_CFGR2_SWTRIG | ADC_CFGR2_BULB | ADC_CFGR2_SMPTRIG
| ADC_CFGR2_GCOMP
| ADC_CFGR2_OVSR | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE)
);
/* Reset register SMPR1 */
CLEAR_BIT(ADCx->SMPR1,
(ADC_SMPR1_SMP9 | ADC_SMPR1_SMP8 | ADC_SMPR1_SMP7
| ADC_SMPR1_SMP6 | ADC_SMPR1_SMP5 | ADC_SMPR1_SMP4
| ADC_SMPR1_SMP3 | ADC_SMPR1_SMP2 | ADC_SMPR1_SMP1)
);
/* Reset register SMPR2 */
CLEAR_BIT(ADCx->SMPR2,
(ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16
| ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13
| ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10)
);
/* Reset register TR1 */
MODIFY_REG(ADCx->TR1, ADC_TR1_AWDFILT | ADC_TR1_HT1 | ADC_TR1_LT1, ADC_TR1_HT1);
/* Reset register TR2 */
MODIFY_REG(ADCx->TR2, ADC_TR2_HT2 | ADC_TR2_LT2, ADC_TR2_HT2);
/* Reset register TR3 */
MODIFY_REG(ADCx->TR3, ADC_TR3_HT3 | ADC_TR3_LT3, ADC_TR3_HT3);
/* Reset register SQR1 */
CLEAR_BIT(ADCx->SQR1,
(ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2
| ADC_SQR1_SQ1 | ADC_SQR1_L)
);
/* Reset register SQR2 */
CLEAR_BIT(ADCx->SQR2,
(ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7
| ADC_SQR2_SQ6 | ADC_SQR2_SQ5)
);
/* Reset register SQR3 */
CLEAR_BIT(ADCx->SQR3,
(ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12
| ADC_SQR3_SQ11 | ADC_SQR3_SQ10)
);
/* Reset register SQR4 */
CLEAR_BIT(ADCx->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15);
/* Reset register JSQR */
CLEAR_BIT(ADCx->JSQR,
(ADC_JSQR_JL
| ADC_JSQR_JEXTSEL | ADC_JSQR_JEXTEN
| ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3
| ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1)
);
/* Reset register DR */
/* Note: bits in access mode read only, no direct reset applicable */
/* Reset register OFR1 */
CLEAR_BIT(ADCx->OFR1, ADC_OFR1_OFFSET1_EN | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1 | ADC_OFR1_SATEN | ADC_OFR1_OFFSETPOS);
/* Reset register OFR2 */
CLEAR_BIT(ADCx->OFR2, ADC_OFR2_OFFSET2_EN | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2 | ADC_OFR2_SATEN | ADC_OFR2_OFFSETPOS);
/* Reset register OFR3 */
CLEAR_BIT(ADCx->OFR3, ADC_OFR3_OFFSET3_EN | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3 | ADC_OFR3_SATEN | ADC_OFR3_OFFSETPOS);
/* Reset register OFR4 */
CLEAR_BIT(ADCx->OFR4, ADC_OFR4_OFFSET4_EN | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4 | ADC_OFR4_SATEN | ADC_OFR4_OFFSETPOS);
/* Reset registers JDR1, JDR2, JDR3, JDR4 */
/* Note: bits in access mode read only, no direct reset applicable */
/* Reset register AWD2CR */
CLEAR_BIT(ADCx->AWD2CR, ADC_AWD2CR_AWD2CH);
/* Reset register AWD3CR */
CLEAR_BIT(ADCx->AWD3CR, ADC_AWD3CR_AWD3CH);
/* Reset register DIFSEL */
CLEAR_BIT(ADCx->DIFSEL, ADC_DIFSEL_DIFSEL);
/* Reset register CALFACT */
CLEAR_BIT(ADCx->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S);
/* Reset register GCOMP */
CLEAR_BIT(ADCx->GCOMP, ADC_GCOMP_GCOMPCOEFF);
}
else
{
/* ADC instance is in an unknown state */
/* Need to performing a hard reset of ADC instance, using high level */
/* clock source RCC ADC reset. */
/* Caution: On this STM32 series, if several ADC instances are available */
/* on the selected device, RCC ADC reset will reset */
/* all ADC instances belonging to the common ADC instance. */
/* Caution: On this STM32 series, if several ADC instances are available */
/* on the selected device, RCC ADC reset will reset */
/* all ADC instances belonging to the common ADC instance. */
status = ERROR;
}
return status;
}
/**
* @brief Initialize some features of ADC instance.
* @note These parameters have an impact on ADC scope: ADC instance.
* Affects both group regular and group injected (availability
* of ADC group injected depends on STM32 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 ADCx ADC instance
* @param ADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are initialized
* - ERROR: ADC registers are not initialized
*/
ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
assert_param(IS_LL_ADC_RESOLUTION(ADC_InitStruct->Resolution));
assert_param(IS_LL_ADC_DATA_ALIGN(ADC_InitStruct->DataAlignment));
assert_param(IS_LL_ADC_LOW_POWER(ADC_InitStruct->LowPowerMode));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if (LL_ADC_IsEnabled(ADCx) == 0UL)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC instance */
/* - Set ADC data resolution */
/* - Set ADC conversion data alignment */
/* - Set ADC low power mode */
MODIFY_REG(ADCx->CFGR,
ADC_CFGR_RES
| ADC_CFGR_ALIGN
| ADC_CFGR_AUTDLY
,
ADC_InitStruct->Resolution
| ADC_InitStruct->DataAlignment
| ADC_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 ADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct)
{
/* Set ADC_InitStruct fields to default values */
/* Set fields of ADC instance */
ADC_InitStruct->Resolution = LL_ADC_RESOLUTION_12B;
ADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT;
ADC_InitStruct->LowPowerMode = LL_ADC_LP_MODE_NONE;
}
/**
* @brief Initialize some features of ADC group regular.
* @note These parameters have an impact on ADC scope: ADC group regular.
* Refer to corresponding unitary functions into
* @ref ADC_LL_EF_Configuration_ADC_Group_Regular
* (functions with prefix "REG").
* @note The setting of these parameters by function @ref LL_ADC_Init()
* is conditioned to ADC state:
* ADC instance must be disabled.
* This condition is applied to all ADC features, for efficiency
* and compatibility over all STM32 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 ADCx ADC instance
* @param ADC_REG_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_REG_Init(ADC_TypeDef *ADCx, LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADCx, ADC_REG_InitStruct->TriggerSource));
assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(ADC_REG_InitStruct->SequencerLength));
if (ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(ADC_REG_InitStruct->SequencerDiscont));
/* ADC group regular continuous mode and discontinuous mode */
/* can not be enabled simultenaeously */
assert_param((ADC_REG_InitStruct->ContinuousMode == LL_ADC_REG_CONV_SINGLE)
|| (ADC_REG_InitStruct->SequencerDiscont == LL_ADC_REG_SEQ_DISCONT_DISABLE));
}
assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(ADC_REG_InitStruct->ContinuousMode));
assert_param(IS_LL_ADC_REG_DMA_TRANSFER(ADC_REG_InitStruct->DMATransfer));
assert_param(IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(ADC_REG_InitStruct->Overrun));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if (LL_ADC_IsEnabled(ADCx) == 0UL)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC group regular */
/* - Set ADC group regular trigger source */
/* - Set ADC group regular sequencer length */
/* - Set ADC group regular sequencer discontinuous mode */
/* - Set ADC group regular continuous mode */
/* - Set ADC group regular conversion data transfer: no transfer or */
/* transfer by DMA, and DMA requests mode */
/* - Set ADC group regular overrun behavior */
/* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */
/* setting of trigger source to SW start. */
if (ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(ADCx->CFGR,
ADC_CFGR_EXTSEL
| ADC_CFGR_EXTEN
| ADC_CFGR_DISCEN
| ADC_CFGR_DISCNUM
| ADC_CFGR_CONT
| ADC_CFGR_DMAEN
| ADC_CFGR_DMACFG
| ADC_CFGR_OVRMOD
,
ADC_REG_InitStruct->TriggerSource
| ADC_REG_InitStruct->SequencerDiscont
| ADC_REG_InitStruct->ContinuousMode
| ADC_REG_InitStruct->DMATransfer
| ADC_REG_InitStruct->Overrun
);
}
else
{
MODIFY_REG(ADCx->CFGR,
ADC_CFGR_EXTSEL
| ADC_CFGR_EXTEN
| ADC_CFGR_DISCEN
| ADC_CFGR_DISCNUM
| ADC_CFGR_CONT
| ADC_CFGR_DMAEN
| ADC_CFGR_DMACFG
| ADC_CFGR_OVRMOD
,
ADC_REG_InitStruct->TriggerSource
| LL_ADC_REG_SEQ_DISCONT_DISABLE
| ADC_REG_InitStruct->ContinuousMode
| ADC_REG_InitStruct->DMATransfer
| ADC_REG_InitStruct->Overrun
);
}
/* Set ADC group regular sequencer length and scan direction */
LL_ADC_REG_SetSequencerLength(ADCx, ADC_REG_InitStruct->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 ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct)
{
/* Set ADC_REG_InitStruct fields to default values */
/* Set fields of ADC group regular */
/* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */
/* setting of trigger source to SW start. */
ADC_REG_InitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE;
ADC_REG_InitStruct->SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE;
ADC_REG_InitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE;
ADC_REG_InitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE;
ADC_REG_InitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE;
ADC_REG_InitStruct->Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN;
}
/**
* @brief Initialize some features of ADC group injected.
* @note These parameters have an impact on ADC scope: ADC group injected.
* Refer to corresponding unitary functions into
* @ref ADC_LL_EF_Configuration_ADC_Group_Regular
* (functions with prefix "INJ").
* @note The setting of these parameters by function @ref LL_ADC_Init()
* is conditioned to ADC state:
* ADC instance must be disabled.
* This condition is applied to all ADC features, for efficiency
* and compatibility over all STM32 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();
* @note Caution if feature ADC group injected contexts queue is enabled
* (refer to with function @ref LL_ADC_INJ_SetQueueMode() ):
* using successively several times this function will appear as
* having no effect.
* To set several features of ADC group injected, use
* function @ref LL_ADC_INJ_ConfigQueueContext().
* @param ADCx ADC instance
* @param ADC_INJ_InitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are initialized
* - ERROR: ADC registers are not initialized
*/
ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(ADCx, ADC_INJ_InitStruct->TriggerSource));
assert_param(IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(ADC_INJ_InitStruct->SequencerLength));
if (ADC_INJ_InitStruct->SequencerLength != LL_ADC_INJ_SEQ_SCAN_DISABLE)
{
assert_param(IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(ADC_INJ_InitStruct->SequencerDiscont));
}
assert_param(IS_LL_ADC_INJ_TRIG_AUTO(ADC_INJ_InitStruct->TrigAuto));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if (LL_ADC_IsEnabled(ADCx) == 0UL)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC group injected */
/* - Set ADC group injected trigger source */
/* - Set ADC group injected sequencer length */
/* - Set ADC group injected sequencer discontinuous mode */
/* - Set ADC group injected conversion trigger: independent or */
/* from ADC group regular */
/* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */
/* setting of trigger source to SW start. */
if (ADC_INJ_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(ADCx->CFGR,
ADC_CFGR_JDISCEN
| ADC_CFGR_JAUTO
,
ADC_INJ_InitStruct->SequencerDiscont
| ADC_INJ_InitStruct->TrigAuto
);
}
else
{
MODIFY_REG(ADCx->CFGR,
ADC_CFGR_JDISCEN
| ADC_CFGR_JAUTO
,
LL_ADC_REG_SEQ_DISCONT_DISABLE
| ADC_INJ_InitStruct->TrigAuto
);
}
MODIFY_REG(ADCx->JSQR,
ADC_JSQR_JEXTSEL
| ADC_JSQR_JEXTEN
| ADC_JSQR_JL
,
ADC_INJ_InitStruct->TriggerSource
| ADC_INJ_InitStruct->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 ADC_INJ_InitStruct 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 *ADC_INJ_InitStruct)
{
/* Set ADC_INJ_InitStruct fields to default values */
/* Set fields of ADC group injected */
ADC_INJ_InitStruct->TriggerSource = LL_ADC_INJ_TRIG_SOFTWARE;
ADC_INJ_InitStruct->SequencerLength = LL_ADC_INJ_SEQ_SCAN_DISABLE;
ADC_INJ_InitStruct->SequencerDiscont = LL_ADC_INJ_SEQ_DISCONT_DISABLE;
ADC_INJ_InitStruct->TrigAuto = LL_ADC_INJ_TRIG_INDEPENDENT;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ADC1 || ADC2 || ADC3 || ADC4 || ADC5 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 76,251 |
C
| 52.472651 | 126 | 0.48503 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_gpio.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_gpio.c
* @author MCD Application Team
* @brief GPIO LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_gpio.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG)
/** @addtogroup GPIO_LL
* @{
*/
/** MISRA C:2012 deviation rule has been granted for following rules:
* Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of
* range of the shift operator in following API :
* LL_GPIO_Init
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup GPIO_LL_Private_Macros
* @{
*/
#define IS_LL_GPIO_PIN(__VALUE__) (((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);
}
else if (GPIOx == GPIOD)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOD);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOD);
}
else if (GPIOx == GPIOE)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOE);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOE);
}
else if (GPIOx == GPIOF)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOF);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOF);
}
else if (GPIOx == GPIOG)
{
LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_GPIOG);
LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_GPIOG);
}
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) != 0x00000000U)
{
/* Get current io position */
currentpin = (GPIO_InitStruct->Pin) & (0x00000001UL << pinpos);
if (currentpin != 0x00u)
{
if ((GPIO_InitStruct->Mode == LL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE))
{
/* Check Speed mode parameters */
assert_param(IS_LL_GPIO_SPEED(GPIO_InitStruct->Speed));
/* Speed mode configuration */
LL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed);
/* Check Output mode parameters */
assert_param(IS_LL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType));
/* Output mode configuration*/
LL_GPIO_SetPinOutputType(GPIOx, GPIO_InitStruct->Pin, GPIO_InitStruct->OutputType);
}
/* Pull-up Pull down resistor configuration*/
LL_GPIO_SetPinPull(GPIOx, currentpin, GPIO_InitStruct->Pull);
if (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE)
{
/* Check Alternate parameter */
assert_param(IS_LL_GPIO_ALTERNATE(GPIO_InitStruct->Alternate));
/* Speed mode configuration */
if (currentpin < LL_GPIO_PIN_8)
{
LL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate);
}
else
{
LL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate);
}
}
/* Pin Mode configuration */
LL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode);
}
pinpos++;
}
return (SUCCESS);
}
/**
* @brief Set each @ref LL_GPIO_InitTypeDef field to default value.
* @param GPIO_InitStruct pointer to a @ref LL_GPIO_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_GPIO_StructInit(LL_GPIO_InitTypeDef *GPIO_InitStruct)
{
/* Reset GPIO init structure parameters values */
GPIO_InitStruct->Pin = LL_GPIO_PIN_ALL;
GPIO_InitStruct->Mode = LL_GPIO_MODE_ANALOG;
GPIO_InitStruct->Speed = LL_GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct->OutputType = LL_GPIO_OUTPUT_PUSHPULL;
GPIO_InitStruct->Pull = LL_GPIO_PULL_NO;
GPIO_InitStruct->Alternate = LL_GPIO_AF_0;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
| 9,708 |
C
| 34.826568 | 142 | 0.502266 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_usart_ex.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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;
}
/**
* @}
*/
/**
* @}
*/
/** @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 */
/**
* @}
*/
/**
* @}
*/
| 15,812 |
C
| 28.175277 | 98 | 0.610422 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_fmac.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_fmac.c
* @author MCD Application Team
* @brief Header for stm32g4xx_ll_fmac.c module
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_fmac.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_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 */
| 3,249 |
C
| 22.722628 | 82 | 0.493998 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_smartcard.c
|
/**
******************************************************************************
* @file stm32g4xx_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) 2019 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 "stm32g4xx_hal.h"
/** @addtogroup STM32G4xx_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)
{
/* 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;
/* Enable the SMARTCARD transmit DMA channel */
if (HAL_DMA_Start_IT(hsmartcard->hdmatx, (uint32_t)hsmartcard->pTxBuffPtr, (uint32_t)&hsmartcard->Instance->TDR,
Size) == 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)
{
/* 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;
/* Enable the DMA channel */
if (HAL_DMA_Start_IT(hsmartcard->hdmarx, (uint32_t)&hsmartcard->Instance->RDR, (uint32_t)hsmartcard->pRxBuffPtr,
Size) == 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 */
/**
* @}
*/
/**
* @}
*/
| 124,129 |
C
| 37.936637 | 148 | 0.653892 |
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_utils.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_utils.c
* @author MCD Application Team
* @brief UTILS LL module driver.
******************************************************************************
* @attention
*
* Copyright (c) 2019 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 "stm32g4xx_ll_utils.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_system.h"
#include "stm32g4xx_ll_pwr.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
/** @addtogroup UTILS_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup UTILS_LL_Private_Constants
* @{
*/
#define UTILS_MAX_FREQUENCY_SCALE1 170000000U /*!< Maximum frequency for system clock at power scale1, in Hz */
#define UTILS_MAX_FREQUENCY_SCALE2 26000000U /*!< Maximum frequency for system clock at power scale2, in Hz */
/* Defines used for PLL range */
#define UTILS_PLLVCO_INPUT_MIN 2660000U /*!< Frequency min for PLLVCO input, in Hz */
#define UTILS_PLLVCO_INPUT_MAX 8000000U /*!< 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 48000000U /*!< Frequency max for HSE frequency, in Hz */
/* Defines used for FLASH latency according to HCLK Frequency */
#define UTILS_SCALE1_LATENCY1_FREQ 20000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */
#define UTILS_SCALE1_LATENCY2_FREQ 40000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */
#define UTILS_SCALE1_LATENCY3_FREQ 60000000U /*!< HCLK frequency to set FLASH latency 3 in power scale 1 */
#define UTILS_SCALE1_LATENCY4_FREQ 80000000U /*!< HCLK frequency to set FLASH latency 4 in power scale 1 */
#define UTILS_SCALE1_LATENCY5_FREQ 100000000U /*!< HCLK frequency to set FLASH latency 5 in power scale 1 */
#define UTILS_SCALE1_LATENCY6_FREQ 120000000U /*!< HCLK frequency to set FLASH latency 6 in power scale 1 */
#define UTILS_SCALE1_LATENCY7_FREQ 140000000U /*!< HCLK frequency to set FLASH latency 7 in power scale 1 */
#define UTILS_SCALE1_LATENCY8_FREQ 160000000U /*!< HCLK frequency to set FLASH latency 8 in power scale 1 */
#define UTILS_SCALE1_LATENCY9_FREQ 170000000U /*!< HCLK frequency to set FLASH latency 9 in power scale 1 */
#define UTILS_SCALE2_LATENCY1_FREQ 8000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 2 */
#define UTILS_SCALE2_LATENCY2_FREQ 16000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 2 */
#define UTILS_SCALE2_LATENCY3_FREQ 26000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 2 */
/**
* @}
*/
/* 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_PLLM_VALUE(__VALUE__) (((__VALUE__) == LL_RCC_PLLM_DIV_1) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_2) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_3) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_4) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_5) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_6) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_7) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_8) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_9) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_10) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_11) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_12) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_13) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_14) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_15) \
|| ((__VALUE__) == LL_RCC_PLLM_DIV_16))
#define IS_LL_UTILS_PLLN_VALUE(__VALUE__) ((8U <= (__VALUE__)) && ((__VALUE__) <= 127U))
#define IS_LL_UTILS_PLLR_VALUE(__VALUE__) (((__VALUE__) == LL_RCC_PLLR_DIV_2) \
|| ((__VALUE__) == LL_RCC_PLLR_DIV_4) \
|| ((__VALUE__) == LL_RCC_PLLR_DIV_6) \
|| ((__VALUE__) == LL_RCC_PLLR_DIV_8))
#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_SCALE1) ? ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1) : \
((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE2))
#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; /* MISRAC2012-Rule-17.8 */
/* Add this code to indicate that local variable is not used */
((void)tmp);
tmpDelay = Delay;
/* 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 is
170000000 Hz for STM32G4xx.
@endverbatim
@internal
Depending on the device voltage range, the maximum frequency should be
adapted accordingly:
(++) Table 1. HCLK clock frequency for STM32G4xx devices
(++) +--------------------------------------------------------+
(++) | Latency | HCLK clock frequency (MHz) |
(++) | |--------------------------------------|
(++) | | voltage range 1 | voltage range 2 |
(++) | | 1.2 V | 1.0 V |
(++) |-----------------|-------------------|------------------|
(++) |0WS(1 CPU cycles)| 0 < HCLK <= 20 | 0 < HCLK <= 8 |
(++) |-----------------|-------------------|------------------|
(++) |1WS(2 CPU cycles)| 20 < HCLK <= 40 | 8 < HCLK <= 16 |
(++) |-----------------|-------------------|------------------|
(++) |2WS(3 CPU cycles)| 40 < HCLK <= 60 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |3WS(4 CPU cycles)| 60 < HCLK <= 80 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |4WS(5 CPU cycles)| 80 < HCLK <= 100 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |5WS(6 CPU cycles)| 100 < HCLK <= 120 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |6WS(7 CPU cycles)| 120 < HCLK <= 140 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |7WS(8 CPU cycles)| 140 < HCLK <= 160 | 16 < HCLK <= 26 |
(++) |-----------------|-------------------|------------------|
(++) |8WS(9 CPU cycles)| 160 < HCLK <= 170 | 16 < HCLK <= 26 |
(++) +--------------------------------------------------------+
@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 HCLKFrequency HCLK frequency
* @retval An ErrorStatus enumeration value:
* - SUCCESS: Latency has been modified
* - ERROR: Latency cannot be modified
*/
ErrorStatus LL_SetFlashLatency(uint32_t HCLKFrequency)
{
uint32_t timeout;
uint32_t getlatency;
ErrorStatus status = SUCCESS;
uint32_t latency = LL_FLASH_LATENCY_0; /* default value 0WS */
/* Frequency cannot be equal to 0 or greater than max clock */
if((HCLKFrequency == 0U) || (HCLKFrequency > UTILS_SCALE1_LATENCY9_FREQ))
{
status = ERROR;
}
else
{
if(LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE1)
{
if(HCLKFrequency > UTILS_SCALE1_LATENCY8_FREQ)
{
/* 160 < HCLK <= 170 => 8WS (9 CPU cycles) */
latency = LL_FLASH_LATENCY_8;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY7_FREQ)
{
/* 140 < HCLK <= 160 => 7WS (8 CPU cycles) */
latency = LL_FLASH_LATENCY_7;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY6_FREQ)
{
/* 120 < HCLK <= 140 => 6WS (7 CPU cycles) */
latency = LL_FLASH_LATENCY_6;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY5_FREQ)
{
/* 100 < HCLK <= 120 => 5WS (6 CPU cycles) */
latency = LL_FLASH_LATENCY_5;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY4_FREQ)
{
/* 80 < HCLK <= 100 => 4WS (5 CPU cycles) */
latency = LL_FLASH_LATENCY_4;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY3_FREQ)
{
/* 60 < HCLK <= 80 => 3WS (4 CPU cycles) */
latency = LL_FLASH_LATENCY_3;
}
else if(HCLKFrequency > UTILS_SCALE1_LATENCY2_FREQ)
{
/* 40 < HCLK <= 60 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else
{
if(HCLKFrequency > UTILS_SCALE1_LATENCY1_FREQ)
{
/* 20 < HCLK <= 40 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
/* else HCLKFrequency <= 10MHz default LL_FLASH_LATENCY_0 0WS */
}
}
else /* SCALE2 */
{
if(HCLKFrequency > UTILS_SCALE2_LATENCY2_FREQ)
{
/* 16 < HCLK <= 26 => 2WS (3 CPU cycles) */
latency = LL_FLASH_LATENCY_2;
}
else
{
if(HCLKFrequency > UTILS_SCALE2_LATENCY1_FREQ)
{
/* 8 < HCLK <= 16 => 1WS (2 CPU cycles) */
latency = LL_FLASH_LATENCY_1;
}
/* else HCLKFrequency <= 8MHz default LL_FLASH_LATENCY_0 0WS */
}
}
if (status != ERROR)
{
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 = 2U;
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 at maximum frequency with HSI as clock source of the PLL
* @note The application need to ensure that PLL is disabled.
* @note Function is based on the following formula:
* - PLL output frequency = (((HSI frequency / PLLM) * PLLN) / PLLR)
* - PLLM: ensure that the VCO input frequency ranges from 2.66 to 8 MHz (PLLVCO_input = HSI frequency / PLLM)
* - PLLN: ensure that the VCO output frequency is between 64 and 344 MHz (PLLVCO_output = PLLVCO_input * PLLN)
* - PLLR: ensure that max frequency at 170000000 Hz is reach (PLLVCO_output / PLLR)
* @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;
uint32_t hpre = LL_RCC_SYSCLK_DIV_1;
/* 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_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN,
UTILS_PLLInitStruct->PLLR);
/* Prevent undershoot at highest frequency by applying intermediate AHB prescaler 2 */
if(pllfreq > 80000000U)
{
if (UTILS_ClkInitStruct->AHBCLKDivider == LL_RCC_SYSCLK_DIV_1)
{
UTILS_ClkInitStruct->AHBCLKDivider = LL_RCC_SYSCLK_DIV_2;
hpre = LL_RCC_SYSCLK_DIV_2;
}
}
/* Enable PLL and switch system clock to PLL */
status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct);
/* Apply definitive AHB prescaler value if necessary */
if ((status == SUCCESS) && (hpre != LL_RCC_SYSCLK_DIV_1))
{
/* Set FLASH latency to highest latency */
status = LL_SetFlashLatency(pllfreq);
if (status == SUCCESS)
{
UTILS_ClkInitStruct->AHBCLKDivider = LL_RCC_SYSCLK_DIV_1;
LL_RCC_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider);
LL_SetSystemCoreClock(pllfreq);
}
}
}
else
{
/* Current PLL configuration cannot be modified */
status = ERROR;
}
return status;
}
/**
* @brief This function configures system clock with HSE as clock source of the PLL
* @note The application need to ensure that PLL is disabled.
* @note Function is based on the following formula:
* - PLL output frequency = (((HSE frequency / PLLM) * PLLN) / PLLR)
* - PLLM: ensure that the VCO input frequency ranges from 2.66 to 8 MHz (PLLVCO_input = HSE frequency / PLLM)
* - PLLN: ensure that the VCO output frequency is between 64 and 344 MHz (PLLVCO_output = PLLVCO_input * PLLN)
* - PLLR: ensure that max frequency at 170000000 Hz is reached (PLLVCO_output / PLLR)
* @param HSEFrequency Value between Min_Data = 4000000 and Max_Data = 48000000
* @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;
uint32_t hpre = LL_RCC_SYSCLK_DIV_1;
/* 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_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSE, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN,
UTILS_PLLInitStruct->PLLR);
/* Prevent undershoot at highest frequency by applying intermediate AHB prescaler 2 */
if(pllfreq > 80000000U)
{
if (UTILS_ClkInitStruct->AHBCLKDivider == LL_RCC_SYSCLK_DIV_1)
{
UTILS_ClkInitStruct->AHBCLKDivider = LL_RCC_SYSCLK_DIV_2;
hpre = LL_RCC_SYSCLK_DIV_2;
}
}
/* Enable PLL and switch system clock to PLL */
status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct);
/* Apply definitive AHB prescaler value if necessary */
if ((status == SUCCESS) && (hpre != LL_RCC_SYSCLK_DIV_1))
{
/* Set FLASH latency to highest latency */
status = LL_SetFlashLatency(pllfreq);
if (status == SUCCESS)
{
UTILS_ClkInitStruct->AHBCLKDivider = LL_RCC_SYSCLK_DIV_1;
LL_RCC_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider);
LL_SetSystemCoreClock(pllfreq);
}
}
}
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 2.66 to 8 MHz. */
pllfreq = PLL_InputFrequency / (((UTILS_PLLInitStruct->PLLM >> RCC_PLLCFGR_PLLM_Pos) + 1U));
assert_param(IS_LL_UTILS_PLLVCO_INPUT(pllfreq));
/* - PLLN: ensure that the VCO output frequency is between 64 and 344 MHz.*/
pllfreq = pllfreq * (UTILS_PLLInitStruct->PLLN & (RCC_PLLCFGR_PLLN >> RCC_PLLCFGR_PLLN_Pos));
assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(pllfreq));
/* - PLLR: ensure that max frequency at 170000000 Hz is reached */
pllfreq = pllfreq / (((UTILS_PLLInitStruct->PLLR >> RCC_PLLCFGR_PLLR_Pos) + 1U) * 2U);
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 PLL is busy*/
if(LL_RCC_PLL_IsReady() != 0U)
{
/* PLL 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));
/* 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 PLL */
LL_RCC_PLL_Enable();
LL_RCC_PLL_EnableDomain_SYS();
while (LL_RCC_PLL_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_PLL);
while (LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
{
/* Wait for system clock switch to PLL */
}
/* Set APB1 & APB2 prescaler*/
LL_RCC_SetAPB1Prescaler(UTILS_ClkInitStruct->APB1CLKDivider);
LL_RCC_SetAPB2Prescaler(UTILS_ClkInitStruct->APB2CLKDivider);
}
/* 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;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 27,465 |
C
| 38.237143 | 159 | 0.547278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.