file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/stspin32g4.c
/** ****************************************************************************** * @file stspin32g4.c * @author P. Lombardi, IPC Application Team * @brief Implementation of STSPIN32G4 driver library ****************************************************************************** * @attention * * <h2><center>&copy; 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 * ****************************************************************************** **/ #if defined(USE_FULL_LL_DRIVER) #include <stm32g4xx_ll_i2c.h> #include <stm32g4xx_ll_gpio.h> #include <stm32g4xx_ll_bus.h> #include <stm32g4xx_ll_cortex.h> #include <stm32g4xx_ll_rcc.h> #include <stm32g4xx_ll_utils.h> #else #include <stm32g4xx_hal.h> #include <stm32g4xx_hal_def.h> #include <stm32g4xx_hal_i2c.h> #endif #include <stdint.h> #include <stdbool.h> #include <stspin32g4.h> #define STSPIN32G4_I2C_TIMEOUT (100u) #define STSPIN32G4_I2C_LOCKCODE (0xDu) #if defined(USE_FULL_LL_DRIVER) #define GD_READY_GPIO_Port GPIOE #define GD_READY_Pin LL_GPIO_PIN_14 #define GD_NFAULT_GPIO_Port GPIOE #define GD_NFAULT_Pin LL_GPIO_PIN_15 #define GD_WAKE_GPIO_Port GPIOE #define GD_WAKE_Pin LL_GPIO_PIN_7 #else #define GD_READY_GPIO_Port GPIOE #define GD_READY_Pin GPIO_PIN_14 #define GD_NFAULT_GPIO_Port GPIOE #define GD_NFAULT_Pin GPIO_PIN_15 #define GD_WAKE_GPIO_Port GPIOE #define GD_WAKE_Pin GPIO_PIN_7 #endif static uint8_t STSPIN32G4_bkupREADY; #if !defined(USE_FULL_LL_DRIVER) extern I2C_HandleTypeDef hi2c3; #endif void SystemClock_Config(void); STSPIN32G4_StatusTypeDef STSPIN32G4_init(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { return STSPIN32G4_ERROR; } #if defined(USE_FULL_LL_DRIVER) LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; hdl->i2cHdl = I2C3; LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOE); LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); GPIO_InitStruct.Pin = GD_WAKE_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Speed = LL_GPIO_SPEED_LOW; LL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_INPUT; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_INPUT; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #else GPIO_InitTypeDef GPIO_InitStruct = {0}; hdl->i2cHdl = &hi2c3; __HAL_RCC_GPIOE_CLK_ENABLE(); HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); GPIO_InitStruct.Pin = GD_WAKE_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #endif if (status != STSPIN32G4_OK) { return status; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_deInit(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; #if defined(USE_FULL_LL_DRIVER) LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; status = (STSPIN32G4_StatusTypeDef) LL_I2C_DeInit(hdl->i2cHdl); GPIO_InitStruct.Mode = LL_GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Pin = GD_WAKE_Pin; LL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; LL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; LL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #else status = (STSPIN32G4_StatusTypeDef) HAL_I2C_DeInit(hdl->i2cHdl); HAL_GPIO_DeInit(GD_WAKE_GPIO_Port, GD_WAKE_Pin); HAL_GPIO_DeInit(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin); HAL_GPIO_DeInit(GD_READY_GPIO_Port, GD_READY_Pin); #endif hdl->i2cHdl = NULL; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_lockReg(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statusReg; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } i2cReg = ((STSPIN32G4_I2C_LOCKCODE << 4) & 0xf0) | (STSPIN32G4_I2C_LOCKCODE & 0x0f); status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOCK, i2cReg); #ifdef STSPIN32G4_I2C_LOCKUSEPARANOID if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statusReg); } if (status == STSPIN32G4_OK) { if (statusReg.lock != 1) { status = STSPIN32G4_ERROR; } } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_unlockReg(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statusReg; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } i2cReg = (((~STSPIN32G4_I2C_LOCKCODE) << 4) & 0xf0) | (STSPIN32G4_I2C_LOCKCODE & 0x0f); status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOCK, i2cReg); #ifdef STSPIN32G4_I2C_LOCKUSEPARANOID if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statusReg); } if (status == STSPIN32G4_OK) { if (statusReg.lock == 1) { status = STSPIN32G4_ERROR; } } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_readReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t *value) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (hdl->i2cHdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (value == NULL) { status = STSPIN32G4_ERROR; return status; } #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); uint32_t tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } uint8_t stat = 0; uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * tickFreq) / 1000 + 1; while (true) { switch (stat) { case 0: stat += !LL_I2C_IsActiveFlag_BUSY(hdl->i2cHdl); break; case 1: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, LL_I2C_MODE_SOFTEND, LL_I2C_GENERATE_START_WRITE); stat++; break; case 2: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 3: LL_I2C_TransmitData8(hdl->i2cHdl, regAddr); stat++; break; case 4: stat += LL_I2C_IsActiveFlag_TC(hdl->i2cHdl); break; case 5: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_AUTOEND, LL_I2C_GENERATE_START_READ); stat++; break; case 6: stat += LL_I2C_IsActiveFlag_RXNE(hdl->i2cHdl); break; case 7: *value = LL_I2C_ReceiveData8(hdl->i2cHdl); stat++; break; case 8: stat += LL_I2C_IsActiveFlag_STOP(hdl->i2cHdl); break; case 9: LL_I2C_ClearFlag_STOP(hdl->i2cHdl); status = STSPIN32G4_OK; return status; default: status = STSPIN32G4_ERROR; return status; } if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if(ticks == 0) { status = STSPIN32G4_TIMEOUT; return status; } } #else uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * HAL_GetTickFreq()) / 1000 + 1; status = (STSPIN32G4_StatusTypeDef) HAL_I2C_Mem_Read(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, (uint16_t) regAddr, 1, value, 1, ticks); return status; #endif } STSPIN32G4_StatusTypeDef STSPIN32G4_writeReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (hdl->i2cHdl == NULL) { status = STSPIN32G4_ERROR; return status; } #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); uint32_t tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } uint8_t stat = 0; uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * tickFreq) / 1000 + 1; while (true) { switch (stat) { case 0: stat += !LL_I2C_IsActiveFlag_BUSY(hdl->i2cHdl); break; case 1: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_RELOAD, LL_I2C_GENERATE_START_WRITE); stat++; break; case 2: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 3: LL_I2C_TransmitData8(hdl->i2cHdl, regAddr); stat++; break; case 4: stat += LL_I2C_IsActiveFlag_TCR(hdl->i2cHdl); break; case 5: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_AUTOEND, LL_I2C_GENERATE_NOSTARTSTOP); stat++; break; case 6: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 7: LL_I2C_TransmitData8(hdl->i2cHdl, value); stat++; break; case 8: stat += LL_I2C_IsActiveFlag_STOP(hdl->i2cHdl); break; case 9: LL_I2C_ClearFlag_STOP(hdl->i2cHdl); status = STSPIN32G4_OK; return status; default: status = STSPIN32G4_ERROR; return status; } if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if(ticks == 0) { status = STSPIN32G4_TIMEOUT; return status; } } #else uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * HAL_GetTickFreq()) / 1000 + 1; status = (STSPIN32G4_StatusTypeDef) HAL_I2C_Mem_Write(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, (uint16_t) regAddr, 1, &value, 1, ticks); return status; #endif } STSPIN32G4_StatusTypeDef STSPIN32G4_writeVerifyReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; status = STSPIN32G4_writeReg(hdl, regAddr, value); if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, regAddr, &i2cReg); } if (status == STSPIN32G4_OK) { if (value != i2cReg) { status = STSPIN32G4_ERROR; } } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_set3V3(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg &= ~STSPIN32G4_I2C_REG3V3_DIS; } else { i2cReg |= STSPIN32G4_I2C_REG3V3_DIS; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_get3V3(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_REG3V3_DIS) ? false : true; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC vcc) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { switch (vcc.voltage) { case _EXT: i2cReg |= STSPIN32G4_I2C_VCC_DIS; break; case _8V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_0; break; case _10V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_1; break; case _12V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_2; break; case _15V: i2cReg &= ~STSPIN32G4_I2C_VCC_DIS; i2cReg |= STSPIN32G4_I2C_VCC_VAL_3; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); } if (status == STSPIN32G4_OK) // configuration of nFAULT pin { if (vcc.useNFAULT) { i2cReg |= STSPIN32G4_I2C_VCC_UVLO_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_VCC_UVLO_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); } if (status == STSPIN32G4_OK) // configuration of READY pin { if (vcc.useREADY) { i2cReg |= STSPIN32G4_I2C_VCC_UVLO_RDY; } else { i2cReg &= ~STSPIN32G4_I2C_VCC_UVLO_RDY; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC *vcc) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (vcc == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { if (i2cReg & STSPIN32G4_I2C_VCC_DIS) { vcc->voltage = _EXT; } else { switch (i2cReg & STSPIN32G4_I2C_VCC_VAL_3) { case STSPIN32G4_I2C_VCC_VAL_0: vcc->voltage = _8V; break; case STSPIN32G4_I2C_VCC_VAL_1: vcc->voltage = _10V; break; case STSPIN32G4_I2C_VCC_VAL_2: vcc->voltage = _12V; break; case STSPIN32G4_I2C_VCC_VAL_3: vcc->voltage = _15V; break; default: status = STSPIN32G4_ERROR; break; } } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); vcc->useNFAULT = (i2cReg & STSPIN32G4_I2C_VCC_UVLO_FLT) ? true : false; } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); vcc->useREADY = (i2cReg & STSPIN32G4_I2C_VCC_UVLO_RDY) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg |= STSPIN32G4_I2C_ILOCK; } else { i2cReg &= ~STSPIN32G4_I2C_ILOCK; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_ILOCK) ? true : false; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg |= STSPIN32G4_I2C_DTMIN; } else { i2cReg &= ~STSPIN32G4_I2C_DTMIN; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_DTMIN) ? true : false; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP vdsp) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { i2cReg &= ~STSPIN32G4_I2C_VDS_P_DEG_3; switch (vdsp.deglitchTime) { case _6us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_0; break; case _4us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_1; break; case _3us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_2; break; case _2us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_3; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); } if (status == STSPIN32G4_OK) // configure nFault signaling { if (vdsp.useNFAULT) { i2cReg |= STSPIN32G4_I2C_VDS_P_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_VDS_P_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP *vdsp) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (vdsp == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { switch (i2cReg & STSPIN32G4_I2C_VDS_P_DEG_3) { case STSPIN32G4_I2C_VDS_P_DEG_0: vdsp->deglitchTime = _6us; break; case STSPIN32G4_I2C_VDS_P_DEG_1: vdsp->deglitchTime = _4us; break; case STSPIN32G4_I2C_VDS_P_DEG_2: vdsp->deglitchTime = _3us; break; case STSPIN32G4_I2C_VDS_P_DEG_3: vdsp->deglitchTime = _2us; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); vdsp->useNFAULT = (i2cReg & STSPIN32G4_I2C_VDS_P_FLT) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD thsd) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (thsd.useNFAULT) { i2cReg |= STSPIN32G4_I2C_THSD_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_THSD_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); } if (status == STSPIN32G4_OK) { if (thsd.useREADY) { i2cReg |= STSPIN32G4_I2C_THSD_RDY; } else { i2cReg &= ~STSPIN32G4_I2C_THSD_RDY; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD *thsd) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (thsd == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); thsd->useNFAULT = (i2cReg & STSPIN32G4_I2C_THSD_FLT) ? true : false; if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); thsd->useREADY = (i2cReg & STSPIN32G4_I2C_THSD_RDY) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_clearFaults(STSPIN32G4_HandleTypeDef *hdl) { uint8_t i2cReg = 0xff; if (hdl == NULL) { return STSPIN32G4_ERROR; } return STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_CLEAR, i2cReg); } STSPIN32G4_StatusTypeDef STSPIN32G4_reset(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0xff; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_unlockReg(hdl); if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_RESET, i2cReg); } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_standby(STSPIN32G4_HandleTypeDef *hdl, bool enableStbyReg) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; uint32_t tickFreq; uint32_t ticks; #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } #else uint32_t tickStart; tickFreq = HAL_GetTickFreq() / 1000; // in kHz to have ms base #endif if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) // configure the Standby regulator { if (enableStbyReg) { i2cReg |= STSPIN32G4_I2C_STBY_REG_EN; } else { i2cReg &= ~STSPIN32G4_I2C_STBY_REG_EN; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) // create backup of the READY register { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &STSPIN32G4_bkupREADY); } if (status == STSPIN32G4_OK) // set only STBY_RDY to signal the exit from standby { i2cReg = STSPIN32G4_I2C_STBY_RDY; status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) // WAKE line low { #if defined(USE_FULL_LL_DRIVER) LL_GPIO_ResetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); #else HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_RESET); #endif } #ifdef STSPIN32G4_HSI16 if (status == STSPIN32G4_OK) { if (enableStbyReg) { // Set HSI16 clock to reduce current consumption #if defined(USE_FULL_LL_DRIVER) status = (STSPIN32G4_StatusTypeDef) LL_RCC_DeInit(); #else status = (STSPIN32G4_StatusTypeDef) HAL_RCC_DeInit(); #endif } } #endif // request to enter standby if (status == STSPIN32G4_OK) { i2cReg = 0x01; status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_STBY, i2cReg); } ticks = (1 * tickFreq) / 1000 + 1; #if defined(USE_FULL_LL_DRIVER) if (LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); status = STSPIN32G4_ERROR; } else { LL_SYSTICK_IsActiveCounterFlag(); while (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if (ticks == 0) { status = STSPIN32G4_TIMEOUT; break; } } } #else if (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_SET) { HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); status = STSPIN32G4_ERROR; } else { tickStart = HAL_GetTick(); while (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_RESET) { if ((HAL_GetTick() - tickStart) > ticks) // expected time is 100us { status = STSPIN32G4_TIMEOUT; break; } } } #endif // wait 1ms and check possible exit from standby #if defined(USE_FULL_LL_DRIVER) LL_mDelay(ticks); if (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin) || !LL_GPIO_IsInputPinSet(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin)) { status = STSPIN32G4_ERROR; } #else HAL_Delay(ticks); if ((HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) != GPIO_PIN_SET) || (HAL_GPIO_ReadPin(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin) != GPIO_PIN_SET)) { status = STSPIN32G4_ERROR; } #endif #ifdef STSPIN32G4_HSI16 // if the driver failed to enter standby clock is reconfigured if (status != STSPIN32G4_OK) { SystemClock_Config(); // restore clock configuration } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_wakeup(STSPIN32G4_HandleTypeDef *hdl, uint8_t timeout_ms) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statReg; uint32_t tickFreq; uint32_t ticks; #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } #else uint32_t tickStart; tickFreq = HAL_GetTickFreq() / 1000; // in kHz to have ms base #endif if (hdl == NULL) { return STSPIN32G4_ERROR; } #if defined(USE_FULL_LL_DRIVER) LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); #else HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); #endif if (timeout_ms < 4) { timeout_ms = 4; // The soft start is expected to take 4ms } ticks = (timeout_ms * tickFreq) / 1000 + 1; #if defined(USE_FULL_LL_DRIVER) LL_SYSTICK_IsActiveCounterFlag(); while (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if (ticks == 0) { status = STSPIN32G4_TIMEOUT; break; } } #else tickStart = HAL_GetTick(); while (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_RESET) { if ((HAL_GetTick() - tickStart) > ticks) { status = STSPIN32G4_TIMEOUT; break; } } #endif #ifdef STSPIN32G4_HSI16 if (status == STSPIN32G4_OK) { SystemClock_Config(); } #endif // Restore READY register if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, STSPIN32G4_bkupREADY); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_lockReg(hdl); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statReg); } if (status == STSPIN32G4_OK) { if (statReg.reset == 1) { status = STSPIN32G4_ERROR; } } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_getStatus(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_statusRegTypeDef *status) { if (hdl == NULL) { return STSPIN32G4_ERROR; } if (status == NULL) { return STSPIN32G4_ERROR; } return STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_STATUS, (uint8_t *)status); }
29,260
C
19.62086
138
0.636569
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_2_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_2_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; 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 R3_2_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_2_G4XX_PWMNCURRFDBK_H #define R3_2_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ #ifndef R3_3_OPAMP #define R3_3_OPAMP /** * @brief Current feedback component 3-OPAMP parameters structure definition. Specific to G4XX. */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ uint32_t OPAMPConfig2 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ } R3_3_OPAMPParams_t; #endif /* * @brief R3_2_G4XX_pwm_curr_fdbk component parameters structure definition. */ typedef const struct { /* HW IP involved -----------------------------*/ TIM_TypeDef *TIMx; /* timer used for PWM generation.*/ R3_3_OPAMPParams_t *OPAMPParams; /*!< Pointer to the 3-OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used. Specific to G4XX.*/ COMP_TypeDef *CompOCPASelection; /* Internal comparator used for Phase A protection.*/ COMP_TypeDef *CompOCPBSelection; /* Internal comparator used for Phase B protection.*/ COMP_TypeDef *CompOCPCSelection; /* Internal comparator used for Phase C protection.*/ COMP_TypeDef *CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ DAC_TypeDef *DAC_OCP_ASelection; /*!< DAC used for Phase A protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_BSelection; /*!< DAC used for Phase B protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_CSelection; /*!< DAC used for Phase C protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPA; /*!< DAC channel used for Phase A current protection.*/ uint32_t DAC_Channel_OCPB; /*!< DAC channel used for Phase B current protection.*/ uint32_t DAC_Channel_OCPC; /*!< DAC channel used for Phase C current protection.*/ uint32_t DAC_Channel_OVP; /*!< DAC channel used for Over Voltage protection.*/ ADC_TypeDef *ADCDataReg1[6]; ADC_TypeDef *ADCDataReg2[6]; uint32_t ADCConfig1 [6] ; /* Values of JSQR for first ADC for 6 sectors */ uint32_t ADCConfig2 [6] ; /* Values of JSQR for Second ADC for 6 sectors */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R3_2_Params_t, *pR3_2_Params_t; /* * @brief Handles an instance of the R3_2_G4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalPolarityInjected; /* External trigger selection for ADC peripheral. */ volatile uint8_t PolarizationCounter; uint8_t PolarizationSector; /* Sector selected during calibration phase. */ pR3_2_Params_t pParams_str; bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. Specific to G4XX. */ /* Cut 2.2 patch*/ } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. */ void R3_2_Init(PWMC_R3_2_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_2_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and returns latest converted motor phase currents. */ void R3_2_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Computes and return latest converted motor phase currents. */ void R3_2_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 1. */ uint16_t R3_2_SetADCSampPointSectX(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_2_TIMx_UP_IRQHandler(PWMC_R3_2_Handle_t *pHandle); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable(PWMC_Handle_t *pHdl); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable(PWMC_Handle_t *pHdl); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty); /* * Turns on low sides switches and start ADC triggering. * This function is specific for MP phase. */ void R3_2_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl); /* * Sets the calibrated offset. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_2_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
11,237
C
40.014598
130
0.554418
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/ics_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; 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 ICS_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef ICS_G4XX_PWMNCURRFDBK_H #define ICS_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief ICS_G4XX_pwm_curr_fdbk component parameters definition. */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx_1; /* First ADC peripheral to be used.*/ ADC_TypeDef *ADCx_2; /* Second ADC peripheral to be used.*/ TIM_TypeDef *TIMx; /* Timer used for PWM generation.*/ uint32_t ADCConfig1; /*!< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ uint32_t ADCConfig2; /*!< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When FreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ } ICS_Params_t, *pICS_Params_t; /* * This structure is used to handle an instance of the ICS_G4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. Specific to G4XX. */ /* Cut 2.2 patch*/ pICS_Params_t pParams_str; } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32G4XX. */ void ICS_Init(PWMC_ICS_Handle_t *pHandle); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void ICS_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *ICS_TIMx_UP_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt. */ void *ICS_BRK2_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt. */ void *ICS_BRK_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*ICS_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,573
C
33.239583
127
0.538871
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/stspin32g4.h
/** ****************************************************************************** * @file stspin32g4.h * @author IPC Application Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICSSTSPIN32G4 driver library. ****************************************************************************** * @attention * * <h2><center>&copy; 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 stspin32g4_STSPIN32G4_DriverLib */ /** * * @defgroup stspin32g4_STSPIN32G4_DriverLib STSPIN32G4 Driver Library * @{ * * <h2>Operation</h2> * The STSPIN32G4 is a system in package integrating a triple high-performance * STSPIN32G4f-bridge gate driver with a rich set of programmable features * and one mixed signal STM32G431 microcontroller. * This library provides functions to configure STSPIN32G4 gate driver * but does not include functions to generate PWM signals for MOSFETs driving * * @pre This library requires at least HAL drivers 1.3.0 or Low-layer (LL) drivers 1.5.0 * * The library should be included in an application as follows: * @code * #include <stspin32g4.h> * @endcode * * <h3>Opening the driver</h3> * @code * STSPIN32G4_HandleTypeDef hdlG4; * * STSPIN32G4_StatusTypeDef res = STSPIN32G4_init(&hdlG4); * * if(res != STSPIN32G4_OK) * STSPIN32G4_deInit(&hdlG4); * @endcode * * <h3>Example</h3> * The following code shows a minimal device configuration to operate the gate driver * @code * // Purge registers to default values * STSPIN32G4_reset(&hdlG4); * * // Configure the Buck regulator at 12V and map VCC UVLO on NFAULT pin * STSPIN32G4_confVCC vcc = {.voltage = _12V, .useNFAULT=true, .useREADY=false}; * STSPIN32G4_setVCC(&hdlG4, vcc); * * // Configure VDSP protection with 4us deglitch time and map triggering on NFAULT pin * STSPIN32G4_confVDSP vdsp = {.deglitchTime=_4us, .useNFAULT=true}; * STSPIN32G4_setVDSP(&hdlG4, vdsp); * * // After reset a clearing of fault is needed to enable GHSx/GLSx outputs * STSPIN32G4_clearFaults(&hdlG4); * @endcode * <h3>Closing the driver</h3> * @code * // Reset the device to put GHSx/GLSx outputs in safe state * STSPIN32G4_reset(&hdlG4); * * // Close the driver * STSPIN32G4_deInit(&hdlG4); * @endcode * * <h3>Standby</h3> * * @code * // Enter Standby enabling low quiescent regulator * if(STSPIN32G4_OK == STSPIN32G4_standby(&hdlG4, true)) * { * // Stay 1s in standby * HAL_Delay(1000); // or LL_mDelay(1000); * * // Wakeup the driver waiting 4ms for completion of VCC soft-start * STSPIN32G4_wakeup(&hdlG4, 4); * } * else * { * // Consumption from 3.3V supply is likely too high * } * @endcode */ /** * @defgroup stspin32g4_Basic Basic * @brief Basic function and definitions to work with STSPIN32G4 * @{ * @} */ /** * @defgroup stspin32g4_PowerManagement Power Management * @brief Function and definitions to manage regulators embedded in STSPIN32G4 and standby * @{ * @} */ /** * @defgroup stspin32g4_Protections Protections * @brief Function and definitions to configure protection features of STSPIN32G4 * @{ * @} */ /** @defgroup stspin32g4_I2c Driver Registers @brief Function and definitions to directly access I2C registers of STSPIN32G4 @{ @} */ /** @} */ #ifndef STSPIN32G4 #define STSPIN32G4 #if defined(USE_FULL_LL_DRIVER) #include <stm32g4xx_ll_i2c.h> #include <stm32g4xx_ll_gpio.h> #include <stm32g4xx_ll_bus.h> #include <stm32g4xx_ll_cortex.h> #include <stm32g4xx_ll_rcc.h> #include <stm32g4xx_ll_utils.h> #else #include <stm32g4xx_hal.h> #include <stm32g4xx_hal_def.h> #include <stm32g4xx_hal_i2c.h> #endif #include <stdint.h> #include <stdbool.h> /** @ingroup stspin32g4_I2c @{ */ #define STSPIN32G4_I2C_LOCKUSEPARANOID /**< Flag to check status register lock bit in functions STSPIN32G4_lockReg() and STSPIN32G4_unlockReg() */ #define STSPIN32G4_I2C_ADDR (0x8E) /**< I2C address of STSPIN32G4 */ #define STSPIN32G4_I2C_POWMNG (0x01) /**< Address of register POWMNG */ #define STSPIN32G4_I2C_REG3V3_DIS (1<<6) /**< Bit REG3V3_DIS */ #define STSPIN32G4_I2C_VCC_DIS (1<<5) /**< Bit VCC_DIS */ #define STSPIN32G4_I2C_STBY_REG_EN (1<<4) /**< Bit STBY_REG_EN */ #define STSPIN32G4_I2C_VCC_VAL_0 (0) /**< Bits VCC_VAL as 00, (VCC=8V) */ #define STSPIN32G4_I2C_VCC_VAL_1 (1) /**< Bits VCC_VAL as 01, (VCC=10V) */ #define STSPIN32G4_I2C_VCC_VAL_2 (2) /**< Bits VCC_VAL as 10, (VCC=12V) */ #define STSPIN32G4_I2C_VCC_VAL_3 (3) /**< Bits VCC_VAL as 11, (VCC=15V) */ #define STSPIN32G4_I2C_LOGIC (0x02) /**< Address of register LOGIC */ #define STSPIN32G4_I2C_VDS_P_DEG_0 (0<<2) /**< Bits VDS_P_DEG as 00, (6us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_1 (1<<2) /**< Bits VDS_P_DEG as 01, (4us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_2 (2<<2) /**< Bits VDS_P_DEG as 10, (3us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_3 (3<<2) /**< Bits VDS_P_DEG as 11, (2us deglitch) */ #define STSPIN32G4_I2C_DTMIN (1<<1) /**< Bit DTMIN */ #define STSPIN32G4_I2C_ILOCK (1<<0) /**< Bit ILOCK */ #define STSPIN32G4_I2C_READY (0x07) /**< Address of register READY */ #define STSPIN32G4_I2C_STBY_RDY (1<<3) /**< Bit STBY_RDY */ #define STSPIN32G4_I2C_THSD_RDY (1<<1) /**< Bit THSD_RDY */ #define STSPIN32G4_I2C_VCC_UVLO_RDY (1<<0) /**< Bit VCC_UVLO_RDY */ #define STSPIN32G4_I2C_NFAULT (0x08) /**< Address of register NFAULT */ #define STSPIN32G4_I2C_RESET_FLT (1<<3) /**< Bit RESET_FLT */ #define STSPIN32G4_I2C_VDS_P_FLT (1<<2) /**< Bit VDS_P_FLT */ #define STSPIN32G4_I2C_THSD_FLT (1<<1) /**< Bit THSD_FLT */ #define STSPIN32G4_I2C_VCC_UVLO_FLT (1<<0) /**< Bit VCC_UVLO_FLT */ #define STSPIN32G4_I2C_CLEAR (0x09) /**< Address of register CLEAR */ #define STSPIN32G4_I2C_STBY (0x0A) /**< Address of register STBY */ #define STSPIN32G4_I2C_LOCK (0x0B) /**< Address of register LOCK */ #define STSPIN32G4_I2C_RESET (0x0C) /**< Address of register RESET */ #define STSPIN32G4_I2C_STATUS (0x80) /**< Address of register STATUS */ /** @} */ /** @ingroup stspin32g4_PowerManagement @{ */ #define STSPIN32G4_HSI16 /**< Flag to automatically reduce system clock frequency before entering standby in function STSPIN32G4_standby() */ /** @brief Possible results of library functions. */ typedef enum { STSPIN32G4_OK = 0, /**< Operation successfully completed. */ STSPIN32G4_ERROR = 1, /**< Operation failed. */ STSPIN32G4_BUSY = 2, /**< The operation cannot be performed since a needed resource is not ready or available. */ STSPIN32G4_TIMEOUT = 3 /**< A timeout occurred before operation ended. */ } STSPIN32G4_StatusTypeDef; /** @brief Configuration for VCC voltage to be used with functions STSPIN32G4_setVCC() and STSPIN32G4_getVCC(). @details The STSPIN32G4 embeds a Buck converter to generate the supply voltage for the gate drivers, VCC, starting from the motor supply voltage. \n Four different VCC output values can be selected. \n The Under Voltage Lock Out (UVLO) condition of VCC can be signaled via pins nFAULT and READY. */ typedef struct { /** @brief VCC voltage selection. @details When VCC set point is changed the Buck converter performs a soft-start ramp. */ enum valVCC { _EXT = 0, /**< Buck converter is disabled and VCC should be supplied externally. */ _8V, /**< VCC = 8V generetad by Buck converter. Deafult value. */ _10V, /**< VCC = 10V generetad by Buck converter. */ _12V, /**< VCC = 12V generetad by Buck converter. */ _15V /**< VCC = 15V generetad by Buck converter. */ } voltage; /**< Value assigned to VCC voltage */ bool useNFAULT; /**< If true the nNFAULT pin goes low when device is in VCC UVLO condition. */ bool useREADY; /**< If true the READY pin goes low when device is in VCC UVLO condition. */ } STSPIN32G4_confVCC; /** @} */ /** @brief Configuration for VDS monitoring protection to be used with functions STSPIN32G4_setVDSP() and STSPIN32G4_getVDSP(). @details The STSPIN32G4 embeds a circuitry which measures the voltage between the drain and the source of each MOSFET (VDS) and compares it with a specified threshold set by voltage of SCREF pin. In case an overvoltage of one MOSFET is detected, all gate driver outputs GHSx and GLSx go low whatever the driver inputs INHx and INLx. \n The protection provides a deglitch filtering with configurable value. \n Triggering of the protection can be signaled via nFAULT pin. \n Function STSPIN32G4_clearFaults() can be used to clear the fault condition and make the device operative again. @ingroup stspin32g4_Protections */ typedef struct { /** @brief Deglitch filtering time for VDS protection. @ingroup stspin32g4_Protections */ enum degVDSP { _6us = 0, /**< 6 micro seconds. Deafult value. */ _4us, /**< 4 micro seconds */ _3us, /**< 3 micro seconds */ _2us /**< 2 micro seconds */ } deglitchTime; /**< Value assigned to deglitch filtering time of VDS protection */ bool useNFAULT; /**< If true the nNFAULT pin goes low in case of VDS protection triggering. */ } STSPIN32G4_confVDSP; /** @brief Configuration for Thermal Shutdown signaling to be used with functions STSPIN32G4_setTHSD() and STSPIN32G4_getTHSD(). @details The STSPIN32G4 embeds one Buck converter and one LDO linear regulator. Both voltage regulators are protected in case of overheating by thermal shutdown. \n The protection is always active and its triggering can be signaled via nFAULT and READY pins. @ingroup stspin32g4_Protections */ typedef struct { bool useNFAULT; /**< If true the nFAULT pin goes low in case of Thermal Shutdown. */ bool useREADY; /**< If true the READY pin goes low in case of Thermal Shutdown. */ } STSPIN32G4_confTHSD; /** @brief Status register fileds to be used with function STSPIN32G4_getStatus() @ingroup stspin32g4_Basic */ typedef struct { uint8_t vccUvlo:1; /**< If 1 the device is in VCC UVLO condition. While in VCC UVLO condition the device cannot drive MOSFETs*/ uint8_t thsd:1; /**< If 1 one voltage regulator is in Thermal Shutdown. While in Thermal Shutdown the device cannot drive MOSFETs*/ uint8_t vdsp:1; /**< If 1 the VDS protection triggered. Use STSPIN32G4_clearFaults() to make the device operative again. */ uint8_t reset:1; /**< If 1 the device performed a reset or power up. Use STSPIN32G4_clearFaults() to make the device operative. */ uint8_t r1:1; /**< Reserved. */ uint8_t r2:1; /**< Reserved. */ uint8_t r3:1; /**< Reserved. */ uint8_t lock:1; /**< If 1 the protected registers are locked and cannot be modified. */ } STSPIN32G4_statusRegTypeDef; /** @brief Handler of STSPIN32G4 driver to be used with all driver functions @see STSPIN32G4_init() for example code @ingroup stspin32g4_Basic */ typedef struct { #if defined(USE_FULL_LL_DRIVER) I2C_TypeDef *i2cHdl; /**< Handler to i2c3 */ #else I2C_HandleTypeDef *i2cHdl; /**< Handler to i2c3 */ #endif } STSPIN32G4_HandleTypeDef; /** @brief Initialize the STSPIN32G4 driver @pre The STSPIN32G4_HandleTypeDef structure must exist and be persistent before this function can be called. \n This function must also be called before any other driver APIs. \n The driver uses I2C3 interface which must be already initialized. \n Initialization example: @code STSPIN32G4_HandleTypeDef hdlG4; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_init(&hdlG4); @endcode @param [out] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_init(STSPIN32G4_HandleTypeDef *hdl); /** @brief De-initialize the STSPIN32G4 driver @param [in] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_deInit(STSPIN32G4_HandleTypeDef *hdl); /** @brief Perform a reset. All registers will be set to their default values. @param [in] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_reset(STSPIN32G4_HandleTypeDef *hdl); /** @brief Get the status register @see STSPIN32G4_statusRegTypeDef @param [in] hdl Driver handler @param [out] status Current value of the status register @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_getStatus(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_statusRegTypeDef *status); /** @brief Enable or Disable the LDO linear regulator @param [in] hdl Driver handler @param [in] enabled If 1 the 3.3V supply is internally generated via the LDO linear regulator. \n If 0 the LDO regulator is disabled and the 3.3V supply have to be provided externally. @warning The device will perform a reset if the LDO is disabled without providing externally the 3.3V supply. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_set3V3(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of LDO linear regulator @param [in] hdl Driver handler @param [out] enabled Set to 1 if the internal LDO is active, 0 otherwise. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_get3V3(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the Buck converter and VCC UVLO signaling @see STSPIN32G4_confVCC @param [in] hdl Driver handler @param [in] vcc VCC configuration to be applied \n Example to set VCC at 12V and enable VCC UVLO singaling on NFAULT pin: @code STSPIN32G4_confVCC vcc = {.voltage = _12V, .useNFAULT=true, .useREADY=false}; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_setVCC(&hdlG4, vcc); @endcode @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement **/ STSPIN32G4_StatusTypeDef STSPIN32G4_setVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC vcc); /** @brief Get current configuration of Buck converter and VCC UVLO signaling @see STSPIN32G4_confVCC @param [in] hdl Driver handler @param [out] vcc Current VCC configuration @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_getVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC *vcc); /** @brief Configures the Thermal Shutdown signaling @see STSPIN32G4_confTHSD @param [in] hdl Driver handler @param [in] thsd Configuration of Thermal Shutdown signaling to be applied @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD thsd); /** @brief Get current configuration of the Thermal Shutdown signaling @see STSPIN32G4_confTHSD @param [in] hdl Driver handler @param [out] thsd Current configuration of Thermal Shutdown signaling @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD *thsd); /** @brief Requests the device to enter standby mode @details In standby mode the device turns off most of its internal circuitry with inclusion of Buck converter, LDO linear regulator and gate drivers. \n In standby the overall current consumption is reduced to ~15uA and the MCU can be supplied via dedicated low quiescent linear regulator from main supply voltage. @param [in] hdl Driver handler @param [in] enableStbyReg If 1 the internal low quiescent linear regulator will be activated when entering standby mode @warning Overall consumption from 3.3V supply should be reduced as much as possible before entering standby. \n In case the consumption exceeds 5mA the device will automatically exit from standby performing a reset. \n Disable all MCU peripherals and reduce system clock frequency before calling function STSPIN32G4_standby(). \n If flag STSPIN32G4_HSI16 is used, the driver will automatically reduce system clock frequency. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_standby(STSPIN32G4_HandleTypeDef *hdl, bool enableStbyReg); /** @brief Wake up from standby @param [in] hdl Driver handler @param [in] timeout_ms Timeout in milliseconds allowed for device wake up. The minimum value is 4. @return STSPIN32G4_ERROR in case of failure \n STSPIN32G4_TIMEOUT in case the timeout time elapsed before device returned operative \n STSPIN32G4_OK in case of proper wake up @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_wakeup(STSPIN32G4_HandleTypeDef *hdl, uint8_t timeout_ms); /** @brief Configures the interlocking @details The device integrates interlocking features that prevents the power stage from accidental cross conduction. \n HS and LS MOSFET of same channel cannot be turned on simultaneously when interlocking is active. @param [in] hdl Driver handler @param [in] enabled If 1 the interlocking is enabled. \n If 0 the interlocking is disabled. @warning Disable the interlocking is potentially desruptive for power stage. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of the interlocking @param [in] hdl Driver handler @param [out] enabled If 1 the interlocking is enabled. \n If 0 the interlocking is disabled. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the minimum deadtime @details The device integrates a minimum deadtime features. When enabled a minimum delay is imposed between the turn-off of one MOSFET and the turn-on of the complementary one. @param [in] hdl Driver handler @param [in] enabled If 1 the minimum deadtime is enabled \n If 0 the the minimum deadtime is disabled. \n The minimum deadtime is not added to the one imposed by the MCU @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of the minimum deadtime @param [in] hdl Driver handler @param [out] enabled If 1 the minimum deadtime is enabled \n If 0 the the minimum deadtime is disabled. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the VDS monitoring protection @see STSPIN32G4_confVDSP @param [in] hdl Driver handler. @param [in] vdsp Settings of the VDS protection. @note Example to set deglitch time to 4 microsenconds and enable signaling on NFAULT pin: @code STSPIN32G4_confVDSP vdsp = {.deglitchTime=_4us, .useNFAULT=true}; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_setVDSP(&hdlG4, vdsp); @endcode @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP vdsp); /** @brief Get current configuration for the VDS monitoring protection @see STSPIN32G4_confVDSP @param [in] hdl Driver handler. @param [out] vdsp Current configuration for the VDS protection. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP *vdsp); /** @brief Clear a fault condition @param [in] hdl Driver handler. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_clearFaults(STSPIN32G4_HandleTypeDef *hdl); /** @brief Lock protected registers @param [in] hdl Driver handler. @note With flag STSPIN32G4_I2C_LOCKUSEPARANOID the lock bit of status register will be tested to 1 at the end of locking. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_lockReg(STSPIN32G4_HandleTypeDef *hdl); /** @brief Un-Lock protected registers @param [in] hdl Driver handler. @note With flag STSPIN32G4_I2C_LOCKUSEPARANOID the lock bit of status register will be tested to 0 at the end of unlocking. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_unlockReg(STSPIN32G4_HandleTypeDef *hdl); /** @brief Read register at address @p regAddr @param [in] hdl Driver handler. @param [in] regAddr Address of the register to read. @param [out] value Contains the register value. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_readReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t *value); /** @brief Write register at address @p regAddr @param [in] hdl Driver handler. @param [in] regAddr Address of the register to write. @param [in] value Content to write in the register. @warning Before writing a protected register use function STSPIN32G4_unlockReg() @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_writeReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value); /** @brief Write register at address @p regAddr then read back register and verify value matching @param [in] hdl Driver handler. @param [in] regAddr Address of the register to write. @param [in] value Content to write in the register. @warning Before writing a protected register use function STSPIN32G4_unlockReg() @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_writeVerifyReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value); #endif //#define STSPIN32G4
23,205
C
38.736301
147
0.727559
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/g4xx_bemf_ADC_fdbk.h
/** ****************************************************************************** * @file g4xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; 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 SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /*!< Length of buffer used to store the timer period measurements */ /** * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /*!< Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /*!< Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /*!< Pointer to the ADC */ uint32_t AdcChannel[3]; /*!< Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /*!< Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /*!< GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /*!< GPIO pin enabling the bemf resistor divider */ } Bemf_ADC_Params_t; /** * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /*!< BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /*!< BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /*!< Pulse value of the timer channel used to trig the ADC */ } Bemf_Sensing_Params; /** * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /*!< Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /*!< Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /*!< Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /*!< Minimum demagnetization time */ } Bemf_Demag_Params; /** * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /**< Bemf measurements of phase */ uint8_t ZcEvents; /**< Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /**< Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /**< Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /*!< Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /*!< Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /*!< Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /*!< Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /*!< Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /*!< Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /*!< This flag is set when ADC is locked for bemf acquisition */ int32_t ElPeriodSum; /*!< Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /*!< Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /*!< Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /*!< Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /*!< Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /*!< Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /*!< Number of consecutive tests on speed consistency to be passed before validating the start-up */ uint8_t OverSamplingRate; bool IsSpeedReliable; /*!< Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /*!< Boolean variable containing observer convergence information */ bool IsLoopClosed; /*!< Boolean variable containing speed loop status*/ bool ZcDetected; /*!< This flag is set when zero crossing is detected */ bool StepUpdate; /*!< This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /*!< Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/*!< Holding the last period captures */ uint32_t LowFreqTimerPsc; /*!< Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/*!< Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /*!< Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle;/*!< Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /*!< Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /*!< Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/*!< Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /*!< Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /*!< Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout;/*!< Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /*!< Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /*!< Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /*!< Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /*!< Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /*!< Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /*!< Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /*!< Last low frequency timer counter value at zero crossing sensed with pwm off*/ uint32_t ZC_Counter_On_Last; /*!< Last low frequency timer counter value at zero crossing sensed with pwm on. Specific to G4XX.*/ uint32_t Last_Zc2Comm_Delay; /*!< Last delay between zero crossing and step change */ uint16_t DemagCounter; /*!< Demagnetization counter */ uint16_t DemagCounterThreshold; /*!< PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /*!< Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,318
C
50.40604
152
0.612547
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_3_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_3_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_3_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** * @ingroup R3_3_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_3_G4XX_PWMNCURRFDBK_H #define __R3_3_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_3_G4XX_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /** * @brief R3_3_G4XX_pwm_curr_fdbk component OPAMP parameters definition */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMP_PHA; /* OPAMP dedicated to phase A */ OPAMP_TypeDef *OPAMP_PHB; /* OPAMP dedicated to phase B */ OPAMP_TypeDef *OPAMP_PHC; /* OPAMP dedicated to phase C */ uint32_t wOPAMP_InvertingInput; /*!< First OPAMP inverting input pin. It must be one of the following: OPAMP1_InvertingInput_PC5 or OPAMP1_InvertingInput_PA3 if the bOPAMP_InvertingInput_MODE is EXT_MODE or OPAMP1_InvertingInput_PGA or OPAMP1_InvertingInput_FOLLOWER if the bOPAMP_InvertingInput_MODE is INT_MODE.*/ uint32_t wOPAMP_NonInvertingInput_PHA; uint32_t wOPAMP_NonInvertingInput_PHB; uint32_t wOPAMP_NonInvertingInput_PHC; } R3_3_G4XXOPAMPParams_t, *pR3_3_G4XXOPAMPParams_t; /** * @brief R3_3_G4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /*!< It is used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /*!< When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef *ADCx_A; /*!< First ADC peripheral to be used.*/ ADC_TypeDef *ADCx_B; /*!< Second ADC peripheral to be used.*/ ADC_TypeDef *ADCx_C; /*!< Third ADC peripheral to be used.*/ /* PWM generation parameters --------------------------------------------------*/ uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ uint16_t hTafter; /*!< It is the sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /*!< It is the sampling time express in number of TIM clocks.*/ TIM_TypeDef *TIMx; /*!< It contains the pointer to the timer used for PWM generation. It must equal to TIM1 if bInstanceNbr is equal to 1, to TIM8 otherwise */ /* PWM Driving signals initialization ----------------------------------------*/ LowSideOutputsFunction_t LowSideOutputs; /*!< Low side or enabling signals generation method are defined here.*/ GPIO_TypeDef *pwm_en_u_port; /*!< Channel 1N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_u_pin; /*!< Channel 1N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ GPIO_TypeDef *pwm_en_v_port; /*!< Channel 2N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_v_pin; /*!< Channel 2N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ GPIO_TypeDef *pwm_en_w_port; /*!< Channel 3N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_w_pin; /*!< Channel 3N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ /* Internal OPAMP common settings --------------------------------------------*/ pR3_3_G4XXOPAMPParams_t pOPAMPParams; /*!< Pointer to the OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used.*/ /* Internal COMP settings ----------------------------------------------------*/ COMP_TypeDef *wCompOCPASelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPAInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOCPBSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPBInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOCPCSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPCInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOVPSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* DAC settings --------------------------------------------------------------*/ uint16_t hDAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t hDAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* Regular conversion --------------------------------------------------------*/ ADC_TypeDef *regconvADCx; /*!< ADC peripheral used for regular conversion.*/ } R3_3_G4XXParams_t, *pR3_3_G4XXParams_t; /** * @brief Handles an instance of the R3_3_G4XX_pwm_curr_fdbk component parameters structure definition. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t wPhaseAOffset; /*!< Offset of Phase A current sensing network. */ uint32_t wPhaseBOffset; /*!< Offset of Phase B current sensing network. */ uint32_t wPhaseCOffset; /*!< Offset of Phase C current sensing network. */ uint32_t wADC_JSQR_phA; /*!< Injected sequence register for the ADC sampling phase A. */ uint32_t wADC_JSQR_phB; /*!< Injected sequence register for the ADC sampling phase B. */ uint32_t wADC_JSQR_phC; /*!< Injected sequence register for the ADC sampling phase C. */ uint32_t wOAMP1CR; /*!< OAMP1 control register to select channel current sampling. */ uint32_t wOAMP2CR; /*!< OAMP2 control register to select channel current sampling. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t hRegConv; /*!< Variable used to store regular conversions result. */ volatile uint8_t bSoFOC; /*!< This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated. */ uint8_t bIndex; /*!< Counter for the number of conversions in one cycle. */ uint16_t ADC_ExternalTriggerInjected; /*!< External trigger selection for ADC peripheral. */ uint16_t ADC_ExternalPolarityInjected; pR3_3_G4XXParams_t pParams_str; } PWMC_R3_3_G4_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. */ void R3_3_G4XX_Init(PWMC_R3_3_G4_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_3_G4XX_CurrentReadingCalibration(PWMC_Handle_t *pHdl); /* * Computes and returns latest converted motor phase currents. */ void R3_3_G4XX_GetPhaseCurrents(PWMC_Handle_t *pHdl, Curr_Components *pStator_Currents); /* * Turns on low sides switches. */ void R3_3_G4XX_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_3_G4XX_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_3_G4XX_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 1. */ uint16_t R3_3_G4XX_SetADCSampPointSect1(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 2. */ uint16_t R3_3_G4XX_SetADCSampPointSect2(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 3. */ uint16_t R3_3_G4XX_SetADCSampPointSect3(PWMC_Handle_t *pHdl); /* * Configure the ADC for the current sampling related to sector 4. */ uint16_t R3_3_G4XX_SetADCSampPointSect4(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 5. */ uint16_t R3_3_G4XX_SetADCSampPointSect5(PWMC_Handle_t *pHdl); /* * Configure the ADC for the current sampling related to sector 6. */ uint16_t R3_3_G4XX_SetADCSampPointSect6(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_3_G4XX_TIMx_UP_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt. */ void *R3_3_G4XX_BRK2_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt. */ void *R3_3_G4XX_BRK_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Sets the calibrated offset. */ void R3_3_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_3_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_3_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
16,204
C
45.83526
105
0.534066
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_1_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_1_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; 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 R3_1_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_1_G4XX_PWMNCURRFDBK_H #define R3_1_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ #ifndef R3_3_OPAMP #define R3_3_OPAMP /** * @brief Current feedback component 3-OPAMP parameters structure definition. Specific to G4XX. */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ uint32_t OPAMPConfig2 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ } R3_3_OPAMPParams_t; #endif /* * @brief R3_1_G4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx; /* ADC peripheral to be used.*/ TIM_TypeDef *TIMx; /* timer used for PWM generation.*/ R3_3_OPAMPParams_t *OPAMPParams; /*!< Pointer to the OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used. Specific to G4XX.*/ COMP_TypeDef *CompOCPASelection; /* Internal comparator used for Phase A protection.*/ COMP_TypeDef *CompOCPBSelection; /* Internal comparator used for Phase B protection.*/ COMP_TypeDef *CompOCPCSelection; /* Internal comparator used for Phase C protection.*/ COMP_TypeDef *CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ DAC_TypeDef *DAC_OCP_ASelection; /*!< DAC used for Phase A protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_BSelection; /*!< DAC used for Phase B protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_CSelection; /*!< DAC used for Phase C protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPA; /*!< DAC channel used for Phase A current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPB; /*!< DAC channel used for Phase B current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPC; /*!< DAC channel used for Phase C current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OVP; /*!< DAC channel used for Over Voltage protection. Specific to G4XX.*/ uint32_t ADCConfig [6] ; /* Stores ADC sequence for the 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R3_1_Params_t, *pR3_1_Params_t; /* * @brief This structure is used to handle an instance of the * PWM and current feedback component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t PolarizationSector; /* Sector selected during calibration phase. */ pR3_1_Params_t pParams_str; bool ADCRegularLocked; /* Cut 2.2 patch, specific to G4XX. */ } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and ADC. */ void R3_1_Init(PWMC_R3_1_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_1_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling . */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling. Specific to overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_1_TIMx_UP_IRQHandler(PWMC_R3_1_Handle_t *pHandle); /* * Sets the calibrated offsets. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable(PWMC_Handle_t *pHdl); /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable(PWMC_Handle_t *pHdl); /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty); /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_RLGetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents); /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t *pHdl); /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_1_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,818
C
39.566456
127
0.581994
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r1_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r1_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R1_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; 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 R1_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R1_G4XX_PWMNCURRFDBK_H #define R1_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) #define STBD3 0x02u /*!< Flag to indicate which phase has been distorted in boudary 3 zone (A or B).*/ #define DSTEN 0x04u /*!< Flag to indicate if the distortion must be performed or not (in case of charge of bootstrap capacitor phase is not required).*/ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /** * @brief Current feedback component parameters structure definition for 1 Shunt configurations. Common to G0XX and G4XX MCUs. */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx; /*!< ADC peripheral to be used. */ TIM_TypeDef *TIMx; /*!< Timer used for PWM generation. */ OPAMP_TypeDef *OPAMP_Selection; /*!< Selected Opamp for 1 shunt configuration. */ COMP_TypeDef *CompOCPSelection; /*!< Internal comparator used for Phases protection. */ COMP_TypeDef *CompOVPSelection; /*!< Internal comparator used for Over Voltage protection. */ 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. */ DAC_TypeDef *DAC_OCP_Selection; /*!< DAC used for Over Current protection. */ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. */ uint32_t DAC_Channel_OCP; /*!< DAC channel used for Phase A current protection. */ uint32_t DAC_Channel_OVP; /*!< DAC channel used for over voltage protection. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t TMin; /* */ uint16_t HTMin; /* */ uint16_t CHTMin; /* */ uint16_t Tbefore; /*!< Sampling time expressed in number of TIM clocks. */ uint16_t Tafter; /*!< Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t TSample; /*!< Sampling time expressed in number of TIM clocks. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V 65536 = VDD_DAC. */ uint16_t DAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V 65536 = VDD_DAC. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t IChannel; uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /*!< It is used in case of dual MC to effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3. */ uint8_t IsHigherFreqTim; /*!< When bFreqRatio is greather than 1 this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R1_Params_t; /** * @brief This structure is used to handle an instance of the * Current feedback component for 1 Shunt configurations. Common to G0XX and G4XX MCUs. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ DMA_Channel_TypeDef * DistortionDMAy_Chx; /*!< DMA resource used for doing the distortion. */ uint32_t ADCConfig; /*!< Values of JSQR register for ADC. */ uint32_t PhaseOffset; /*!< Offset of Phase A current sensing network. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t DmaBuff[2]; uint16_t CntSmp1; uint16_t CntSmp2; uint16_t CurrAOld; uint16_t CurrBOld; uint8_t bIChannel; /*!< ADC channel used for current conversion. */ uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase. */ uint8_t sampCur1; uint8_t sampCur2; uint8_t Inverted_pwm_new; /* */ uint8_t Flags; /* */ bool UpdateFlagBuffer; /*!< Buffered version of Timer update IT flag. */ /* Trigger selection for ADC peripheral.*/ bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. */ R1_Params_t * pParams_str; } PWMC_R1_Handle_t; /** @addtogroup R1_G4XX_pwm_curr_fdbk * @{ */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in single shunt configuration using STM3G4XX */ void R1_Init(PWMC_R1_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowin into the * motor */ void R1_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and return latest converted motor phase currents. */ void R1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches */ void R1_TurnOnLowSides(PWMC_Handle_t *pHdl); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit */ void R1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit */ void R1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling */ uint16_t R1_CalcDutyCycles(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt */ void *R1_TIMx_UP_IRQHandler(PWMC_R1_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt */ void *R1_BRK2_IRQHandler(PWMC_R1_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt */ void *R1_BRK_IRQHandler(PWMC_R1_Handle_t *pHdl); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R1_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
8,878
C
38.995495
127
0.528272
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/STM32CubeIDE/Application/User/sysmem.c
/** ****************************************************************************** * @file sysmem.c * @author Generated by STM32CubeIDE * @brief STM32CubeIDE System Memory calls file * * For more information about which C functions * need which of these lowlevel functions * please consult the newlib libc manual ****************************************************************************** * @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. * ****************************************************************************** */ /* Includes */ #include <errno.h> #include <stdint.h> /** * Pointer to the current high watermark of the heap usage */ static uint8_t *__sbrk_heap_end = NULL; /** * @brief _sbrk() allocates memory to the newlib heap and is used by malloc * and others from the C library * * @verbatim * ############################################################################ * # .data # .bss # newlib heap # MSP stack # * # # # # Reserved by _Min_Stack_Size # * ############################################################################ * ^-- RAM start ^-- _end _estack, RAM end --^ * @endverbatim * * This implementation starts allocating at the '_end' linker symbol * The '_Min_Stack_Size' linker symbol reserves a memory for the MSP stack * The implementation considers '_estack' linker symbol to be RAM end * NOTE: If the MSP stack, at any point during execution, grows larger than the * reserved size, please increase the '_Min_Stack_Size'. * * @param incr Memory size * @return Pointer to allocated memory */ void *_sbrk(ptrdiff_t incr) { extern uint8_t _end; /* Symbol defined in the linker script */ extern uint8_t _estack; /* Symbol defined in the linker script */ extern uint32_t _Min_Stack_Size; /* Symbol defined in the linker script */ const uint32_t stack_limit = (uint32_t)&_estack - (uint32_t)&_Min_Stack_Size; const uint8_t *max_heap = (uint8_t *)stack_limit; uint8_t *prev_heap_end; /* Initialize heap end at first call */ if (NULL == __sbrk_heap_end) { __sbrk_heap_end = &_end; } /* Protect heap from growing into the reserved MSP stack */ if (__sbrk_heap_end + incr > max_heap) { errno = ENOMEM; return (void *)-1; } prev_heap_end = __sbrk_heap_end; __sbrk_heap_end += incr; return (void *)prev_heap_end; }
2,726
C
33.0875
79
0.537784
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_hal_pwr.c
/** ****************************************************************************** * @file stm32g4xx_hal_pwr.c * @author MCD Application Team * @brief PWR HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Power Controller (PWR) peripheral: * + Initialization/de-initialization functions * + Peripheral Control functions * ****************************************************************************** * @attention * * Copyright (c) 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 PWR PWR * @brief PWR HAL module driver * @{ */ #ifdef HAL_PWR_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup PWR_Private_Defines PWR Private Defines * @{ */ /** @defgroup PWR_PVD_Mode_Mask PWR PVD Mode Mask * @{ */ #define PVD_MODE_IT ((uint32_t)0x00010000) /*!< Mask for interruption yielded by PVD threshold crossing */ #define PVD_MODE_EVT ((uint32_t)0x00020000) /*!< Mask for event yielded by PVD threshold crossing */ #define PVD_RISING_EDGE ((uint32_t)0x00000001) /*!< Mask for rising edge set as PVD trigger */ #define PVD_FALLING_EDGE ((uint32_t)0x00000002) /*!< Mask for falling edge set as PVD trigger */ /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup PWR_Exported_Functions PWR Exported Functions * @{ */ /** @defgroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and de-initialization functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] @endverbatim * @{ */ /** * @brief Deinitialize the HAL PWR peripheral registers to their default reset values. * @retval None */ void HAL_PWR_DeInit(void) { __HAL_RCC_PWR_FORCE_RESET(); __HAL_RCC_PWR_RELEASE_RESET(); } /** * @brief Enable access to the backup domain * (RTC registers, RTC backup data registers). * @note After reset, the backup domain is protected against * possible unwanted write accesses. * @note RTCSEL that sets the RTC clock source selection is in the RTC back-up domain. * In order to set or modify the RTC clock, the backup domain access must be * disabled. * @note LSEON bit that switches on and off the LSE crystal belongs as well to the * back-up domain. * @retval None */ void HAL_PWR_EnableBkUpAccess(void) { SET_BIT(PWR->CR1, PWR_CR1_DBP); } /** * @brief Disable access to the backup domain * (RTC registers, RTC backup data registers). * @retval None */ void HAL_PWR_DisableBkUpAccess(void) { CLEAR_BIT(PWR->CR1, PWR_CR1_DBP); } /** * @} */ /** @defgroup PWR_Exported_Functions_Group2 Peripheral Control functions * @brief Low Power modes configuration functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] *** PVD configuration *** ========================= [..] (+) The PVD is used to monitor the VDD power supply by comparing it to a threshold selected by the PVD Level (PLS[2:0] bits in PWR_CR2 register). (+) PVDO flag is available to indicate if VDD/VDDA is higher or lower than the PVD threshold. This event is internally connected to the EXTI line16 and can generate an interrupt if enabled. This is done through __HAL_PVD_EXTI_ENABLE_IT() macro. (+) The PVD is stopped in Standby mode. *** WakeUp pin configuration *** ================================ [..] (+) WakeUp pins are used to wakeup the system from Standby mode or Shutdown mode. The polarity of these pins can be set to configure event detection on high level (rising edge) or low level (falling edge). *** Low Power modes configuration *** ===================================== [..] The devices feature 8 low-power modes: (+) Low-power Run mode: core and peripherals are running, main regulator off, low power regulator on. (+) Sleep mode: Cortex-M4 core stopped, peripherals kept running, main and low power regulators on. (+) Low-power Sleep mode: Cortex-M4 core stopped, peripherals kept running, main regulator off, low power regulator on. (+) Stop 0 mode: all clocks are stopped except LSI and LSE, main and low power regulators on. (+) Stop 1 mode: all clocks are stopped except LSI and LSE, main regulator off, low power regulator on. (+) Standby mode with SRAM2: all clocks are stopped except LSI and LSE, SRAM2 content preserved, main regulator off, low power regulator on. (+) Standby mode without SRAM2: all clocks are stopped except LSI and LSE, main and low power regulators off. (+) Shutdown mode: all clocks are stopped except LSE, main and low power regulators off. *** Low-power run mode *** ========================== [..] (+) Entry: (from main run mode) (++) set LPR bit with HAL_PWREx_EnableLowPowerRunMode() API after having decreased the system clock below 2 MHz. (+) Exit: (++) clear LPR bit then wait for REGLP bit to be reset with HAL_PWREx_DisableLowPowerRunMode() API. Only then can the system clock frequency be increased above 2 MHz. *** Sleep mode / Low-power sleep mode *** ========================================= [..] (+) Entry: The Sleep mode / Low-power Sleep mode is entered through HAL_PWR_EnterSLEEPMode() API in specifying whether or not the regulator is forced to low-power mode and if exit is interrupt or event-triggered. (++) PWR_MAINREGULATOR_ON: Sleep mode (regulator in main mode). (++) PWR_LOWPOWERREGULATOR_ON: Low-power sleep (regulator in low power mode). In the latter case, the system clock frequency must have been decreased below 2 MHz beforehand. (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction (+) WFI Exit: (++) Any peripheral interrupt acknowledged by the nested vectored interrupt controller (NVIC) or any wake-up event. (+) WFE Exit: (++) Any wake-up event such as an EXTI line configured in event mode. [..] When exiting the Low-power sleep mode by issuing an interrupt or a wakeup event, the MCU is in Low-power Run mode. *** Stop 0, Stop 1 modes *** =============================== [..] (+) Entry: The Stop 0, Stop 1 modes are entered through the following API's: (++) HAL_PWREx_EnterSTOP0Mode() for mode 0 or HAL_PWREx_EnterSTOP1Mode() for mode 1 or for porting reasons HAL_PWR_EnterSTOPMode(). (+) Regulator setting (applicable to HAL_PWR_EnterSTOPMode() only): (++) PWR_MAINREGULATOR_ON (++) PWR_LOWPOWERREGULATOR_ON (+) Exit (interrupt or event-triggered, specified when entering STOP mode): (++) PWR_STOPENTRY_WFI: enter Stop mode with WFI instruction (++) PWR_STOPENTRY_WFE: enter Stop mode with WFE instruction (+) WFI Exit: (++) Any EXTI Line (Internal or External) configured in Interrupt mode. (++) Some specific communication peripherals (USART, LPUART, I2C) interrupts when programmed in wakeup mode. (+) WFE Exit: (++) Any EXTI Line (Internal or External) configured in Event mode. [..] When exiting Stop 0 and Stop 1 modes, the MCU is either in Run mode or in Low-power Run mode depending on the LPR bit setting. *** Standby mode *** ==================== [..] The Standby mode offers two options: (+) option a) all clocks off except LSI and LSE, RRS bit set (keeps voltage regulator in low power mode). SRAM and registers contents are lost except for the SRAM2 content, the RTC registers, RTC backup registers and Standby circuitry. (+) option b) all clocks off except LSI and LSE, RRS bit cleared (voltage regulator then disabled). SRAM and register contents are lost except for the RTC registers, RTC backup registers and Standby circuitry. (++) Entry: (+++) The Standby mode is entered through HAL_PWR_EnterSTANDBYMode() API. SRAM1 and register contents are lost except for registers in the Backup domain and Standby circuitry. SRAM2 content can be preserved if the bit RRS is set in PWR_CR3 register. To enable this feature, the user can resort to HAL_PWREx_EnableSRAM2ContentRetention() API to set RRS bit. (++) Exit: (+++) WKUP pin rising edge, RTC alarm or wakeup, tamper event, time-stamp event, external reset in NRST pin, IWDG reset. [..] After waking up from Standby mode, program execution restarts in the same way as after a Reset. *** Shutdown mode *** ====================== [..] In Shutdown mode, voltage regulator is disabled, all clocks are off except LSE, RRS bit is cleared. SRAM and registers contents are lost except for backup domain registers. (+) Entry: The Shutdown mode is entered through HAL_PWREx_EnterSHUTDOWNMode() API. (+) Exit: (++) WKUP pin rising edge, RTC alarm or wakeup, tamper event, time-stamp event, external reset in NRST pin. [..] After waking up from Shutdown mode, program execution restarts in the same way as after a Reset. *** Auto-wakeup (AWU) from low-power mode *** ============================================= [..] The MCU can be woken up from low-power mode by an RTC Alarm event, an RTC Wakeup event, a tamper event or a time-stamp event, without depending on an external interrupt (Auto-wakeup mode). (+) RTC auto-wakeup (AWU) from the Stop, Standby and Shutdown modes (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to configure the RTC to generate the RTC alarm using the HAL_RTC_SetAlarm_IT() function. (++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it is necessary to configure the RTC to detect the tamper or time stamp event using the HAL_RTCEx_SetTimeStamp_IT() or HAL_RTCEx_SetTamper_IT() functions. (++) To wake up from the Stop mode with an RTC WakeUp event, it is necessary to configure the RTC to generate the RTC WakeUp event using the HAL_RTCEx_SetWakeUpTimer_IT() function. @endverbatim * @{ */ /** * @brief Configure the voltage threshold detected by the Power Voltage Detector (PVD). * @param sConfigPVD: pointer to a PWR_PVDTypeDef structure that contains the PVD * configuration information. * @note Refer to the electrical characteristics of your device datasheet for * more details about the voltage thresholds corresponding to each * detection level. * @retval None */ HAL_StatusTypeDef HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD) { /* Check the parameters */ assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel)); assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode)); /* Set PLS bits according to PVDLevel value */ MODIFY_REG(PWR->CR2, PWR_CR2_PLS, sConfigPVD->PVDLevel); /* Clear any previous config. Keep it clear if no event or IT mode is selected */ __HAL_PWR_PVD_EXTI_DISABLE_EVENT(); __HAL_PWR_PVD_EXTI_DISABLE_IT(); __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE(); /* Configure interrupt mode */ if((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT) { __HAL_PWR_PVD_EXTI_ENABLE_IT(); } /* Configure event mode */ if((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT) { __HAL_PWR_PVD_EXTI_ENABLE_EVENT(); } /* Configure the edge */ if((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE) { __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE(); } if((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE) { __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); } return HAL_OK; } /** * @brief Enable the Power Voltage Detector (PVD). * @retval None */ void HAL_PWR_EnablePVD(void) { SET_BIT(PWR->CR2, PWR_CR2_PVDE); } /** * @brief Disable the Power Voltage Detector (PVD). * @retval None */ void HAL_PWR_DisablePVD(void) { CLEAR_BIT(PWR->CR2, PWR_CR2_PVDE); } /** * @brief Enable the WakeUp PINx functionality. * @param WakeUpPinPolarity: Specifies which Wake-Up pin to enable. * This parameter can be one of the following legacy values which set the default polarity * i.e. detection on high level (rising edge): * @arg @ref PWR_WAKEUP_PIN1, PWR_WAKEUP_PIN2, PWR_WAKEUP_PIN3, PWR_WAKEUP_PIN4, PWR_WAKEUP_PIN5 * * or one of the following value where the user can explicitly specify the enabled pin and * the chosen polarity: * @arg @ref PWR_WAKEUP_PIN1_HIGH or PWR_WAKEUP_PIN1_LOW * @arg @ref PWR_WAKEUP_PIN2_HIGH or PWR_WAKEUP_PIN2_LOW * @arg @ref PWR_WAKEUP_PIN3_HIGH or PWR_WAKEUP_PIN3_LOW * @arg @ref PWR_WAKEUP_PIN4_HIGH or PWR_WAKEUP_PIN4_LOW * @arg @ref PWR_WAKEUP_PIN5_HIGH or PWR_WAKEUP_PIN5_LOW * @note PWR_WAKEUP_PINx and PWR_WAKEUP_PINx_HIGH are equivalent. * @retval None */ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinPolarity) { assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinPolarity)); /* Specifies the Wake-Up pin polarity for the event detection (rising or falling edge) */ MODIFY_REG(PWR->CR4, (PWR_CR3_EWUP & WakeUpPinPolarity), (WakeUpPinPolarity >> PWR_WUP_POLARITY_SHIFT)); /* Enable wake-up pin */ SET_BIT(PWR->CR3, (PWR_CR3_EWUP & WakeUpPinPolarity)); } /** * @brief Disable the WakeUp PINx functionality. * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable. * This parameter can be one of the following values: * @arg @ref PWR_WAKEUP_PIN1, PWR_WAKEUP_PIN2, PWR_WAKEUP_PIN3, PWR_WAKEUP_PIN4, PWR_WAKEUP_PIN5 * @retval None */ void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) { assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); CLEAR_BIT(PWR->CR3, (PWR_CR3_EWUP & WakeUpPinx)); } /** * @brief Enter Sleep or Low-power Sleep mode. * @note In Sleep/Low-power Sleep mode, all I/O pins keep the same state as in Run mode. * @param Regulator: Specifies the regulator state in Sleep/Low-power Sleep mode. * This parameter can be one of the following values: * @arg @ref PWR_MAINREGULATOR_ON Sleep mode (regulator in main mode) * @arg @ref PWR_LOWPOWERREGULATOR_ON Low-power Sleep mode (regulator in low-power mode) * @note Low-power Sleep mode is entered from Low-power Run mode. Therefore, if not yet * in Low-power Run mode before calling HAL_PWR_EnterSLEEPMode() with Regulator set * to PWR_LOWPOWERREGULATOR_ON, the user can optionally configure the * Flash in power-down monde in setting the SLEEP_PD bit in FLASH_ACR register. * Additionally, the clock frequency must be reduced below 2 MHz. * Setting SLEEP_PD in FLASH_ACR then appropriately reducing the clock frequency must * be done before calling HAL_PWR_EnterSLEEPMode() API. * @note When exiting Low-power Sleep mode, the MCU is in Low-power Run mode. To move in * Run mode, the user must resort to HAL_PWREx_DisableLowPowerRunMode() API. * @param SLEEPEntry: Specifies if Sleep mode is entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg @ref PWR_SLEEPENTRY_WFI enter Sleep or Low-power Sleep mode with WFI instruction * @arg @ref PWR_SLEEPENTRY_WFE enter Sleep or Low-power Sleep mode with WFE instruction * @note When WFI entry is used, tick interrupt have to be disabled if not desired as * the interrupt wake up source. * @retval None */ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) { /* Check the parameters */ assert_param(IS_PWR_REGULATOR(Regulator)); assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); /* Set Regulator parameter */ if (Regulator == PWR_MAINREGULATOR_ON) { /* If in low-power run mode at this point, exit it */ if (HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_REGLPF)) { (void)HAL_PWREx_DisableLowPowerRunMode(); } /* Regulator now in main mode. */ } else { /* If in run mode, first move to low-power run mode. The system clock frequency must be below 2 MHz at this point. */ if (HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_REGLPF) == 0U) { HAL_PWREx_EnableLowPowerRunMode(); } } /* Clear SLEEPDEEP bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* Select SLEEP mode entry -------------------------------------------------*/ if(SLEEPEntry == PWR_SLEEPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } } /** * @brief Enter Stop mode * @note This API is named HAL_PWR_EnterSTOPMode to ensure compatibility with legacy code running * on devices where only "Stop mode" is mentioned with main or low power regulator ON. * @note In Stop mode, all I/O pins keep the same state as in Run mode. * @note All clocks in the VCORE domain are stopped; the PLL, * the HSI and the HSE oscillators are disabled. Some peripherals with the wakeup capability * (I2Cx, USARTx and LPUART) can switch on the HSI to receive a frame, and switch off the HSI * after receiving the frame if it is not a wakeup frame. In this case, the HSI clock is propagated * only to the peripheral requesting it. * SRAM1, SRAM2 and register contents are preserved. * The BOR is available. * The voltage regulator can be configured either in normal (Stop 0) or low-power mode (Stop 1). * @note When exiting Stop 0 or Stop 1 mode by issuing an interrupt or a wakeup event, * the HSI RC oscillator is selected as system clock. * @note When the voltage regulator operates in low power mode (Stop 1), an additional * startup delay is incurred when waking up. * By keeping the internal regulator ON during Stop mode (Stop 0), the consumption * is higher although the startup time is reduced. * @param Regulator: Specifies the regulator state in Stop mode. * This parameter can be one of the following values: * @arg @ref PWR_MAINREGULATOR_ON Stop 0 mode (main regulator ON) * @arg @ref PWR_LOWPOWERREGULATOR_ON Stop 1 mode (low power regulator ON) * @param STOPEntry: Specifies Stop 0 or Stop 1 mode is entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg @ref PWR_STOPENTRY_WFI Enter Stop 0 or Stop 1 mode with WFI instruction. * @arg @ref PWR_STOPENTRY_WFE Enter Stop 0 or Stop 1 mode with WFE instruction. * @retval None */ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) { /* Check the parameters */ assert_param(IS_PWR_REGULATOR(Regulator)); if(Regulator == PWR_LOWPOWERREGULATOR_ON) { HAL_PWREx_EnterSTOP1Mode(STOPEntry); } else { HAL_PWREx_EnterSTOP0Mode(STOPEntry); } } /** * @brief Enter Standby mode. * @note In Standby mode, the PLL, the HSI and the HSE oscillators are switched * off. The voltage regulator is disabled, except when SRAM2 content is preserved * in which case the regulator is in low-power mode. * SRAM1 and register contents are lost except for registers in the Backup domain and * Standby circuitry. SRAM2 content can be preserved if the bit RRS is set in PWR_CR3 register. * To enable this feature, the user can resort to HAL_PWREx_EnableSRAM2ContentRetention() API * to set RRS bit. * The BOR is available. * @note The I/Os can be configured either with a pull-up or pull-down or can be kept in analog state. * HAL_PWREx_EnableGPIOPullUp() and HAL_PWREx_EnableGPIOPullDown() respectively enable Pull Up and * Pull Down state, HAL_PWREx_DisableGPIOPullUp() and HAL_PWREx_DisableGPIOPullDown() disable the * same. * These states are effective in Standby mode only if APC bit is set through * HAL_PWREx_EnablePullUpPullDownConfig() API. * @retval None */ void HAL_PWR_EnterSTANDBYMode(void) { /* Set Stand-by mode */ MODIFY_REG(PWR->CR1, PWR_CR1_LPMS, PWR_CR1_LPMS_STANDBY); /* Set SLEEPDEEP bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* This option is used to ensure that store operations are completed */ #if defined ( __CC_ARM) __force_stores(); #endif /* Request Wait For Interrupt */ __WFI(); } /** * @brief Indicate Sleep-On-Exit when returning from Handler mode to Thread mode. * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the processor * re-enters SLEEP mode when an interruption handling is over. * Setting this bit is useful when the processor is expected to run only on * interruptions handling. * @retval None */ void HAL_PWR_EnableSleepOnExit(void) { /* Set SLEEPONEXIT bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); } /** * @brief Disable Sleep-On-Exit feature when returning from Handler mode to Thread mode. * @note Clear SLEEPONEXIT bit of SCR register. When this bit is set, the processor * re-enters SLEEP mode when an interruption handling is over. * @retval None */ void HAL_PWR_DisableSleepOnExit(void) { /* Clear SLEEPONEXIT bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); } /** * @brief Enable CORTEX M4 SEVONPEND bit. * @note Set SEVONPEND bit of SCR register. When this bit is set, this causes * WFE to wake up when an interrupt moves from inactive to pended. * @retval None */ void HAL_PWR_EnableSEVOnPend(void) { /* Set SEVONPEND bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); } /** * @brief Disable CORTEX M4 SEVONPEND bit. * @note Clear SEVONPEND bit of SCR register. When this bit is set, this causes * WFE to wake up when an interrupt moves from inactive to pended. * @retval None */ void HAL_PWR_DisableSEVOnPend(void) { /* Clear SEVONPEND bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); } /** * @brief PWR PVD interrupt callback * @retval None */ __weak void HAL_PWR_PVDCallback(void) { /* NOTE : This function should not be modified; when the callback is needed, the HAL_PWR_PVDCallback can be implemented in the user file */ } /** * @} */ /** * @} */ #endif /* HAL_PWR_MODULE_ENABLED */ /** * @} */ /** * @} */
24,463
C
36.464012
146
0.625107
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_uart_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_uart_ex.c * @author MCD Application Team * @brief Extended UART HAL module driver. * This file provides firmware functions to manage the following extended * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). * + Initialization and de-initialization functions * + Peripheral Control functions * * ****************************************************************************** * @attention * * Copyright (c) 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 ============================================================================== ##### UART peripheral extended features ##### ============================================================================== (#) Declare a UART_HandleTypeDef handle structure. (#) For the UART RS485 Driver Enable mode, initialize the UART registers by calling the HAL_RS485Ex_Init() API. (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. -@- When UART operates in FIFO mode, FIFO mode must be enabled prior starting RX/TX transfers. Also RX/TX FIFO thresholds must be configured prior starting RX/TX transfers. @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup UARTEx UARTEx * @brief UART Extended HAL module driver * @{ */ #ifdef HAL_UART_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup UARTEX_Private_Constants UARTEx Private Constants * @{ */ /* UART RX FIFO depth */ #define RX_FIFO_DEPTH 8U /* UART TX FIFO depth */ #define TX_FIFO_DEPTH 8U /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup UARTEx_Private_Functions UARTEx Private Functions * @{ */ static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup UARTEx_Exported_Functions UARTEx Exported Functions * @{ */ /** @defgroup UARTEx_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Extended Initialization and Configuration Functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to initialize the USARTx or the UARTy in asynchronous mode. (+) For the asynchronous mode the parameters below can be configured: (++) Baud Rate (++) Word Length (++) Stop Bit (++) Parity: If the parity is enabled, then the MSB bit of the data written in the data register is transmitted but is changed by the parity bit. (++) Hardware flow control (++) Receiver/transmitter modes (++) Over Sampling Method (++) One-Bit Sampling Method (+) For the asynchronous mode, the following advanced features can be configured as well: (++) TX and/or RX pin level inversion (++) data logical level inversion (++) RX and TX pins swap (++) RX overrun detection disabling (++) DMA disabling on RX error (++) MSB first on communication line (++) auto Baud rate detection [..] The HAL_RS485Ex_Init() API follows the UART RS485 mode configuration procedures (details for the procedures are available in reference manual). @endverbatim Depending on the frame length defined by the M1 and M0 bits (7-bit, 8-bit or 9-bit), the possible UART formats are listed in the following table. Table 1. UART frame format. +-----------------------------------------------------------------------+ | M1 bit | M0 bit | PCE bit | UART frame | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 0 | | SB | 8 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 0 | | SB | 9 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 0 | | SB | 7 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | +-----------------------------------------------------------------------+ * @{ */ /** * @brief Initialize the RS485 Driver enable feature according to the specified * parameters in the UART_InitTypeDef and creates the associated handle. * @param huart UART handle. * @param Polarity Select the driver enable polarity. * This parameter can be one of the following values: * @arg @ref UART_DE_POLARITY_HIGH DE signal is active high * @arg @ref UART_DE_POLARITY_LOW DE signal is active low * @param AssertionTime Driver Enable assertion time: * 5-bit value defining the time between the activation of the DE (Driver Enable) * signal and the beginning of the start bit. It is expressed in sample time * units (1/8 or 1/16 bit time, depending on the oversampling rate) * @param DeassertionTime Driver Enable deassertion time: * 5-bit value defining the time between the end of the last stop bit, in a * transmitted message, and the de-activation of the DE (Driver Enable) signal. * It is expressed in sample time units (1/8 or 1/16 bit time, depending on the * oversampling rate). * @retval HAL status */ HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, uint32_t DeassertionTime) { uint32_t temp; /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check the Driver Enable UART instance */ assert_param(IS_UART_DRIVER_ENABLE_INSTANCE(huart->Instance)); /* Check the Driver Enable polarity */ assert_param(IS_UART_DE_POLARITY(Polarity)); /* Check the Driver Enable assertion time */ assert_param(IS_UART_ASSERTIONTIME(AssertionTime)); /* Check the Driver Enable deassertion time */ assert_param(IS_UART_DEASSERTIONTIME(DeassertionTime)); if (huart->gState == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) UART_InitCallbacksToDefault(huart); if (huart->MspInitCallback == NULL) { huart->MspInitCallback = HAL_UART_MspInit; } /* Init the low level hardware */ huart->MspInitCallback(huart); #else /* Init the low level hardware : GPIO, CLOCK, CORTEX */ HAL_UART_MspInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } huart->gState = HAL_UART_STATE_BUSY; /* Disable the Peripheral */ __HAL_UART_DISABLE(huart); /* Set the UART Communication parameters */ if (UART_SetConfig(huart) == HAL_ERROR) { return HAL_ERROR; } if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) { UART_AdvFeatureConfig(huart); } /* Enable the Driver Enable mode by setting the DEM bit in the CR3 register */ SET_BIT(huart->Instance->CR3, USART_CR3_DEM); /* Set the Driver Enable polarity */ MODIFY_REG(huart->Instance->CR3, USART_CR3_DEP, Polarity); /* Set the Driver Enable assertion and deassertion times */ temp = (AssertionTime << UART_CR1_DEAT_ADDRESS_LSB_POS); temp |= (DeassertionTime << UART_CR1_DEDT_ADDRESS_LSB_POS); MODIFY_REG(huart->Instance->CR1, (USART_CR1_DEDT | USART_CR1_DEAT), temp); /* Enable the Peripheral */ __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ return (UART_CheckIdleState(huart)); } /** * @} */ /** @defgroup UARTEx_Exported_Functions_Group2 IO operation functions * @brief Extended functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== This subsection provides a set of Wakeup and FIFO mode related callback functions. (#) Wakeup from Stop mode Callback: (+) HAL_UARTEx_WakeupCallback() (#) TX/RX Fifos Callbacks: (+) HAL_UARTEx_RxFifoFullCallback() (+) HAL_UARTEx_TxFifoEmptyCallback() @endverbatim * @{ */ /** * @brief UART wakeup from Stop mode callback. * @param huart UART handle. * @retval None */ __weak void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UARTEx_WakeupCallback can be implemented in the user file. */ } /** * @brief UART RX Fifo full callback. * @param huart UART handle. * @retval None */ __weak void HAL_UARTEx_RxFifoFullCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UARTEx_RxFifoFullCallback can be implemented in the user file. */ } /** * @brief UART TX Fifo empty callback. * @param huart UART handle. * @retval None */ __weak void HAL_UARTEx_TxFifoEmptyCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UARTEx_TxFifoEmptyCallback can be implemented in the user file. */ } /** * @} */ /** @defgroup UARTEx_Exported_Functions_Group3 Peripheral Control functions * @brief Extended Peripheral Control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides the following functions: (+) HAL_MultiProcessorEx_AddressLength_Set() API optionally sets the UART node address detection length to more than 4 bits for multiprocessor address mark wake up. (+) HAL_UARTEx_StopModeWakeUpSourceConfig() API defines the wake-up from stop mode trigger: address match, Start Bit detection or RXNE bit status. (+) HAL_UARTEx_EnableStopMode() API enables the UART to wake up the MCU from stop mode (+) HAL_UARTEx_DisableStopMode() API disables the above functionality (+) HAL_UARTEx_EnableFifoMode() API enables the FIFO mode (+) HAL_UARTEx_DisableFifoMode() API disables the FIFO mode (+) HAL_UARTEx_SetTxFifoThreshold() API sets the TX FIFO threshold (+) HAL_UARTEx_SetRxFifoThreshold() API sets the RX FIFO threshold [..] This subsection also provides a set of additional functions providing enhanced reception services to user. (For example, these functions allow application to handle use cases where number of data to be received is unknown). (#) Compared to standard reception services which only consider number of received data elements as reception completion criteria, these functions also consider additional events as triggers for updating reception status to caller : (+) Detection of inactivity period (RX line has not been active for a given period). (++) RX inactivity detected by IDLE event, i.e. RX line has been in idle state (normally high state) for 1 frame time, after last received byte. (++) RX inactivity detected by RTO, i.e. line has been in idle state for a programmable time, after last received byte. (+) Detection that a specific character has been received. (#) There are two mode of transfer: (+) Blocking mode: The reception is performed in polling mode, until either expected number of data is received, or till IDLE event occurs. Reception is handled only during function execution. When function exits, no data reception could occur. HAL status and number of actually received data elements, are returned by function after finishing transfer. (+) Non-Blocking mode: The reception is performed using Interrupts or DMA. These API's return the HAL status. The end of the data processing will be indicated through the dedicated UART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. The HAL_UARTEx_RxEventCallback() user callback will be executed during Receive process The HAL_UART_ErrorCallback()user callback will be executed when a reception error is detected. (#) Blocking mode API: (+) HAL_UARTEx_ReceiveToIdle() (#) Non-Blocking mode API with Interrupt: (+) HAL_UARTEx_ReceiveToIdle_IT() (#) Non-Blocking mode API with DMA: (+) HAL_UARTEx_ReceiveToIdle_DMA() @endverbatim * @{ */ /** * @brief By default in multiprocessor mode, when the wake up method is set * to address mark, the UART handles only 4-bit long addresses detection; * this API allows to enable longer addresses detection (6-, 7- or 8-bit * long). * @note Addresses detection lengths are: 6-bit address detection in 7-bit data mode, * 7-bit address detection in 8-bit data mode, 8-bit address detection in 9-bit data mode. * @param huart UART handle. * @param AddressLength This parameter can be one of the following values: * @arg @ref UART_ADDRESS_DETECT_4B 4-bit long address * @arg @ref UART_ADDRESS_DETECT_7B 6-, 7- or 8-bit long address * @retval HAL status */ HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check the address length parameter */ assert_param(IS_UART_ADDRESSLENGTH_DETECT(AddressLength)); huart->gState = HAL_UART_STATE_BUSY; /* Disable the Peripheral */ __HAL_UART_DISABLE(huart); /* Set the address length */ MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, AddressLength); /* Enable the Peripheral */ __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState to Ready */ return (UART_CheckIdleState(huart)); } /** * @brief Set Wakeup from Stop mode interrupt flag selection. * @note It is the application responsibility to enable the interrupt used as * usart_wkup interrupt source before entering low-power mode. * @param huart UART handle. * @param WakeUpSelection Address match, Start Bit detection or RXNE/RXFNE bit status. * This parameter can be one of the following values: * @arg @ref UART_WAKEUP_ON_ADDRESS * @arg @ref UART_WAKEUP_ON_STARTBIT * @arg @ref UART_WAKEUP_ON_READDATA_NONEMPTY * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) { HAL_StatusTypeDef status = HAL_OK; uint32_t tickstart; /* check the wake-up from stop mode UART instance */ assert_param(IS_UART_WAKEUP_FROMSTOP_INSTANCE(huart->Instance)); /* check the wake-up selection parameter */ assert_param(IS_UART_WAKEUP_SELECTION(WakeUpSelection.WakeUpEvent)); /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Disable the Peripheral */ __HAL_UART_DISABLE(huart); /* Set the wake-up selection scheme */ MODIFY_REG(huart->Instance->CR3, USART_CR3_WUS, WakeUpSelection.WakeUpEvent); if (WakeUpSelection.WakeUpEvent == UART_WAKEUP_ON_ADDRESS) { UARTEx_Wakeup_AddressConfig(huart, WakeUpSelection); } /* Enable the Peripheral */ __HAL_UART_ENABLE(huart); /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); /* Wait until REACK flag is set */ if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) { status = HAL_TIMEOUT; } else { /* Initialize the UART State */ huart->gState = HAL_UART_STATE_READY; } /* Process Unlocked */ __HAL_UNLOCK(huart); return status; } /** * @brief Enable UART Stop Mode. * @note The UART is able to wake up the MCU from Stop 1 mode as long as UART clock is HSI or LSE. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart) { /* Process Locked */ __HAL_LOCK(huart); /* Set UESM bit */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_UESM); /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Disable UART Stop Mode. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart) { /* Process Locked */ __HAL_LOCK(huart); /* Clear UESM bit */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_UESM); /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Enable the FIFO mode. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_EnableFifoMode(UART_HandleTypeDef *huart) { uint32_t tmpcr1; /* Check parameters */ assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Save actual UART configuration */ tmpcr1 = READ_REG(huart->Instance->CR1); /* Disable UART */ __HAL_UART_DISABLE(huart); /* Enable FIFO mode */ SET_BIT(tmpcr1, USART_CR1_FIFOEN); huart->FifoMode = UART_FIFOMODE_ENABLE; /* Restore UART configuration */ WRITE_REG(huart->Instance->CR1, tmpcr1); /* Determine the number of data to process during RX/TX ISR execution */ UARTEx_SetNbDataToProcess(huart); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Disable the FIFO mode. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) { uint32_t tmpcr1; /* Check parameters */ assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Save actual UART configuration */ tmpcr1 = READ_REG(huart->Instance->CR1); /* Disable UART */ __HAL_UART_DISABLE(huart); /* Enable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); huart->FifoMode = UART_FIFOMODE_DISABLE; /* Restore UART configuration */ WRITE_REG(huart->Instance->CR1, tmpcr1); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Set the TXFIFO threshold. * @param huart UART handle. * @param Threshold TX FIFO threshold value * This parameter can be one of the following values: * @arg @ref UART_TXFIFO_THRESHOLD_1_8 * @arg @ref UART_TXFIFO_THRESHOLD_1_4 * @arg @ref UART_TXFIFO_THRESHOLD_1_2 * @arg @ref UART_TXFIFO_THRESHOLD_3_4 * @arg @ref UART_TXFIFO_THRESHOLD_7_8 * @arg @ref UART_TXFIFO_THRESHOLD_8_8 * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_SetTxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) { uint32_t tmpcr1; /* Check parameters */ assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); assert_param(IS_UART_TXFIFO_THRESHOLD(Threshold)); /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Save actual UART configuration */ tmpcr1 = READ_REG(huart->Instance->CR1); /* Disable UART */ __HAL_UART_DISABLE(huart); /* Update TX threshold configuration */ MODIFY_REG(huart->Instance->CR3, USART_CR3_TXFTCFG, Threshold); /* Determine the number of data to process during RX/TX ISR execution */ UARTEx_SetNbDataToProcess(huart); /* Restore UART configuration */ WRITE_REG(huart->Instance->CR1, tmpcr1); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Set the RXFIFO threshold. * @param huart UART handle. * @param Threshold RX FIFO threshold value * This parameter can be one of the following values: * @arg @ref UART_RXFIFO_THRESHOLD_1_8 * @arg @ref UART_RXFIFO_THRESHOLD_1_4 * @arg @ref UART_RXFIFO_THRESHOLD_1_2 * @arg @ref UART_RXFIFO_THRESHOLD_3_4 * @arg @ref UART_RXFIFO_THRESHOLD_7_8 * @arg @ref UART_RXFIFO_THRESHOLD_8_8 * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_SetRxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) { uint32_t tmpcr1; /* Check the parameters */ assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); assert_param(IS_UART_RXFIFO_THRESHOLD(Threshold)); /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Save actual UART configuration */ tmpcr1 = READ_REG(huart->Instance->CR1); /* Disable UART */ __HAL_UART_DISABLE(huart); /* Update RX threshold configuration */ MODIFY_REG(huart->Instance->CR3, USART_CR3_RXFTCFG, Threshold); /* Determine the number of data to process during RX/TX ISR execution */ UARTEx_SetNbDataToProcess(huart); /* Restore UART configuration */ WRITE_REG(huart->Instance->CR1, tmpcr1); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Receive an amount of data in blocking mode till either the expected number of data * is received or an IDLE event occurs. * @note HAL_OK is returned if reception is completed (expected number of data has been received) * or if reception is stopped after IDLE event (less than the expected number of data has been received) * In this case, RxLen output parameter indicates number of data available in reception buffer. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of uint16_t. In this case, Size must indicate the number * of uint16_t available through pData. * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO * is not empty. Read operations from the RDR register are performed when * RXFNE flag is set. From hardware perspective, RXFNE flag and * RXNE are mapped on the same bit-field. * @param huart UART handle. * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). * @param Size Amount of data elements (uint8_t or uint16_t) to be received. * @param RxLen Number of data elements finally received * (could be lower than Size, in case reception ends on IDLE event) * @param Timeout Timeout duration expressed in ms (covers the whole reception sequence). * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, uint32_t Timeout) { uint8_t *pdata8bits; uint16_t *pdata16bits; uint16_t uhMask; uint32_t tickstart; /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; huart->RxState = HAL_UART_STATE_BUSY_RX; huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); huart->RxXferSize = Size; huart->RxXferCount = Size; /* Computation of UART mask to apply to RDR register */ UART_MASK_COMPUTATION(huart); uhMask = huart->Mask; /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { pdata8bits = NULL; pdata16bits = (uint16_t *) pData; } else { pdata8bits = pData; pdata16bits = NULL; } __HAL_UNLOCK(huart); /* Initialize output number of received elements */ *RxLen = 0U; /* as long as data have to be received */ while (huart->RxXferCount > 0U) { /* Check if IDLE flag is set */ if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) { /* Clear IDLE flag in ISR */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); /* If Set, but no data ever received, clear flag without exiting loop */ /* If Set, and data has already been received, this means Idle Event is valid : End reception */ if (*RxLen > 0U) { huart->RxState = HAL_UART_STATE_READY; return HAL_OK; } } /* Check if RXNE flag is set */ if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE)) { if (pdata8bits == NULL) { *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); pdata16bits++; } else { *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); pdata8bits++; } /* Increment number of received elements */ *RxLen += 1U; huart->RxXferCount--; } /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) { huart->RxState = HAL_UART_STATE_READY; return HAL_TIMEOUT; } } } /* Set number of received elements in output parameter : RxLen */ *RxLen = huart->RxXferSize - huart->RxXferCount; /* At end of Rx process, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in interrupt mode till either the expected number of data * is received or an IDLE event occurs. * @note Reception is initiated by this function call. Further progress of reception is achieved thanks * to UART interrupts raised by RXNE and IDLE events. Callback is called at end of reception indicating * number of received data elements. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of uint16_t. In this case, Size must indicate the number * of uint16_t available through pData. * @param huart UART handle. * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). * @param Size Amount of data elements (uint8_t or uint16_t) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { HAL_StatusTypeDef status; /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); /* Set Reception type to reception till IDLE Event*/ huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; status = UART_Start_Receive_IT(huart, pData, Size); /* Check Rx process has been successfully started */ if (status == HAL_OK) { if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); } else { /* In case of errors already pending when reception is started, Interrupts may have already been raised and lead to reception abortion. (Overrun error for instance). In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ status = HAL_ERROR; } } return status; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in DMA mode till either the expected number * of data is received or an IDLE event occurs. * @note Reception is initiated by this function call. Further progress of reception is achieved thanks * to DMA services, transferring automatically received data elements in user reception buffer and * calling registered callbacks at half/end of reception. UART IDLE events are also used to consider * reception phase as ended. In all cases, callback execution will indicate number of received data elements. * @note When the UART parity is enabled (PCE = 1), the received data contain * the parity bit (MSB position). * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of uint16_t. In this case, Size must indicate the number * of uint16_t available through pData. * @param huart UART handle. * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). * @param Size Amount of data elements (uint8_t or uint16_t) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { HAL_StatusTypeDef status; /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); /* Set Reception type to reception till IDLE Event*/ huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; status = UART_Start_Receive_DMA(huart, pData, Size); /* Check Rx process has been successfully started */ if (status == HAL_OK) { if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); } else { /* In case of errors already pending when reception is started, Interrupts may have already been raised and lead to reception abortion. (Overrun error for instance). In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ status = HAL_ERROR; } } return status; } else { return HAL_BUSY; } } /** * @} */ /** * @} */ /** @addtogroup UARTEx_Private_Functions * @{ */ /** * @brief Initialize the UART wake-up from stop mode parameters when triggered by address detection. * @param huart UART handle. * @param WakeUpSelection UART wake up from stop mode parameters. * @retval None */ static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) { assert_param(IS_UART_ADDRESSLENGTH_DETECT(WakeUpSelection.AddressLength)); /* Set the USART address length */ MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, WakeUpSelection.AddressLength); /* Set the USART address node */ MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)WakeUpSelection.Address << UART_CR2_ADDRESS_LSB_POS)); } /** * @brief Calculate the number of data to process in RX/TX ISR. * @note The RX FIFO depth and the TX FIFO depth is extracted from * the UART configuration registers. * @param huart UART handle. * @retval None */ static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart) { uint8_t rx_fifo_depth; uint8_t tx_fifo_depth; uint8_t rx_fifo_threshold; uint8_t tx_fifo_threshold; static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; if (huart->FifoMode == UART_FIFOMODE_DISABLE) { huart->NbTxDataToProcess = 1U; huart->NbRxDataToProcess = 1U; } else { rx_fifo_depth = RX_FIFO_DEPTH; tx_fifo_depth = TX_FIFO_DEPTH; rx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos); tx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos); huart->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / (uint16_t)denominator[tx_fifo_threshold]; huart->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / (uint16_t)denominator[rx_fifo_threshold]; } } /** * @} */ #endif /* HAL_UART_MODULE_ENABLED */ /** * @} */ /** * @} */
34,412
C
32.771344
120
0.615657
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_hal_flash_ramfunc.c
/** ****************************************************************************** * @file stm32g4xx_hal_flash_ramfunc.c * @author MCD Application Team * @brief FLASH RAMFUNC driver. * This file provides a Flash firmware functions which should be * executed from internal SRAM * + FLASH Power Down in Run mode * + FLASH DBANK User Option Byte * * @verbatim ============================================================================== ##### Flash RAM functions ##### ============================================================================== *** ARM Compiler *** -------------------- [..] RAM functions are defined using the toolchain options. Functions that are executed in RAM should reside in a separate source module. Using the 'Options for File' dialog you can simply change the 'Code / Const' area of a module to a memory space in physical RAM. Available memory areas are declared in the 'Target' tab of the Options for Target' dialog. *** ICCARM Compiler *** ----------------------- [..] RAM functions are defined using a specific toolchain keyword "__ramfunc". *** GNU Compiler *** -------------------- [..] RAM functions are defined using a specific toolchain attribute "__attribute__((section(".RamFunc")))". @endverbatim ****************************************************************************** * @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 FLASH_RAMFUNC FLASH_RAMFUNC * @brief FLASH functions executed from RAM * @{ */ #ifdef HAL_FLASH_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions -------------------------------------------------------*/ /** @defgroup FLASH_RAMFUNC_Exported_Functions FLASH_RAMFUNC Exported Functions * @{ */ /** @defgroup FLASH_RAMFUNC_Exported_Functions_Group1 Peripheral features functions * @brief Data transfers functions * @verbatim =============================================================================== ##### ramfunc functions ##### =============================================================================== [..] This subsection provides a set of functions that should be executed from RAM. @endverbatim * @{ */ /** * @brief Enable the Power down in Run Mode * @note This function should be called and executed from SRAM memory. * @retval None */ __RAM_FUNC HAL_StatusTypeDef HAL_FLASHEx_EnableRunPowerDown(void) { /* Enable the Power Down in Run mode*/ __HAL_FLASH_POWER_DOWN_ENABLE(); return HAL_OK; } /** * @brief Disable the Power down in Run Mode * @note This function should be called and executed from SRAM memory. * @retval None */ __RAM_FUNC HAL_StatusTypeDef HAL_FLASHEx_DisableRunPowerDown(void) { /* Disable the Power Down in Run mode*/ __HAL_FLASH_POWER_DOWN_DISABLE(); return HAL_OK; } #if defined (FLASH_OPTR_DBANK) /** * @brief Program the FLASH DBANK User Option Byte. * * @note To configure the user option bytes, the option lock bit OPTLOCK must * be cleared with the call of the HAL_FLASH_OB_Unlock() function. * @note To modify the DBANK option byte, no PCROP region should be defined. * To deactivate PCROP, user should perform RDP changing. * * @param DBankConfig The FLASH DBANK User Option Byte value. * This parameter can be one of the following values: * @arg OB_DBANK_128_BITS: Single-bank with 128-bits data * @arg OB_DBANK_64_BITS: Dual-bank with 64-bits data * * @retval HAL_Status */ __RAM_FUNC HAL_StatusTypeDef HAL_FLASHEx_OB_DBankConfig(uint32_t DBankConfig) { uint32_t count, reg; HAL_StatusTypeDef status = HAL_ERROR; /* Process Locked */ __HAL_LOCK(&pFlash); /* Check if the PCROP is disabled */ reg = FLASH->PCROP1SR; if (reg > FLASH->PCROP1ER) { reg = FLASH->PCROP2SR; if (reg > FLASH->PCROP2ER) { /* Disable Flash prefetch */ __HAL_FLASH_PREFETCH_BUFFER_DISABLE(); if (READ_BIT(FLASH->ACR, FLASH_ACR_ICEN) != 0U) { /* Disable Flash instruction cache */ __HAL_FLASH_INSTRUCTION_CACHE_DISABLE(); /* Flush Flash instruction cache */ __HAL_FLASH_INSTRUCTION_CACHE_RESET(); } if (READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) != 0U) { /* Disable Flash data cache */ __HAL_FLASH_DATA_CACHE_DISABLE(); /* Flush Flash data cache */ __HAL_FLASH_DATA_CACHE_RESET(); } /* Disable WRP zone A of 1st bank if needed */ reg = FLASH->WRP1AR; if (((reg & FLASH_WRP1AR_WRP1A_STRT) >> FLASH_WRP1AR_WRP1A_STRT_Pos) <= ((reg & FLASH_WRP1AR_WRP1A_END) >> FLASH_WRP1AR_WRP1A_END_Pos)) { MODIFY_REG(FLASH->WRP1AR, (FLASH_WRP1AR_WRP1A_STRT | FLASH_WRP1AR_WRP1A_END), FLASH_WRP1AR_WRP1A_STRT); } /* Disable WRP zone B of 1st bank if needed */ reg = FLASH->WRP1BR; if (((reg & FLASH_WRP1BR_WRP1B_STRT) >> FLASH_WRP1BR_WRP1B_STRT_Pos) <= ((reg & FLASH_WRP1BR_WRP1B_END) >> FLASH_WRP1BR_WRP1B_END_Pos)) { MODIFY_REG(FLASH->WRP1BR, (FLASH_WRP1BR_WRP1B_STRT | FLASH_WRP1BR_WRP1B_END), FLASH_WRP1BR_WRP1B_STRT); } /* Disable WRP zone A of 2nd bank if needed */ reg = FLASH->WRP2AR; if (((reg & FLASH_WRP2AR_WRP2A_STRT) >> FLASH_WRP2AR_WRP2A_STRT_Pos) <= ((reg & FLASH_WRP2AR_WRP2A_END) >> FLASH_WRP2AR_WRP2A_END_Pos)) { MODIFY_REG(FLASH->WRP2AR, (FLASH_WRP2AR_WRP2A_STRT | FLASH_WRP2AR_WRP2A_END), FLASH_WRP2AR_WRP2A_STRT); } /* Disable WRP zone B of 2nd bank if needed */ reg = FLASH->WRP2BR; if (((reg & FLASH_WRP2BR_WRP2B_STRT) >> FLASH_WRP2BR_WRP2B_STRT_Pos) <= ((reg & FLASH_WRP2BR_WRP2B_END) >> FLASH_WRP2BR_WRP2B_END_Pos)) { MODIFY_REG(FLASH->WRP2BR, (FLASH_WRP2BR_WRP2B_STRT | FLASH_WRP2BR_WRP2B_END), FLASH_WRP2BR_WRP2B_STRT); } /* Modify the DBANK user option byte */ MODIFY_REG(FLASH->OPTR, FLASH_OPTR_DBANK, DBankConfig); /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ /* 8 is the number of required instruction cycles for the below loop statement (timeout expressed in ms) */ count = FLASH_TIMEOUT_VALUE * (SystemCoreClock / 8U / 1000U); do { if (count == 0U) { break; } count--; } while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET); /* If the option byte program operation is completed, disable the OPTSTRT Bit */ CLEAR_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Set the bit to force the option byte reloading */ SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH); } } /* Process Unlocked */ __HAL_UNLOCK(&pFlash); return status; } #endif /** * @} */ /** * @} */ #endif /* HAL_FLASH_MODULE_ENABLED */ /** * @} */ /** * @} */
7,937
C
30.251968
113
0.536979
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_gpio.c
/** ****************************************************************************** * @file stm32g4xx_hal_gpio.c * @author MCD Application Team * @brief GPIO HAL module driver. * This file provides firmware functions to manage the following * functionalities of the General Purpose Input/Output (GPIO) peripheral: * + Initialization and de-initialization functions * + IO operation functions * ****************************************************************************** * @attention * * Copyright (c) 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 ============================================================================== ##### GPIO Peripheral features ##### ============================================================================== [..] (+) Each port bit of the general-purpose I/O (GPIO) ports can be individually configured by software in several modes: (++) Input mode (++) Analog mode (++) Output mode (++) Alternate function mode (++) External interrupt/event lines (+) During and just after reset, the alternate functions and external interrupt lines are not active and the I/O ports are configured in input floating mode. (+) All GPIO pins have weak internal pull-up and pull-down resistors, which can be activated or not. (+) In Output or Alternate mode, each IO can be configured on open-drain or push-pull type and the IO speed can be selected depending on the VDD value. (+) The microcontroller IO pins are connected to onboard peripherals/modules through a multiplexer that allows only one peripheral alternate function (AF) connected to an IO pin at a time. In this way, there can be no conflict between peripherals sharing the same IO pin. (+) All ports have external interrupt/event capability. To use external interrupt lines, the port must be configured in input mode. All available GPIO pins are connected to the 16 external interrupt/event lines from EXTI0 to EXTI15. (+) The external interrupt/event controller consists of up to 44 edge detectors (16 lines are connected to GPIO) for generating event/interrupt requests (each input line can be independently configured to select the type (interrupt or event) and the corresponding trigger event (rising or falling or both). Each line can also be masked independently. ##### How to use this driver ##### ============================================================================== [..] (#) Enable the GPIO AHB clock using the following function: __HAL_RCC_GPIOx_CLK_ENABLE(). (#) Configure the GPIO pin(s) using HAL_GPIO_Init(). (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef structure. (++) In case of Output or alternate function mode selection: the speed is configured through "Speed" member from GPIO_InitTypeDef structure. (++) In alternate mode is selection, the alternate function connected to the IO is configured through "Alternate" member from GPIO_InitTypeDef structure. (++) Analog mode is required when a pin is to be used as ADC channel or DAC output. (++) In case of external interrupt/event selection the "Mode" member from GPIO_InitTypeDef structure select the type (interrupt or event) and the corresponding trigger event (rising or falling or both). (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using HAL_NVIC_EnableIRQ(). (#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin(). (#) To set/reset the level of a pin configured in output mode use HAL_GPIO_WritePin()/HAL_GPIO_TogglePin(). (#) To lock pin configuration until next reset use HAL_GPIO_LockPin(). (#) During and just after reset, the alternate functions are not active and the GPIO pins are configured in input floating mode (except JTAG pins). (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has priority over the GPIO function. (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as general purpose PF0 and PF1, respectively, when the HSE oscillator is off. The HSE has priority over the GPIO function. @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup GPIO * @{ */ /** MISRA C:2012 deviation rule has been granted for following rules: * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of * range of the shift operator in following API : * HAL_GPIO_Init * HAL_GPIO_DeInit */ #ifdef HAL_GPIO_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /** @addtogroup GPIO_Private_Constants GPIO Private Constants * @{ */ #define GPIO_NUMBER (16U) /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup GPIO_Exported_Functions * @{ */ /** @defgroup GPIO_Exported_Functions_Group1 Initialization/de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Initialize the GPIOx peripheral according to the specified parameters in the GPIO_Init. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Init pointer to a GPIO_InitTypeDef structure that contains * the configuration information for the specified GPIO peripheral. * @retval None */ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) { uint32_t position = 0x00U; uint32_t iocurrent; uint32_t temp; /* Check the parameters */ assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); /* Configure the port pins */ while (((GPIO_Init->Pin) >> position) != 0U) { /* Get current io position */ iocurrent = (GPIO_Init->Pin) & (1UL << position); if (iocurrent != 0x00u) { /*--------------------- GPIO Mode Configuration ------------------------*/ /* In case of Output or Alternate function mode selection */ if(((GPIO_Init->Mode & GPIO_MODE) == MODE_OUTPUT) || ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF)) { /* Check the Speed parameter */ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed)); /* Configure the IO Speed */ temp = GPIOx->OSPEEDR; temp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2U)); temp |= (GPIO_Init->Speed << (position * 2U)); GPIOx->OSPEEDR = temp; /* Configure the IO Output Type */ temp = GPIOx->OTYPER; temp &= ~(GPIO_OTYPER_OT0 << position) ; temp |= (((GPIO_Init->Mode & OUTPUT_TYPE) >> OUTPUT_TYPE_Pos) << position); GPIOx->OTYPER = temp; } if ((GPIO_Init->Mode & GPIO_MODE) != MODE_ANALOG) { /* Check the Pull parameter */ assert_param(IS_GPIO_PULL(GPIO_Init->Pull)); /* Activate the Pull-up or Pull down resistor for the current IO */ temp = GPIOx->PUPDR; temp &= ~(GPIO_PUPDR_PUPD0 << (position * 2U)); temp |= ((GPIO_Init->Pull) << (position * 2U)); GPIOx->PUPDR = temp; } /* In case of Alternate function mode selection */ if ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF) { /* Check the Alternate function parameters */ assert_param(IS_GPIO_AF_INSTANCE(GPIOx)); assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); /* Configure Alternate function mapped with the current IO */ temp = GPIOx->AFR[position >> 3U]; temp &= ~(0xFU << ((position & 0x07U) * 4U)); temp |= ((GPIO_Init->Alternate) << ((position & 0x07U) * 4U)); GPIOx->AFR[position >> 3U] = temp; } /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ temp = GPIOx->MODER; temp &= ~(GPIO_MODER_MODE0 << (position * 2U)); temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2U)); GPIOx->MODER = temp; /*--------------------- EXTI Mode Configuration ------------------------*/ /* Configure the External Interrupt or event for the current IO */ if ((GPIO_Init->Mode & EXTI_MODE) != 0x00u) { /* Enable SYSCFG Clock */ __HAL_RCC_SYSCFG_CLK_ENABLE(); temp = SYSCFG->EXTICR[position >> 2U]; temp &= ~(0x0FUL << (4U * (position & 0x03U))); temp |= (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U))); SYSCFG->EXTICR[position >> 2U] = temp; /* Clear Rising Falling edge configuration */ temp = EXTI->RTSR1; temp &= ~(iocurrent); if ((GPIO_Init->Mode & TRIGGER_RISING) != 0x00U) { temp |= iocurrent; } EXTI->RTSR1 = temp; temp = EXTI->FTSR1; temp &= ~(iocurrent); if ((GPIO_Init->Mode & TRIGGER_FALLING) != 0x00U) { temp |= iocurrent; } EXTI->FTSR1 = temp; temp = EXTI->EMR1; temp &= ~(iocurrent); if ((GPIO_Init->Mode & EXTI_EVT) != 0x00U) { temp |= iocurrent; } EXTI->EMR1 = temp; /* Clear EXTI line configuration */ temp = EXTI->IMR1; temp &= ~(iocurrent); if ((GPIO_Init->Mode & EXTI_IT) != 0x00U) { temp |= iocurrent; } EXTI->IMR1 = temp; } } position++; } } /** * @brief De-initialize the GPIOx peripheral registers to their default reset values. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the port bit to be written. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @retval None */ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) { uint32_t position = 0x00U; uint32_t iocurrent; uint32_t tmp; /* Check the parameters */ assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); assert_param(IS_GPIO_PIN(GPIO_Pin)); /* Configure the port pins */ while ((GPIO_Pin >> position) != 0U) { /* Get current io position */ iocurrent = (GPIO_Pin) & (1UL << position); if (iocurrent != 0x00u) { /*------------------------- EXTI Mode Configuration --------------------*/ /* Clear the External Interrupt or Event for the current IO */ tmp = SYSCFG->EXTICR[position >> 2U]; tmp &= (0x0FUL << (4U * (position & 0x03U))); if (tmp == (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U)))) { /* Clear EXTI line configuration */ EXTI->IMR1 &= ~(iocurrent); EXTI->EMR1 &= ~(iocurrent); /* Clear Rising Falling edge configuration */ EXTI->FTSR1 &= ~(iocurrent); EXTI->RTSR1 &= ~(iocurrent); tmp = 0x0FUL << (4U * (position & 0x03U)); SYSCFG->EXTICR[position >> 2U] &= ~tmp; } /*------------------------- GPIO Mode Configuration --------------------*/ /* Configure IO in Analog Mode */ GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * 2u)); /* Configure the default Alternate Function in current IO */ GPIOx->AFR[position >> 3u] &= ~(0xFu << ((position & 0x07u) * 4u)); /* Deactivate the Pull-up and Pull-down resistor for the current IO */ GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * 2u)); /* Configure the default value IO Output Type */ GPIOx->OTYPER &= ~(GPIO_OTYPER_OT0 << position); /* Configure the default value for IO Speed */ GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2u)); } position++; } } /** * @} */ /** @addtogroup GPIO_Exported_Functions_Group2 * @brief GPIO Read, Write, Toggle, Lock and EXTI management functions. * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Read the specified input port pin. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the port bit to read. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @retval The input port pin value. */ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { GPIO_PinState bitstatus; /* Check the parameters */ assert_param(IS_GPIO_PIN(GPIO_Pin)); if ((GPIOx->IDR & GPIO_Pin) != 0x00U) { bitstatus = GPIO_PIN_SET; } else { bitstatus = GPIO_PIN_RESET; } return bitstatus; } /** * @brief Set or clear the selected data port bit. * * @note This function uses GPIOx_BSRR and GPIOx_BRR registers to allow atomic read/modify * accesses. In this way, there is no risk of an IRQ occurring between * the read and the modify access. * * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the port bit to be written. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @param PinState specifies the value to be written to the selected bit. * This parameter can be one of the GPIO_PinState enum values: * @arg GPIO_PIN_RESET: to clear the port pin * @arg GPIO_PIN_SET: to set the port pin * @retval None */ void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) { /* Check the parameters */ assert_param(IS_GPIO_PIN(GPIO_Pin)); assert_param(IS_GPIO_PIN_ACTION(PinState)); if (PinState != GPIO_PIN_RESET) { GPIOx->BSRR = (uint32_t)GPIO_Pin; } else { GPIOx->BRR = (uint32_t)GPIO_Pin; } } /** * @brief Toggle the specified GPIO pin. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the pin to be toggled. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @retval None */ void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { uint32_t odr; /* Check the parameters */ assert_param(IS_GPIO_PIN(GPIO_Pin)); /* get current Output Data Register value */ odr = GPIOx->ODR; /* Set selected pins that were at low level, and reset ones that were high */ GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin); } /** * @brief Lock GPIO Pins configuration registers. * @note The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR, * GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH. * @note The configuration of the locked GPIO pins can no longer be modified * until the next reset. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the port bits to be locked. * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). * @retval None */ HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { __IO uint32_t tmp = GPIO_LCKR_LCKK; /* Check the parameters */ assert_param(IS_GPIO_LOCK_INSTANCE(GPIOx)); assert_param(IS_GPIO_PIN(GPIO_Pin)); /* Apply lock key write sequence */ tmp |= GPIO_Pin; /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ GPIOx->LCKR = tmp; /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ GPIOx->LCKR = GPIO_Pin; /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ GPIOx->LCKR = tmp; /* Read LCKK register. This read is mandatory to complete key lock sequence */ tmp = GPIOx->LCKR; /* read again in order to confirm lock is active */ if ((GPIOx->LCKR & GPIO_LCKR_LCKK) != 0x00u) { return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Handle EXTI interrupt request. * @param GPIO_Pin Specifies the port pin connected to corresponding EXTI line. * @retval None */ void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) { /* EXTI line interrupt detected */ if (__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != 0x00u) { __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); HAL_GPIO_EXTI_Callback(GPIO_Pin); } } /** * @brief EXTI line detection callback. * @param GPIO_Pin: Specifies the port pin connected to corresponding EXTI line. * @retval None */ __weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { /* Prevent unused argument(s) compilation warning */ UNUSED(GPIO_Pin); /* NOTE: This function should not be modified, when the callback is needed, the HAL_GPIO_EXTI_Callback could be implemented in the user file */ } /** * @} */ /** * @} */ #endif /* HAL_GPIO_MODULE_ENABLED */ /** * @} */ /** * @} */
18,379
C
33.484052
99
0.572556
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_crc_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_crc_ex.c * @author MCD Application Team * @brief Extended CRC HAL module driver. * This file provides firmware functions to manage the extended * functionalities of the CRC 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 ##### ================================================================================ [..] (+) Set user-defined generating polynomial through HAL_CRCEx_Polynomial_Set() (+) Configure Input or Output data inversion @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup CRCEx CRCEx * @brief CRC Extended HAL module driver * @{ */ #ifdef HAL_CRC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRCEx_Exported_Functions CRC Extended Exported Functions * @{ */ /** @defgroup CRCEx_Exported_Functions_Group1 Extended Initialization/de-initialization functions * @brief Extended Initialization and Configuration functions. * @verbatim =============================================================================== ##### Extended configuration functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Configure the generating polynomial (+) Configure the input data inversion (+) Configure the output data inversion @endverbatim * @{ */ /** * @brief Initialize the CRC polynomial if different from default one. * @param hcrc CRC handle * @param Pol CRC generating polynomial (7, 8, 16 or 32-bit long). * This parameter is written in normal representation, e.g. * @arg for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65 * @arg for a polynomial of degree 16, X^16 + X^12 + X^5 + 1 is written 0x1021 * @param PolyLength CRC polynomial length. * This parameter can be one of the following values: * @arg @ref CRC_POLYLENGTH_7B 7-bit long CRC (generating polynomial of degree 7) * @arg @ref CRC_POLYLENGTH_8B 8-bit long CRC (generating polynomial of degree 8) * @arg @ref CRC_POLYLENGTH_16B 16-bit long CRC (generating polynomial of degree 16) * @arg @ref CRC_POLYLENGTH_32B 32-bit long CRC (generating polynomial of degree 32) * @retval HAL status */ HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength) { HAL_StatusTypeDef status = HAL_OK; uint32_t msb = 31U; /* polynomial degree is 32 at most, so msb is initialized to max value */ /* Check the parameters */ assert_param(IS_CRC_POL_LENGTH(PolyLength)); /* check polynomial definition vs polynomial size: * polynomial length must be aligned with polynomial * definition. HAL_ERROR is reported if Pol degree is * larger than that indicated by PolyLength. * Look for MSB position: msb will contain the degree of * the second to the largest polynomial member. E.g., for * X^7 + X^6 + X^5 + X^2 + 1, msb = 6. */ while ((msb-- > 0U) && ((Pol & ((uint32_t)(0x1U) << (msb & 0x1FU))) == 0U)) { } switch (PolyLength) { case CRC_POLYLENGTH_7B: if (msb >= HAL_CRC_LENGTH_7B) { status = HAL_ERROR; } break; case CRC_POLYLENGTH_8B: if (msb >= HAL_CRC_LENGTH_8B) { status = HAL_ERROR; } break; case CRC_POLYLENGTH_16B: if (msb >= HAL_CRC_LENGTH_16B) { status = HAL_ERROR; } break; case CRC_POLYLENGTH_32B: /* no polynomial definition vs. polynomial length issue possible */ break; default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* set generating polynomial */ WRITE_REG(hcrc->Instance->POL, Pol); /* set generating polynomial size */ MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, PolyLength); } /* Return function status */ return status; } /** * @brief Set the Reverse Input data mode. * @param hcrc CRC handle * @param InputReverseMode Input Data inversion mode. * This parameter can be one of the following values: * @arg @ref CRC_INPUTDATA_INVERSION_NONE no change in bit order (default value) * @arg @ref CRC_INPUTDATA_INVERSION_BYTE Byte-wise bit reversal * @arg @ref CRC_INPUTDATA_INVERSION_HALFWORD HalfWord-wise bit reversal * @arg @ref CRC_INPUTDATA_INVERSION_WORD Word-wise bit reversal * @retval HAL status */ HAL_StatusTypeDef HAL_CRCEx_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode) { /* Check the parameters */ assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(InputReverseMode)); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* set input data inversion mode */ MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, InputReverseMode); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Set the Reverse Output data mode. * @param hcrc CRC handle * @param OutputReverseMode Output Data inversion mode. * This parameter can be one of the following values: * @arg @ref CRC_OUTPUTDATA_INVERSION_DISABLE no CRC inversion (default value) * @arg @ref CRC_OUTPUTDATA_INVERSION_ENABLE bit-level inversion (e.g. for a 8-bit CRC: 0xB5 becomes 0xAD) * @retval HAL status */ HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode) { /* Check the parameters */ assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(OutputReverseMode)); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* set output data inversion mode */ MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, OutputReverseMode); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @} */ /** * @} */ #endif /* HAL_CRC_MODULE_ENABLED */ /** * @} */ /** * @} */
7,388
C
31.986607
117
0.554819
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_dma.c
/** ****************************************************************************** * @file stm32g4xx_hal_dma.c * @author MCD Application Team * @brief DMA HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Direct Memory Access (DMA) peripheral: * + Initialization and de-initialization functions * + IO operation functions * + Peripheral State and errors functions * ****************************************************************************** * @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 and configure the peripheral to be connected to the DMA Channel (except for internal SRAM / FLASH memories: no initialization is necessary). Please refer to the Reference manual for connection between peripherals and DMA requests. (#) For a given Channel, program the required configuration through the following parameters: Channel request, Transfer Direction, Source and Destination data formats, Circular or Normal mode, Channel Priority level, Source and Destination Increment mode using HAL_DMA_Init() function. Prior to HAL_DMA_Init the peripheral clock shall be enabled for both DMA & DMAMUX thanks to: (##) DMA1 or DMA2: __HAL_RCC_DMA1_CLK_ENABLE() or __HAL_RCC_DMA2_CLK_ENABLE() ; (##) DMAMUX1: __HAL_RCC_DMAMUX1_CLK_ENABLE(); (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error detection. (#) Use HAL_DMA_Abort() function to abort the current transfer -@- In Memory-to-Memory transfer mode, Circular mode is not allowed. *** Polling mode IO operation *** ================================= [..] (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source address and destination address and the Length of data to be transferred (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this case a fixed Timeout can be configured by User depending from his application. *** Interrupt mode IO operation *** =================================== [..] (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority() (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ() (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of Source address and destination address and the Length of data to be transferred. In this case the DMA interrupt is configured (+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can add his own function to register callbacks with HAL_DMA_RegisterCallback(). *** DMA HAL driver macros list *** ============================================= [..] Below the list of macros in DMA HAL driver. (+) __HAL_DMA_ENABLE: Enable the specified DMA Channel. (+) __HAL_DMA_DISABLE: Disable the specified DMA Channel. (+) __HAL_DMA_GET_FLAG: Get the DMA Channel pending flags. (+) __HAL_DMA_CLEAR_FLAG: Clear the DMA Channel pending flags. (+) __HAL_DMA_ENABLE_IT: Enable the specified DMA Channel interrupts. (+) __HAL_DMA_DISABLE_IT: Disable the specified DMA Channel interrupts. (+) __HAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Channel interrupt has occurred or not. [..] (@) You can refer to the DMA HAL driver header file for more useful macros @endverbatim */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup DMA DMA * @brief DMA HAL module driver * @{ */ #ifdef HAL_DMA_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup DMA_Private_Functions DMA Private Functions * @{ */ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); static void DMA_CalcDMAMUXChannelBaseAndMask(DMA_HandleTypeDef *hdma); static void DMA_CalcDMAMUXRequestGenBaseAndMask(DMA_HandleTypeDef *hdma); /** * @} */ /* Exported functions ---------------------------------------------------------*/ /** @defgroup DMA_Exported_Functions DMA Exported Functions * @{ */ /** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and de-initialization functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to initialize the DMA Channel source and destination addresses, incrementation and data sizes, transfer direction, circular/normal mode selection, memory-to-memory mode selection and Channel priority value. [..] The HAL_DMA_Init() function follows the DMA configuration procedures as described in reference manual. @endverbatim * @{ */ /** * @brief Initialize the DMA according to the specified * parameters in the DMA_InitTypeDef and initialize the associated handle. * @param hdma Pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) { uint32_t tmp; /* Check the DMA handle allocation */ if (hdma == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); assert_param(IS_DMA_DIRECTION(hdma->Init.Direction)); assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc)); assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc)); assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment)); assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment)); assert_param(IS_DMA_MODE(hdma->Init.Mode)); assert_param(IS_DMA_PRIORITY(hdma->Init.Priority)); assert_param(IS_DMA_ALL_REQUEST(hdma->Init.Request)); /* Compute the channel index */ if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) { /* DMA1 */ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; hdma->DmaBaseAddress = DMA1; } else { /* DMA2 */ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2; hdma->DmaBaseAddress = DMA2; } /* Change DMA peripheral state */ hdma->State = HAL_DMA_STATE_BUSY; /* Get the CR register value */ tmp = hdma->Instance->CCR; /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR and MEM2MEM bits */ tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR | DMA_CCR_MEM2MEM)); /* Prepare the DMA Channel configuration */ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | hdma->Init.Mode | hdma->Init.Priority; /* Write to DMA Channel CR register */ hdma->Instance->CCR = tmp; /* Initialize parameters for DMAMUX channel : DMAmuxChannel, DMAmuxChannelStatus and DMAmuxChannelStatusMask */ DMA_CalcDMAMUXChannelBaseAndMask(hdma); if (hdma->Init.Direction == DMA_MEMORY_TO_MEMORY) { /* if memory to memory force the request to 0*/ hdma->Init.Request = DMA_REQUEST_MEM2MEM; } /* Set peripheral request to DMAMUX channel */ hdma->DMAmuxChannel->CCR = (hdma->Init.Request & DMAMUX_CxCR_DMAREQ_ID); /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; if (((hdma->Init.Request > 0U) && (hdma->Init.Request <= DMA_REQUEST_GENERATOR3))) { /* Initialize parameters for DMAMUX request generator : DMAmuxRequestGen, DMAmuxRequestGenStatus and DMAmuxRequestGenStatusMask */ DMA_CalcDMAMUXRequestGenBaseAndMask(hdma); /* Reset the DMAMUX request generator register*/ hdma->DMAmuxRequestGen->RGCR = 0U; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; } else { hdma->DMAmuxRequestGen = 0U; hdma->DMAmuxRequestGenStatus = 0U; hdma->DMAmuxRequestGenStatusMask = 0U; } /* Initialize the error code */ hdma->ErrorCode = HAL_DMA_ERROR_NONE; /* Initialize the DMA state*/ hdma->State = HAL_DMA_STATE_READY; /* Allocate lock resource and initialize it */ hdma->Lock = HAL_UNLOCKED; return HAL_OK; } /** * @brief DeInitialize the DMA peripheral. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) { /* Check the DMA handle allocation */ if (NULL == hdma) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); /* Disable the selected DMA Channelx */ __HAL_DMA_DISABLE(hdma); /* Compute the channel index */ if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) { /* DMA1 */ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; hdma->DmaBaseAddress = DMA1; } else { /* DMA2 */ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2; hdma->DmaBaseAddress = DMA2; } /* Reset DMA Channel control register */ hdma->Instance->CCR = 0; /* Clear all flags */ hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Initialize parameters for DMAMUX channel : DMAmuxChannel, DMAmuxChannelStatus and DMAmuxChannelStatusMask */ DMA_CalcDMAMUXChannelBaseAndMask(hdma); /* Reset the DMAMUX channel that corresponds to the DMA channel */ hdma->DMAmuxChannel->CCR = 0; /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; /* Reset Request generator parameters if any */ if (((hdma->Init.Request > 0U) && (hdma->Init.Request <= DMA_REQUEST_GENERATOR3))) { /* Initialize parameters for DMAMUX request generator : DMAmuxRequestGen, DMAmuxRequestGenStatus and DMAmuxRequestGenStatusMask */ DMA_CalcDMAMUXRequestGenBaseAndMask(hdma); /* Reset the DMAMUX request generator register*/ hdma->DMAmuxRequestGen->RGCR = 0U; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; } hdma->DMAmuxRequestGen = 0U; hdma->DMAmuxRequestGenStatus = 0U; hdma->DMAmuxRequestGenStatusMask = 0U; /* Clean callbacks */ hdma->XferCpltCallback = NULL; hdma->XferHalfCpltCallback = NULL; hdma->XferErrorCallback = NULL; hdma->XferAbortCallback = NULL; /* Initialize the error code */ hdma->ErrorCode = HAL_DMA_ERROR_NONE; /* Initialize the DMA state */ hdma->State = HAL_DMA_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hdma); return HAL_OK; } /** * @} */ /** @defgroup DMA_Exported_Functions_Group2 Input and Output operation functions * @brief Input and Output operation functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Configure the source, destination address and data length and Start DMA transfer (+) Configure the source, destination address and data length and Start DMA transfer with interrupt (+) Abort DMA transfer (+) Poll for transfer complete (+) Handle DMA interrupt request @endverbatim * @{ */ /** * @brief Start the DMA Transfer. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param SrcAddress The source memory Buffer address * @param DstAddress The destination memory Buffer address * @param DataLength The length of data to be transferred from source to destination (up to 256Kbytes-1) * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_DMA_BUFFER_SIZE(DataLength)); /* Process locked */ __HAL_LOCK(hdma); if (HAL_DMA_STATE_READY == hdma->State) { /* Change DMA peripheral state */ hdma->State = HAL_DMA_STATE_BUSY; hdma->ErrorCode = HAL_DMA_ERROR_NONE; /* Disable the peripheral */ __HAL_DMA_DISABLE(hdma); /* Configure the source, destination address and the data length & clear flags*/ DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); /* Enable the Peripheral */ __HAL_DMA_ENABLE(hdma); } else { /* Process Unlocked */ __HAL_UNLOCK(hdma); status = HAL_BUSY; } return status; } /** * @brief Start the DMA Transfer with interrupt enabled. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param SrcAddress The source memory Buffer address * @param DstAddress The destination memory Buffer address * @param DataLength The length of data to be transferred from source to destination (up to 256Kbytes-1) * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_DMA_BUFFER_SIZE(DataLength)); /* Process locked */ __HAL_LOCK(hdma); if (HAL_DMA_STATE_READY == hdma->State) { /* Change DMA peripheral state */ hdma->State = HAL_DMA_STATE_BUSY; hdma->ErrorCode = HAL_DMA_ERROR_NONE; /* Disable the peripheral */ __HAL_DMA_DISABLE(hdma); /* Configure the source, destination address and the data length & clear flags*/ DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); /* Enable the transfer complete interrupt */ /* Enable the transfer Error interrupt */ if (NULL != hdma->XferHalfCpltCallback) { /* Enable the Half transfer complete interrupt as well */ __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); } else { __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_TE)); } /* Check if DMAMUX Synchronization is enabled*/ if ((hdma->DMAmuxChannel->CCR & DMAMUX_CxCR_SE) != 0U) { /* Enable DMAMUX sync overrun IT*/ hdma->DMAmuxChannel->CCR |= DMAMUX_CxCR_SOIE; } if (hdma->DMAmuxRequestGen != 0U) { /* if using DMAMUX request generator, enable the DMAMUX request generator overrun IT*/ /* enable the request gen overrun IT*/ hdma->DMAmuxRequestGen->RGCR |= DMAMUX_RGxCR_OIE; } /* Enable the Peripheral */ __HAL_DMA_ENABLE(hdma); } else { /* Process Unlocked */ __HAL_UNLOCK(hdma); /* Remain BUSY */ status = HAL_BUSY; } return status; } /** * @brief Abort the DMA Transfer. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma) { HAL_StatusTypeDef status = HAL_OK; if(hdma->State != HAL_DMA_STATE_BUSY) { /* no transfer ongoing */ hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; status = HAL_ERROR; } else { /* Disable DMA IT */ __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); /* disable the DMAMUX sync overrun IT*/ hdma->DMAmuxChannel->CCR &= ~DMAMUX_CxCR_SOIE; /* Disable the channel */ __HAL_DMA_DISABLE(hdma); /* Clear all flags */ hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; if (hdma->DMAmuxRequestGen != 0U) { /* if using DMAMUX request generator, disable the DMAMUX request generator overrun IT*/ /* disable the request gen overrun IT*/ hdma->DMAmuxRequestGen->RGCR &= ~DMAMUX_RGxCR_OIE; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; } } /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); return status; } /** * @brief Aborts the DMA Transfer in Interrupt mode. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) { HAL_StatusTypeDef status = HAL_OK; if (HAL_DMA_STATE_BUSY != hdma->State) { /* no transfer ongoing */ hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); status = HAL_ERROR; } else { /* Disable DMA IT */ __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); /* Disable the channel */ __HAL_DMA_DISABLE(hdma); /* disable the DMAMUX sync overrun IT*/ hdma->DMAmuxChannel->CCR &= ~DMAMUX_CxCR_SOIE; /* Clear all flags */ hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; if (hdma->DMAmuxRequestGen != 0U) { /* if using DMAMUX request generator, disable the DMAMUX request generator overrun IT*/ /* disable the request gen overrun IT*/ hdma->DMAmuxRequestGen->RGCR &= ~DMAMUX_RGxCR_OIE; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; } /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); /* Call User Abort callback */ if (hdma->XferAbortCallback != NULL) { hdma->XferAbortCallback(hdma); } } return status; } /** * @brief Polling for transfer complete. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param CompleteLevel Specifies the DMA level complete. * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, HAL_DMA_LevelCompleteTypeDef CompleteLevel, uint32_t Timeout) { uint32_t temp; uint32_t tickstart; if (HAL_DMA_STATE_BUSY != hdma->State) { /* no transfer ongoing */ hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; __HAL_UNLOCK(hdma); return HAL_ERROR; } /* Polling mode not supported in circular mode */ if (0U != (hdma->Instance->CCR & DMA_CCR_CIRC)) { hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED; return HAL_ERROR; } /* Get the level transfer complete flag */ if (HAL_DMA_FULL_TRANSFER == CompleteLevel) { /* Transfer Complete flag */ temp = (uint32_t)DMA_FLAG_TC1 << (hdma->ChannelIndex & 0x1FU); } else { /* Half Transfer Complete flag */ temp = (uint32_t)DMA_FLAG_HT1 << (hdma->ChannelIndex & 0x1FU); } /* Get tick */ tickstart = HAL_GetTick(); while (0U == (hdma->DmaBaseAddress->ISR & temp)) { if ((0U != (hdma->DmaBaseAddress->ISR & ((uint32_t)DMA_FLAG_TE1 << (hdma->ChannelIndex & 0x1FU))))) { /* When a DMA transfer error occurs */ /* A hardware clear of its EN bits is performed */ /* Clear all flags */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Update error code */ hdma->ErrorCode = HAL_DMA_ERROR_TE; /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); return HAL_ERROR; } /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) { /* Update error code */ hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); return HAL_ERROR; } } } /*Check for DMAMUX Request generator (if used) overrun status */ if (hdma->DMAmuxRequestGen != 0U) { /* if using DMAMUX request generator Check for DMAMUX request generator overrun */ if ((hdma->DMAmuxRequestGenStatus->RGSR & hdma->DMAmuxRequestGenStatusMask) != 0U) { /* Disable the request gen overrun interrupt */ hdma->DMAmuxRequestGen->RGCR |= DMAMUX_RGxCR_OIE; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_REQGEN; } } /* Check for DMAMUX Synchronization overrun */ if ((hdma->DMAmuxChannelStatus->CSR & hdma->DMAmuxChannelStatusMask) != 0U) { /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_SYNC; } if (HAL_DMA_FULL_TRANSFER == CompleteLevel) { /* Clear the transfer complete flag */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_FLAG_TC1 << (hdma->ChannelIndex & 0x1FU)); /* The selected Channelx EN bit is cleared (DMA is disabled and all transfers are complete) */ hdma->State = HAL_DMA_STATE_READY; } else { /* Clear the half transfer complete flag */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_FLAG_HT1 << (hdma->ChannelIndex & 0x1FU)); } /* Process unlocked */ __HAL_UNLOCK(hdma); return HAL_OK; } /** * @brief Handle DMA interrupt request. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval None */ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) { uint32_t flag_it = hdma->DmaBaseAddress->ISR; uint32_t source_it = hdma->Instance->CCR; /* Half Transfer Complete Interrupt management ******************************/ if ((0U != (flag_it & ((uint32_t)DMA_FLAG_HT1 << (hdma->ChannelIndex & 0x1FU)))) && (0U != (source_it & DMA_IT_HT))) { /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ if ((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) { /* Disable the half transfer interrupt */ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); } /* Clear the half transfer complete flag */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_ISR_HTIF1 << (hdma->ChannelIndex & 0x1FU)); /* DMA peripheral state is not updated in Half Transfer */ /* but in Transfer Complete case */ if (hdma->XferHalfCpltCallback != NULL) { /* Half transfer callback */ hdma->XferHalfCpltCallback(hdma); } } /* Transfer Complete Interrupt management ***********************************/ else if ((0U != (flag_it & ((uint32_t)DMA_FLAG_TC1 << (hdma->ChannelIndex & 0x1FU)))) && (0U != (source_it & DMA_IT_TC))) { if ((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) { /* Disable the transfer complete and error interrupt */ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE | DMA_IT_TC); /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; } /* Clear the transfer complete flag */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_ISR_TCIF1 << (hdma->ChannelIndex & 0x1FU)); /* Process Unlocked */ __HAL_UNLOCK(hdma); if (hdma->XferCpltCallback != NULL) { /* Transfer complete callback */ hdma->XferCpltCallback(hdma); } } /* Transfer Error Interrupt management **************************************/ else if ((0U != (flag_it & ((uint32_t)DMA_FLAG_TE1 << (hdma->ChannelIndex & 0x1FU)))) && (0U != (source_it & DMA_IT_TE))) { /* When a DMA transfer error occurs */ /* A hardware clear of its EN bits is performed */ /* Disable ALL DMA IT */ __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); /* Clear all flags */ hdma->DmaBaseAddress->IFCR = ((uint32_t)DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Update error code */ hdma->ErrorCode = HAL_DMA_ERROR_TE; /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hdma); if (hdma->XferErrorCallback != NULL) { /* Transfer error callback */ hdma->XferErrorCallback(hdma); } } else { /* Nothing To Do */ } return; } /** * @brief Register callbacks * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param CallbackID User Callback identifier * a HAL_DMA_CallbackIDTypeDef ENUM as parameter. * @param pCallback pointer to private callbacsk function which has pointer to * a DMA_HandleTypeDef structure as parameter. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)(DMA_HandleTypeDef *_hdma)) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(hdma); if (HAL_DMA_STATE_READY == hdma->State) { switch (CallbackID) { case HAL_DMA_XFER_CPLT_CB_ID: hdma->XferCpltCallback = pCallback; break; case HAL_DMA_XFER_HALFCPLT_CB_ID: hdma->XferHalfCpltCallback = pCallback; break; case HAL_DMA_XFER_ERROR_CB_ID: hdma->XferErrorCallback = pCallback; break; case HAL_DMA_XFER_ABORT_CB_ID: hdma->XferAbortCallback = pCallback; break; default: status = HAL_ERROR; break; } } else { status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hdma); return status; } /** * @brief UnRegister callbacks * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param CallbackID User Callback identifier * a HAL_DMA_CallbackIDTypeDef ENUM as parameter. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(hdma); if (HAL_DMA_STATE_READY == hdma->State) { switch (CallbackID) { case HAL_DMA_XFER_CPLT_CB_ID: hdma->XferCpltCallback = NULL; break; case HAL_DMA_XFER_HALFCPLT_CB_ID: hdma->XferHalfCpltCallback = NULL; break; case HAL_DMA_XFER_ERROR_CB_ID: hdma->XferErrorCallback = NULL; break; case HAL_DMA_XFER_ABORT_CB_ID: hdma->XferAbortCallback = NULL; break; case HAL_DMA_XFER_ALL_CB_ID: hdma->XferCpltCallback = NULL; hdma->XferHalfCpltCallback = NULL; hdma->XferErrorCallback = NULL; hdma->XferAbortCallback = NULL; break; default: status = HAL_ERROR; break; } } else { status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hdma); return status; } /** * @} */ /** @defgroup DMA_Exported_Functions_Group3 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 DMA state (+) Get error code @endverbatim * @{ */ /** * @brief Return the DMA hande state. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval HAL state */ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma) { /* Return DMA handle state */ return hdma->State; } /** * @brief Return the DMA error code. * @param hdma : pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval DMA Error Code */ uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) { return hdma->ErrorCode; } /** * @} */ /** * @} */ /** @addtogroup DMA_Private_Functions * @{ */ /** * @brief Sets the DMA Transfer parameter. * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @param SrcAddress The source memory Buffer address * @param DstAddress The destination memory Buffer address * @param DataLength The length of data to be transferred from source to destination * @retval HAL status */ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; if (hdma->DMAmuxRequestGen != 0U) { /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; } /* Clear all flags */ hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex & 0x1FU)); /* Configure DMA Channel data length */ hdma->Instance->CNDTR = DataLength; /* Memory to Peripheral */ if ((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) { /* Configure DMA Channel destination address */ hdma->Instance->CPAR = DstAddress; /* Configure DMA Channel source address */ hdma->Instance->CMAR = SrcAddress; } /* Peripheral to Memory */ else { /* Configure DMA Channel source address */ hdma->Instance->CPAR = SrcAddress; /* Configure DMA Channel destination address */ hdma->Instance->CMAR = DstAddress; } } /** * @brief Updates the DMA handle with the DMAMUX channel and status mask depending on stream number * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Stream. * @retval None */ static void DMA_CalcDMAMUXChannelBaseAndMask(DMA_HandleTypeDef *hdma) { uint32_t dmamux_base_addr; uint32_t channel_number; DMAMUX_Channel_TypeDef *DMAMUX1_ChannelBase; /* check if instance is not outside the DMA channel range */ if ((uint32_t)hdma->Instance < (uint32_t)DMA2_Channel1) { /* DMA1 */ DMAMUX1_ChannelBase = DMAMUX1_Channel0; } else { /* DMA2 */ #if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G474xx) || defined (STM32G483xx) || defined (STM32G484xx) || defined (STM32G491xx) || defined (STM32G4A1xx) DMAMUX1_ChannelBase = DMAMUX1_Channel8; #elif defined (STM32G431xx) || defined (STM32G441xx) || defined (STM32GBK1CB) DMAMUX1_ChannelBase = DMAMUX1_Channel6; #else DMAMUX1_ChannelBase = DMAMUX1_Channel7; #endif /* STM32G4x1xx) */ } dmamux_base_addr = (uint32_t)DMAMUX1_ChannelBase; channel_number = (((uint32_t)hdma->Instance & 0xFFU) - 8U) / 20U; hdma->DMAmuxChannel = (DMAMUX_Channel_TypeDef *)(uint32_t)(dmamux_base_addr + ((hdma->ChannelIndex >> 2U) * ((uint32_t)DMAMUX1_Channel1 - (uint32_t)DMAMUX1_Channel0))); hdma->DMAmuxChannelStatus = DMAMUX1_ChannelStatus; hdma->DMAmuxChannelStatusMask = 1UL << (channel_number & 0x1FU); } /** * @brief Updates the DMA handle with the DMAMUX request generator params * @param hdma pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval None */ static void DMA_CalcDMAMUXRequestGenBaseAndMask(DMA_HandleTypeDef *hdma) { uint32_t request = hdma->Init.Request & DMAMUX_CxCR_DMAREQ_ID; /* DMA Channels are connected to DMAMUX1 request generator blocks*/ hdma->DMAmuxRequestGen = (DMAMUX_RequestGen_TypeDef *)((uint32_t)(((uint32_t)DMAMUX1_RequestGenerator0) + ((request - 1U) * 4U))); hdma->DMAmuxRequestGenStatus = DMAMUX1_RequestGenStatus; hdma->DMAmuxRequestGenStatusMask = 1UL << ((request - 1U) & 0x1FU); } /** * @} */ /** * @} */ #endif /* HAL_DMA_MODULE_ENABLED */ /** * @} */ /** * @} */
34,993
C
30.49775
175
0.619152
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_rcc.c
/** ****************************************************************************** * @file stm32g4xx_hal_rcc.c * @author MCD Application Team * @brief RCC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Reset and Clock Control (RCC) peripheral: * + Initialization and de-initialization functions * + Peripheral Control functions * @verbatim ============================================================================== ##### RCC specific features ##### ============================================================================== [..] After reset the device is running from High Speed Internal oscillator (16 MHz) with Flash 0 wait state. Flash prefetch buffer, D-Cache and I-Cache are disabled, and all peripherals are off except internal SRAM, Flash and JTAG. (+) There is no prescaler on High speed (AHBs) and Low speed (APBs) buses: all peripherals mapped on these buses are running at HSI speed. (+) The clock for all peripherals is switched off, except the SRAM and FLASH. (+) All GPIOs are in analog mode, except the JTAG pins which are assigned to be used for debug purpose. [..] Once the device started from reset, the user application has to: (+) Configure the clock source to be used to drive the System clock (if the application needs higher frequency/performance) (+) Configure the System clock frequency and Flash settings (+) Configure the AHB and APB buses prescalers (+) Enable the clock for the peripheral(s) to be used (+) Configure the clock source(s) for peripherals which clocks are not derived from the System clock (USB, RNG, USART, LPUART, FDCAN, some TIMERs, UCPD, I2S, I2C, LPTIM, ADC, QSPI) @endverbatim ****************************************************************************** * @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 RCC RCC * @brief RCC HAL module driver * @{ */ #ifdef HAL_RCC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup RCC_Private_Constants RCC Private Constants * @{ */ #define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT #define HSI_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ #define LSI_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ #define HSI48_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ #define PLL_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ #define CLOCKSWITCH_TIMEOUT_VALUE 5000U /* 5 s */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup RCC_Private_Macros RCC Private Macros * @{ */ #define RCC_GET_MCO_GPIO_PIN(__RCC_MCOx__) ((__RCC_MCOx__) & GPIO_PIN_MASK) #define RCC_GET_MCO_GPIO_AF(__RCC_MCOx__) (((__RCC_MCOx__) & RCC_MCO_GPIOAF_MASK) >> RCC_MCO_GPIOAF_POS) #define RCC_GET_MCO_GPIO_INDEX(__RCC_MCOx__) (((__RCC_MCOx__) & RCC_MCO_GPIOPORT_MASK) >> RCC_MCO_GPIOPORT_POS) #define RCC_GET_MCO_GPIO_PORT(__RCC_MCOx__) (AHB2PERIPH_BASE + ((0x00000400UL) * RCC_GET_MCO_GPIO_INDEX(__RCC_MCOx__))) #define RCC_PLL_OSCSOURCE_CONFIG(__HAL_RCC_PLLSOURCE__) \ (MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, (__HAL_RCC_PLLSOURCE__))) /** * @} */ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup RCC_Private_Functions RCC Private Functions * @{ */ static uint32_t RCC_GetSysClockFreqFromPLLSource(void); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RCC_Exported_Functions RCC Exported Functions * @{ */ /** @defgroup RCC_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to configure the internal and external oscillators (HSE, HSI, LSE, LSI, PLL, CSS and MCO) and the System buses clocks (SYSCLK, AHB, APB1 and APB2). [..] Internal/external clock and PLL configuration (+) HSI (high-speed internal): 16 MHz factory-trimmed RC used directly or through the PLL as System clock source. (+) LSI (low-speed internal): 32 KHz low consumption RC used as IWDG and/or RTC clock source. (+) HSE (high-speed external): 4 to 48 MHz crystal oscillator used directly or through the PLL as System clock source. Can be used also optionally as RTC clock source. (+) LSE (low-speed external): 32.768 KHz oscillator used optionally as RTC clock source. (+) PLL (clocked by HSI, HSE) providing up to three independent output clocks: (++) The first output is used to generate the high speed system clock (up to 170 MHz). (++) The second output is used to generate the clock for the USB (48 MHz), the QSPI (<= 48 MHz), the FDCAN, the SAI and the I2S. (++) The third output is used to generate a clock for ADC (+) CSS (Clock security system): once enabled, if a HSE clock failure occurs (HSE used directly or through PLL as System clock source), the System clock is automatically switched to HSI and an interrupt is generated if enabled. The interrupt is linked to the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector. (+) MCO (microcontroller clock output): used to output LSI, HSI, LSE, HSE, main PLL clock, system clock or RC48 clock (through a configurable prescaler) on PA8 pin. [..] System, AHB and APB buses clocks configuration (+) Several clock sources can be used to drive the System clock (SYSCLK): HSI, HSE and main PLL. The AHB clock (HCLK) is derived from System clock through configurable prescaler and used to clock the CPU, memory and peripherals mapped on AHB bus (DMA, GPIO...). APB1 (PCLK1) and APB2 (PCLK2) clocks are derived from AHB clock through configurable prescalers and used to clock the peripherals mapped on these buses. You can use "HAL_RCC_GetSysClockFreq()" function to retrieve the frequencies of these clocks. -@- All the peripheral clocks are derived from the System clock (SYSCLK) except: (+@) RTC: the RTC clock can be derived either from the LSI, LSE or HSE clock divided by 2 to 31. You have to use __HAL_RCC_RTC_ENABLE() and HAL_RCCEx_PeriphCLKConfig() function to configure this clock. (+@) USB FS and RNG: USB FS requires a frequency equal to 48 MHz to work correctly, while the RNG peripheral requires a frequency equal or lower than to 48 MHz. This clock is derived of the main PLL through PLLQ divider. You have to enable the peripheral clock and use HAL_RCCEx_PeriphCLKConfig() function to configure this clock. (+@) IWDG clock which is always the LSI clock. (+) The maximum frequency of the SYSCLK, HCLK, PCLK1 and PCLK2 is 170 MHz. The clock source frequency should be adapted depending on the device voltage range as listed in the Reference Manual "Clock source frequency versus voltage scaling" chapter. @endverbatim Table 1. HCLK clock frequency for STM32G4xx devices +----------------------------------------------------------------------------+ | Latency | HCLK clock frequency (MHz) | | |----------------------------------------------------------| | | voltage range 1 | voltage range 1 | voltage range 2 | | | boost mode 1.28 V | normal mode 1.2 V | 1.0 V | |-----------------|-------------------|-------------------|------------------| |0WS(1 CPU cycles)| HCLK <= 34 | HCLK <= 30 | HCLK <= 13 | |-----------------|-------------------|-------------------|------------------| |1WS(2 CPU cycles)| HCLK <= 68 | HCLK <= 60 | HCLK <= 26 | |-----------------|-------------------|-------------------|------------------| |2WS(3 CPU cycles)| HCLK <= 102 | HCLK <= 90 | - | |-----------------|-------------------|-------------------|------------------| |3WS(4 CPU cycles)| HCLK <= 136 | HCLK <= 120 | - | |-----------------|-------------------|-------------------|------------------| |4WS(5 CPU cycles)| HCLK <= 170 | HCLK <= 150 | - | +----------------------------------------------------------------------------+ * @{ */ /** * @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, PLL OFF * - AHB, APB1 and APB2 prescaler set to 1. * - CSS, MCO1 OFF * - All interrupts disabled * - All interrupt and reset flags cleared * @note This function doesn't modify the configuration of the * - Peripheral clocks * - LSI, LSE and RTC clocks * @retval HAL status */ HAL_StatusTypeDef HAL_RCC_DeInit(void) { uint32_t tickstart; /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Set HSION bit to the reset value */ SET_BIT(RCC->CR, RCC_CR_HSION); /* Wait till HSI is ready */ while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U) { if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Set HSITRIM[6:0] bits to the reset value */ SET_BIT(RCC->ICSCR, RCC_HSICALIBRATION_DEFAULT << RCC_ICSCR_HSITRIM_Pos); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Reset CFGR register (HSI is selected as system clock source) */ RCC->CFGR = 0x00000001u; /* Wait till HSI is ready */ while (READ_BIT(RCC->CFGR, RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI) { if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Update the SystemCoreClock global variable */ SystemCoreClock = HSI_VALUE; /* Adapt Systick interrupt period */ if (HAL_InitTick(uwTickPrio) != HAL_OK) { return HAL_ERROR; } /* Clear CR register in 2 steps: first to clear HSEON in case bypass was enabled */ RCC->CR = RCC_CR_HSION; /* Then again to HSEBYP in case bypass was enabled */ RCC->CR = RCC_CR_HSION; /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till PLL is OFF */ while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) != 0U) { if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* once PLL is OFF, reset PLLCFGR register to default value */ RCC->PLLCFGR = RCC_PLLCFGR_PLLN_4; /* Disable all interrupts */ CLEAR_REG(RCC->CIER); /* Clear all interrupt flags */ WRITE_REG(RCC->CICR, 0xFFFFFFFFU); /* Clear all reset flags */ SET_BIT(RCC->CSR, RCC_CSR_RMVF); return HAL_OK; } /** * @brief Initialize the RCC Oscillators according to the specified parameters in the * RCC_OscInitTypeDef. * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that * contains the configuration information for the RCC Oscillators. * @note The PLL is not disabled when used as system clock. * @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not * supported by this macro. User should request a transition to LSE Off * first and then LSE On or LSE Bypass. * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not * supported by this macro. User should request a transition to HSE Off * first and then HSE On or HSE Bypass. * @retval HAL status */ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { uint32_t tickstart; uint32_t temp_sysclksrc; uint32_t temp_pllckcfg; /* Check Null pointer */ if (RCC_OscInitStruct == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType)); /*------------------------------- HSE Configuration ------------------------*/ if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) { /* Check the parameters */ assert_param(IS_RCC_HSE(RCC_OscInitStruct->HSEState)); temp_sysclksrc = __HAL_RCC_GET_SYSCLK_SOURCE(); temp_pllckcfg = __HAL_RCC_GET_PLL_OSCSOURCE(); /* When the HSE is used as system clock or clock source for PLL in these cases it is not allowed to be disabled */ if (((temp_sysclksrc == RCC_CFGR_SWS_PLL) && (temp_pllckcfg == RCC_PLLSOURCE_HSE)) || (temp_sysclksrc == RCC_CFGR_SWS_HSE)) { if ((READ_BIT(RCC->CR, RCC_CR_HSERDY) != 0U) && (RCC_OscInitStruct->HSEState == RCC_HSE_OFF)) { return HAL_ERROR; } } else { /* Set the new HSE configuration ---------------------------------------*/ __HAL_RCC_HSE_CONFIG(RCC_OscInitStruct->HSEState); /* Check the HSE State */ if (RCC_OscInitStruct->HSEState != RCC_HSE_OFF) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSE is ready */ while (READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U) { if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } else { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSE is disabled */ while (READ_BIT(RCC->CR, RCC_CR_HSERDY) != 0U) { if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } } } /*----------------------------- HSI Configuration --------------------------*/ if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) { /* Check the parameters */ assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState)); assert_param(IS_RCC_HSI_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ temp_sysclksrc = __HAL_RCC_GET_SYSCLK_SOURCE(); temp_pllckcfg = __HAL_RCC_GET_PLL_OSCSOURCE(); if (((temp_sysclksrc == RCC_CFGR_SWS_PLL) && (temp_pllckcfg == RCC_PLLSOURCE_HSI)) || (temp_sysclksrc == RCC_CFGR_SWS_HSI)) { /* When HSI is used as system clock it will not be disabled */ if ((READ_BIT(RCC->CR, RCC_CR_HSIRDY) != 0U) && (RCC_OscInitStruct->HSIState == RCC_HSI_OFF)) { return HAL_ERROR; } /* Otherwise, just the calibration is allowed */ else { /* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/ __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue); /* Adapt Systick interrupt period */ if (HAL_InitTick(uwTickPrio) != HAL_OK) { return HAL_ERROR; } } } else { /* Check the HSI State */ if (RCC_OscInitStruct->HSIState != RCC_HSI_OFF) { /* Enable the Internal High Speed oscillator (HSI). */ __HAL_RCC_HSI_ENABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSI is ready */ while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U) { if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/ __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue); } else { /* Disable the Internal High Speed oscillator (HSI). */ __HAL_RCC_HSI_DISABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSI is disabled */ while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) != 0U) { if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } } } /*------------------------------ LSI Configuration -------------------------*/ if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) { /* Check the parameters */ assert_param(IS_RCC_LSI(RCC_OscInitStruct->LSIState)); /* Check the LSI State */ if(RCC_OscInitStruct->LSIState != RCC_LSI_OFF) { /* Enable the Internal Low Speed oscillator (LSI). */ __HAL_RCC_LSI_ENABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSI is ready */ while (READ_BIT(RCC->CSR, RCC_CSR_LSIRDY) == 0U) { if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } else { /* Disable the Internal Low Speed oscillator (LSI). */ __HAL_RCC_LSI_DISABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSI is disabled */ while(READ_BIT(RCC->CSR, RCC_CSR_LSIRDY) != 0U) { if((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } } /*------------------------------ LSE Configuration -------------------------*/ if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) { FlagStatus pwrclkchanged = RESET; /* Check the parameters */ assert_param(IS_RCC_LSE(RCC_OscInitStruct->LSEState)); /* Update LSE configuration in Backup Domain control register */ /* Requires to enable write access to Backup Domain if necessary */ if (__HAL_RCC_PWR_IS_CLK_DISABLED() != 0U) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } if (HAL_IS_BIT_CLR(PWR->CR1, PWR_CR1_DBP)) { /* Enable write access to Backup domain */ SET_BIT(PWR->CR1, PWR_CR1_DBP); /* Wait for Backup domain Write protection disable */ tickstart = HAL_GetTick(); while (HAL_IS_BIT_CLR(PWR->CR1, PWR_CR1_DBP)) { if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } /* Set the new LSE configuration -----------------------------------------*/ __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); /* Check the LSE State */ if (RCC_OscInitStruct->LSEState != RCC_LSE_OFF) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ while (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) == 0U) { if((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } else { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSE is disabled */ while (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) != 0U) { if((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } /* Restore clock configuration if changed */ if (pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } } /*------------------------------ HSI48 Configuration -----------------------*/ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48) { /* Check the parameters */ assert_param(IS_RCC_HSI48(RCC_OscInitStruct->HSI48State)); /* Check the HSI48 State */ if(RCC_OscInitStruct->HSI48State != RCC_HSI48_OFF) { /* Enable the Internal Low Speed oscillator (HSI48). */ __HAL_RCC_HSI48_ENABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSI48 is ready */ while(READ_BIT(RCC->CRRCR, RCC_CRRCR_HSI48RDY) == 0U) { if((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } else { /* Disable the Internal Low Speed oscillator (HSI48). */ __HAL_RCC_HSI48_DISABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSI48 is disabled */ while(READ_BIT(RCC->CRRCR, RCC_CRRCR_HSI48RDY) != 0U) { if((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } } /*-------------------------------- PLL Configuration -----------------------*/ /* Check the parameters */ assert_param(IS_RCC_PLL(RCC_OscInitStruct->PLL.PLLState)); if (RCC_OscInitStruct->PLL.PLLState != RCC_PLL_NONE) { /* Check if the PLL is used as system clock or not */ if (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) { if (RCC_OscInitStruct->PLL.PLLState == RCC_PLL_ON) { /* Check the parameters */ assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource)); assert_param(IS_RCC_PLLM_VALUE(RCC_OscInitStruct->PLL.PLLM)); assert_param(IS_RCC_PLLN_VALUE(RCC_OscInitStruct->PLL.PLLN)); assert_param(IS_RCC_PLLP_VALUE(RCC_OscInitStruct->PLL.PLLP)); assert_param(IS_RCC_PLLQ_VALUE(RCC_OscInitStruct->PLL.PLLQ)); assert_param(IS_RCC_PLLR_VALUE(RCC_OscInitStruct->PLL.PLLR)); /* Disable the main PLL. */ __HAL_RCC_PLL_DISABLE(); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till PLL is ready */ while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) != 0U) { if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Configure the main PLL clock source, multiplication and division factors. */ __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource, RCC_OscInitStruct->PLL.PLLM, RCC_OscInitStruct->PLL.PLLN, RCC_OscInitStruct->PLL.PLLP, RCC_OscInitStruct->PLL.PLLQ, RCC_OscInitStruct->PLL.PLLR); /* Enable the main PLL. */ __HAL_RCC_PLL_ENABLE(); /* Enable PLL System Clock output. */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_SYSCLK); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till PLL is ready */ while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) == 0U) { if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } else { /* Disable the main PLL. */ __HAL_RCC_PLL_DISABLE(); /* Disable all PLL outputs to save power if no PLLs on */ MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, RCC_PLLSOURCE_NONE); __HAL_RCC_PLLCLKOUT_DISABLE(RCC_PLL_SYSCLK | RCC_PLL_48M1CLK | RCC_PLL_ADCCLK); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till PLL is disabled */ while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) != 0U) { if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } } else { /* Check if there is a request to disable the PLL used as System clock source */ if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) { return HAL_ERROR; } else { /* Do not return HAL_ERROR if request repeats the current configuration */ temp_pllckcfg = RCC->PLLCFGR; if((READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLSRC) != RCC_OscInitStruct->PLL.PLLSource) || (READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLM) != (((RCC_OscInitStruct->PLL.PLLM) - 1U) << RCC_PLLCFGR_PLLM_Pos)) || (READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLN) != ((RCC_OscInitStruct->PLL.PLLN) << RCC_PLLCFGR_PLLN_Pos)) || (READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLPDIV) != ((RCC_OscInitStruct->PLL.PLLP) << RCC_PLLCFGR_PLLPDIV_Pos)) || (READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLQ) != ((((RCC_OscInitStruct->PLL.PLLQ) >> 1U) - 1U) << RCC_PLLCFGR_PLLQ_Pos)) || (READ_BIT(temp_pllckcfg, RCC_PLLCFGR_PLLR) != ((((RCC_OscInitStruct->PLL.PLLR) >> 1U) - 1U) << RCC_PLLCFGR_PLLR_Pos))) { return HAL_ERROR; } } } } return HAL_OK; } /** * @brief Initialize the CPU, AHB and APB buses clocks according to the specified * parameters in the RCC_ClkInitStruct. * @param RCC_ClkInitStruct pointer to an RCC_OscInitTypeDef structure that * contains the configuration information for the RCC peripheral. * @param FLatency FLASH Latency * This parameter can be one of the following values: * @arg FLASH_LATENCY_0 FLASH 0 Latency cycle * @arg FLASH_LATENCY_1 FLASH 1 Latency cycle * @arg FLASH_LATENCY_2 FLASH 2 Latency cycles * @arg FLASH_LATENCY_3 FLASH 3 Latency cycles * @arg FLASH_LATENCY_4 FLASH 4 Latency cycles * @arg FLASH_LATENCY_5 FLASH 5 Latency cycles * @arg FLASH_LATENCY_6 FLASH 6 Latency cycles * @arg FLASH_LATENCY_7 FLASH 7 Latency cycles * @arg FLASH_LATENCY_8 FLASH 8 Latency cycles * @arg FLASH_LATENCY_9 FLASH 9 Latency cycles * @arg FLASH_LATENCY_10 FLASH 10 Latency cycles * @arg FLASH_LATENCY_11 FLASH 11 Latency cycles * @arg FLASH_LATENCY_12 FLASH 12 Latency cycles * @arg FLASH_LATENCY_13 FLASH 13 Latency cycles * @arg FLASH_LATENCY_14 FLASH 14 Latency cycles * @arg FLASH_LATENCY_15 FLASH 15 Latency cycles * * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency * and updated by HAL_RCC_GetHCLKFreq() function called within this function * * @note The HSI is used by default as system clock source after * startup from Reset, wake-up from STANDBY mode. After restart from Reset, * the HSI frequency is set to its default value 16 MHz. * * @note The HSI can be selected as system clock source after * from STOP modes or in case of failure of the HSE used directly or indirectly * as system clock (if the Clock Security System CSS is enabled). * * @note A switch from one clock source to another occurs only if the target * clock source is ready (clock stable after startup delay or PLL locked). * If a clock source which is not yet ready is selected, the switch will * occur when the clock source is ready. * * @note You can use HAL_RCC_GetClockConfig() function to know which clock is * currently used as system clock source. * * @note Depending on the device voltage range, the software has to set correctly * HPRE[3:0] bits to ensure that HCLK not exceed the maximum allowed frequency * (for more details refer to section above "Initialization/de-initialization functions") * @retval None */ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) { uint32_t tickstart; uint32_t pllfreq; uint32_t hpre = RCC_SYSCLK_DIV1; /* Check Null pointer */ if (RCC_ClkInitStruct == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_RCC_CLOCKTYPE(RCC_ClkInitStruct->ClockType)); assert_param(IS_FLASH_LATENCY(FLatency)); /* To correctly read data from FLASH memory, the number of wait states (LATENCY) must be correctly programmed according to the frequency of the CPU clock (HCLK) and the supply voltage of the device. */ /* Increasing the number of wait states because of higher CPU frequency */ if (FLatency > __HAL_FLASH_GET_LATENCY()) { /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ __HAL_FLASH_SET_LATENCY(FLatency); /* Check that the new number of wait states is taken into account to access the Flash memory by reading the FLASH_ACR register */ if (__HAL_FLASH_GET_LATENCY() != FLatency) { return HAL_ERROR; } } /*------------------------- SYSCLK Configuration ---------------------------*/ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) { assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); /* PLL is selected as System Clock Source */ if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) { /* Check the PLL ready flag */ if (READ_BIT(RCC->CR, RCC_CR_PLLRDY) == 0U) { return HAL_ERROR; } /* Undershoot management when selection PLL as SYSCLK source and frequency above 80Mhz */ /* Compute target PLL output frequency */ pllfreq = RCC_GetSysClockFreqFromPLLSource(); /* Intermediate step with HCLK prescaler 2 necessary before to go over 80Mhz */ if(pllfreq > 80000000U) { if (((READ_BIT(RCC->CFGR, RCC_CFGR_HPRE) == RCC_SYSCLK_DIV1)) || (((((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) && (RCC_ClkInitStruct->AHBCLKDivider == RCC_SYSCLK_DIV1)))) { MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_SYSCLK_DIV2); hpre = RCC_SYSCLK_DIV2; } } } else { /* HSE is selected as System Clock Source */ if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) { /* Check the HSE ready flag */ if(READ_BIT(RCC->CR, RCC_CR_HSERDY) == 0U) { return HAL_ERROR; } } /* HSI is selected as System Clock Source */ else { /* Check the HSI ready flag */ if(READ_BIT(RCC->CR, RCC_CR_HSIRDY) == 0U) { return HAL_ERROR; } } /* Overshoot management when going down from PLL as SYSCLK source and frequency above 80Mhz */ pllfreq = HAL_RCC_GetSysClockFreq(); /* Intermediate step with HCLK prescaler 2 necessary before to go under 80Mhz */ if(pllfreq > 80000000U) { MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_SYSCLK_DIV2); hpre = RCC_SYSCLK_DIV2; } } MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource); /* Get Start Tick*/ tickstart = HAL_GetTick(); while (__HAL_RCC_GET_SYSCLK_SOURCE() != (RCC_ClkInitStruct->SYSCLKSource << RCC_CFGR_SWS_Pos)) { if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } /*-------------------------- HCLK Configuration --------------------------*/ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) { /* Set the highest APB divider in order to ensure that we do not go through a non-spec phase whatever we decrease or increase HCLK. */ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_HCLK_DIV16); } if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, RCC_HCLK_DIV16); } /* Set the new HCLK clock divider */ assert_param(IS_RCC_HCLK(RCC_ClkInitStruct->AHBCLKDivider)); MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider); } else { /* Is intermediate HCLK prescaler 2 applied internally, complete with HCLK prescaler 1 */ if(hpre == RCC_SYSCLK_DIV2) { MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_SYSCLK_DIV1); } } /* Decreasing the number of wait states because of lower CPU frequency */ if (FLatency < __HAL_FLASH_GET_LATENCY()) { /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ __HAL_FLASH_SET_LATENCY(FLatency); /* Check that the new number of wait states is taken into account to access the Flash memory by polling the FLASH_ACR register */ tickstart = HAL_GetTick(); while (__HAL_FLASH_GET_LATENCY() != FLatency) { if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } } /*-------------------------- PCLK1 Configuration ---------------------------*/ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) { assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB1CLKDivider)); MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_ClkInitStruct->APB1CLKDivider); } /*-------------------------- PCLK2 Configuration ---------------------------*/ if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) { assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB2CLKDivider)); MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, ((RCC_ClkInitStruct->APB2CLKDivider) << 3U)); } /* Update the SystemCoreClock global variable */ SystemCoreClock = HAL_RCC_GetSysClockFreq() >> (AHBPrescTable[READ_BIT(RCC->CFGR, RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos] & 0x1FU); /* Configure the source of time base considering new system clocks settings*/ return HAL_InitTick(uwTickPrio); } /** * @} */ /** @defgroup RCC_Exported_Functions_Group2 Peripheral Control functions * @brief RCC clocks control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to: (+) Output clock to MCO pin. (+) Retrieve current clock frequencies. (+) Enable the Clock Security System. @endverbatim * @{ */ /** * @brief Select the clock source to output on MCO pin(PA8/PG10). * @note PA8/PG10 should be configured in alternate function mode. * @note The default configuration of the GPIOG pin 10 (PG10) is set to reset mode (NRST pin) * and user shall set the NRST_MODE Bit in the FLASH OPTR register to be able to use it * as an MCO pin. * The @ref HAL_FLASHEx_OBProgram() API can be used to configure the NRST_MODE Bit value. * @param RCC_MCOx specifies the output direction for the clock source. * For STM32G4xx family this parameter can have only one value: * @arg @ref RCC_MCO_PA8 Clock source to output on MCO1 pin(PA8). * @arg @ref RCC_MCO_PG10 Clock source to output on MCO1 pin(PG10). * @param RCC_MCOSource specifies the clock source to output. * This parameter can be one of the following values: * @arg @ref RCC_MCO1SOURCE_NOCLOCK MCO output disabled, no clock on MCO * @arg @ref RCC_MCO1SOURCE_SYSCLK system clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_HSI HSI clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_HSE HSE clock selected as MCO sourcee * @arg @ref RCC_MCO1SOURCE_PLLCLK main PLL clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_LSI LSI clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_LSE LSE clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_HSI48 HSI48 clock selected as MCO source for devices with HSI48 * @param RCC_MCODiv specifies the MCO prescaler. * This parameter can be one of the following values: * @arg @ref RCC_MCODIV_1 no division applied to MCO clock * @arg @ref RCC_MCODIV_2 division by 2 applied to MCO clock * @arg @ref RCC_MCODIV_4 division by 4 applied to MCO clock * @arg @ref RCC_MCODIV_8 division by 8 applied to MCO clock * @arg @ref RCC_MCODIV_16 division by 16 applied to MCO clock * @retval None */ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) { GPIO_InitTypeDef gpio_initstruct; uint32_t mcoindex; uint32_t mco_gpio_index; GPIO_TypeDef * mco_gpio_port; /* Check the parameters */ assert_param(IS_RCC_MCO(RCC_MCOx)); /* Common GPIO init parameters */ gpio_initstruct.Mode = GPIO_MODE_AF_PP; gpio_initstruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; gpio_initstruct.Pull = GPIO_NOPULL; /* Get MCOx selection */ mcoindex = RCC_MCOx & RCC_MCO_INDEX_MASK; /* Get MCOx GPIO Port */ mco_gpio_port = (GPIO_TypeDef *) RCC_GET_MCO_GPIO_PORT(RCC_MCOx); /* MCOx Clock Enable */ mco_gpio_index = RCC_GET_MCO_GPIO_INDEX(RCC_MCOx); SET_BIT(RCC->AHB2ENR, (1UL << mco_gpio_index )); /* Configure the MCOx pin in alternate function mode */ gpio_initstruct.Pin = RCC_GET_MCO_GPIO_PIN(RCC_MCOx); gpio_initstruct.Alternate = RCC_GET_MCO_GPIO_AF(RCC_MCOx); HAL_GPIO_Init(mco_gpio_port, &gpio_initstruct); if (mcoindex == RCC_MCO1_INDEX) { assert_param(IS_RCC_MCODIV(RCC_MCODiv)); assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource)); /* Mask MCOSEL[] and MCOPRE[] bits then set MCO clock source and prescaler */ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE), (RCC_MCOSource | RCC_MCODiv)); } } /** * @brief Return the SYSCLK frequency. * * @note The system frequency computed by this function is not the real * frequency in the chip. It is calculated based on the predefined * constant and the selected clock source: * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*) * @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(**) * @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(**), * HSI_VALUE(*) Value multiplied/divided by the PLL factors. * @note (*) HSI_VALUE is a constant defined in stm32g4xx_hal_conf.h file (default value * 16 MHz) but the real value may vary depending on the variations * in voltage and temperature. * @note (**) HSE_VALUE is a constant defined in stm32g4xx_hal_conf.h file (default value * 8 MHz), user has to ensure that HSE_VALUE is same as the real * frequency of the crystal used. Otherwise, this function may * have wrong result. * * @note The result of this function could be not correct when using fractional * value for HSE crystal. * * @note This function can be used by the user application to compute the * baudrate for the communication peripherals or configure other parameters. * * @note Each time SYSCLK changes, this function must be called to update the * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect. * * * @retval SYSCLK frequency */ uint32_t HAL_RCC_GetSysClockFreq(void) { uint32_t pllvco, pllsource, pllr, pllm; uint32_t sysclockfreq; if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) { /* HSI used as system clock source */ sysclockfreq = HSI_VALUE; } else if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSE) { /* HSE used as system clock source */ sysclockfreq = HSE_VALUE; } else if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) { /* PLL used as system clock source */ /* PLL_VCO = ((HSE_VALUE or HSI_VALUE)/ PLLM) * PLLN SYSCLK = PLL_VCO / PLLR */ pllsource = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC); pllm = (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1U ; switch (pllsource) { case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */ pllvco = (HSE_VALUE / pllm) * (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos); break; case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */ default: pllvco = (HSI_VALUE / pllm) * (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos); break; } pllr = ((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos) + 1U ) * 2U; sysclockfreq = pllvco/pllr; } else { sysclockfreq = 0U; } return sysclockfreq; } /** * @brief Return the HCLK frequency. * @note Each time HCLK changes, this function must be called to update the * right HCLK value. Otherwise, any configuration based on this function will be incorrect. * * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency. * @retval HCLK frequency in Hz */ uint32_t HAL_RCC_GetHCLKFreq(void) { return SystemCoreClock; } /** * @brief Return the PCLK1 frequency. * @note Each time PCLK1 changes, this function must be called to update the * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect. * @retval PCLK1 frequency in Hz */ uint32_t HAL_RCC_GetPCLK1Freq(void) { /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/ return (HAL_RCC_GetHCLKFreq() >> (APBPrescTable[READ_BIT(RCC->CFGR, RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos] & 0x1FU)); } /** * @brief Return the PCLK2 frequency. * @note Each time PCLK2 changes, this function must be called to update the * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect. * @retval PCLK2 frequency in Hz */ uint32_t HAL_RCC_GetPCLK2Freq(void) { /* Get HCLK source and Compute PCLK2 frequency ---------------------------*/ return (HAL_RCC_GetHCLKFreq()>> (APBPrescTable[READ_BIT(RCC->CFGR, RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos] & 0x1FU)); } /** * @brief Configure the RCC_OscInitStruct according to the internal * RCC configuration registers. * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that * will be configured. * @retval None */ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { /* Check the parameters */ assert_param(RCC_OscInitStruct != (void *)NULL); /* Set all possible values for the Oscillator type parameter ---------------*/ RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | \ RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_HSI48; /* Get the HSE configuration -----------------------------------------------*/ if(READ_BIT(RCC->CR, RCC_CR_HSEBYP) == RCC_CR_HSEBYP) { RCC_OscInitStruct->HSEState = RCC_HSE_BYPASS; } else if(READ_BIT(RCC->CR, RCC_CR_HSEON) == RCC_CR_HSEON) { RCC_OscInitStruct->HSEState = RCC_HSE_ON; } else { RCC_OscInitStruct->HSEState = RCC_HSE_OFF; } /* Get the HSI configuration -----------------------------------------------*/ if(READ_BIT(RCC->CR, RCC_CR_HSION) == RCC_CR_HSION) { RCC_OscInitStruct->HSIState = RCC_HSI_ON; } else { RCC_OscInitStruct->HSIState = RCC_HSI_OFF; } RCC_OscInitStruct->HSICalibrationValue = READ_BIT(RCC->ICSCR, RCC_ICSCR_HSITRIM) >> RCC_ICSCR_HSITRIM_Pos; /* Get the LSE configuration -----------------------------------------------*/ if(READ_BIT(RCC->BDCR, RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) { RCC_OscInitStruct->LSEState = RCC_LSE_BYPASS; } else if(READ_BIT(RCC->BDCR, RCC_BDCR_LSEON) == RCC_BDCR_LSEON) { RCC_OscInitStruct->LSEState = RCC_LSE_ON; } else { RCC_OscInitStruct->LSEState = RCC_LSE_OFF; } /* Get the LSI configuration -----------------------------------------------*/ if(READ_BIT(RCC->CSR, RCC_CSR_LSION) == RCC_CSR_LSION) { RCC_OscInitStruct->LSIState = RCC_LSI_ON; } else { RCC_OscInitStruct->LSIState = RCC_LSI_OFF; } /* Get the HSI48 configuration ---------------------------------------------*/ if(READ_BIT(RCC->CRRCR, RCC_CRRCR_HSI48ON) == RCC_CRRCR_HSI48ON) { RCC_OscInitStruct->HSI48State = RCC_HSI48_ON; } else { RCC_OscInitStruct->HSI48State = RCC_HSI48_OFF; } /* Get the PLL configuration -----------------------------------------------*/ if(READ_BIT(RCC->CR, RCC_CR_PLLON) == RCC_CR_PLLON) { RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON; } else { RCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF; } RCC_OscInitStruct->PLL.PLLSource = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC); RCC_OscInitStruct->PLL.PLLM = (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1U; RCC_OscInitStruct->PLL.PLLN = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; RCC_OscInitStruct->PLL.PLLQ = (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); RCC_OscInitStruct->PLL.PLLR = (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos) + 1U) << 1U); RCC_OscInitStruct->PLL.PLLP = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLPDIV) >> RCC_PLLCFGR_PLLPDIV_Pos; } /** * @brief Configure the RCC_ClkInitStruct according to the internal * RCC configuration registers. * @param RCC_ClkInitStruct pointer to an RCC_ClkInitTypeDef structure that * will be configured. * @param pFLatency Pointer on the Flash Latency. * @retval None */ void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency) { /* Check the parameters */ assert_param(RCC_ClkInitStruct != (void *)NULL); assert_param(pFLatency != (void *)NULL); /* Set all possible values for the Clock type parameter --------------------*/ RCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; /* Get the SYSCLK configuration --------------------------------------------*/ RCC_ClkInitStruct->SYSCLKSource = READ_BIT(RCC->CFGR, RCC_CFGR_SW); /* Get the HCLK configuration ----------------------------------------------*/ RCC_ClkInitStruct->AHBCLKDivider = READ_BIT(RCC->CFGR, RCC_CFGR_HPRE); /* Get the APB1 configuration ----------------------------------------------*/ RCC_ClkInitStruct->APB1CLKDivider = READ_BIT(RCC->CFGR, RCC_CFGR_PPRE1); /* Get the APB2 configuration ----------------------------------------------*/ RCC_ClkInitStruct->APB2CLKDivider = (READ_BIT(RCC->CFGR, RCC_CFGR_PPRE2) >> 3U); /* Get the Flash Wait State (Latency) configuration ------------------------*/ *pFLatency = __HAL_FLASH_GET_LATENCY(); } /** * @brief Enable the Clock Security System. * @note If a failure is detected on the HSE oscillator clock, this oscillator * is automatically disabled and an interrupt is generated to inform the * software about the failure (Clock Security System Interrupt, CSSI), * allowing the MCU to perform rescue operations. The CSSI is linked to * the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector. * @note The Clock Security System can only be cleared by reset. * @retval None */ void HAL_RCC_EnableCSS(void) { SET_BIT(RCC->CR, RCC_CR_CSSON) ; } /** * @brief Enable the LSE Clock Security System. * @note If a failure is detected on the external 32 kHz oscillator, * the LSE clock is no longer supplied to the RTC but no hardware action * is made to the registers. If enabled, an interrupt will be generated * and handle through @ref RCCEx_EXTI_LINE_LSECSS * @note The Clock Security System can only be cleared by reset or after a LSE failure detection. * @retval None */ void HAL_RCC_EnableLSECSS(void) { SET_BIT(RCC->BDCR, RCC_BDCR_LSECSSON) ; } /** * @brief Disable the LSE Clock Security System. * @note After LSE failure detection, the software must disable LSECSSON * @note The Clock Security System can only be cleared by reset otherwise. * @retval None */ void HAL_RCC_DisableLSECSS(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSECSSON) ; } /** * @brief Handle the RCC Clock Security System interrupt request. * @note This API should be called under the NMI_Handler(). * @retval None */ void HAL_RCC_NMI_IRQHandler(void) { /* Check RCC CSSF interrupt flag */ if(__HAL_RCC_GET_IT(RCC_IT_CSS)) { /* RCC Clock Security System interrupt user callback */ HAL_RCC_CSSCallback(); /* Clear RCC CSS pending bit */ __HAL_RCC_CLEAR_IT(RCC_IT_CSS); } } /** * @brief RCC Clock Security System interrupt callback. * @retval none */ __weak void HAL_RCC_CSSCallback(void) { /* NOTE : This function should not be modified, when the callback is needed, the HAL_RCC_CSSCallback should be implemented in the user file */ } /** * @} */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ /** @addtogroup RCC_Private_Functions * @{ */ /** * @brief Compute SYSCLK frequency based on PLL SYSCLK source. * @retval SYSCLK frequency */ static uint32_t RCC_GetSysClockFreqFromPLLSource(void) { uint32_t pllvco, pllsource, pllr, pllm; uint32_t sysclockfreq; /* PLL_VCO = (HSE_VALUE or HSI_VALUE/ PLLM) * PLLN SYSCLK = PLL_VCO / PLLR */ pllsource = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC); pllm = (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1U ; switch (pllsource) { case RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */ pllvco = (HSE_VALUE / pllm) * (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos); break; case RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */ default: pllvco = (HSI_VALUE / pllm) * (READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos); break; } pllr = ((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos) + 1U ) * 2U; sysclockfreq = pllvco/pllr; return sysclockfreq; } /** * @} */ #endif /* HAL_RCC_MODULE_ENABLED */ /** * @} */ /** * @} */
51,161
C
35.492154
130
0.584039
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_dma_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_dma_ex.c * @author MCD Application Team * @brief DMA Extension HAL module driver * This file provides firmware functions to manage the following * functionalities of the DMA Extension peripheral: * + 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 ============================================================================== ##### How to use this driver ##### ============================================================================== [..] The DMA Extension HAL driver can be used as follows: (+) Configure the DMA_MUX Synchronization Block using HAL_DMAEx_ConfigMuxSync function. (+) Configure the DMA_MUX Request Generator Block using HAL_DMAEx_ConfigMuxRequestGenerator function. Functions HAL_DMAEx_EnableMuxRequestGenerator and HAL_DMAEx_DisableMuxRequestGenerator can then be used to respectively enable/disable the request generator. (+) To handle the DMAMUX Interrupts, the function HAL_DMAEx_MUX_IRQHandler should be called from the DMAMUX IRQ handler i.e DMAMUX1_OVR_IRQHandler. As only one interrupt line is available for all DMAMUX channels and request generators , HAL_DMAEx_MUX_IRQHandler should be called with, as parameter, the appropriate DMA handle as many as used DMAs in the user project (exception done if a given DMA is not using the DMAMUX SYNC block neither a request generator) @endverbatim */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup DMAEx DMAEx * @brief DMA Extended HAL module driver * @{ */ #ifdef HAL_DMA_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private Constants ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Functions DMAEx Exported Functions * @{ */ /** @defgroup DMAEx_Exported_Functions_Group1 DMAEx Extended features functions * @brief Extended features functions * @verbatim =============================================================================== ##### Extended features functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Configure the DMAMUX Synchronization Block using HAL_DMAEx_ConfigMuxSync function. (+) Configure the DMAMUX Request Generator Block using HAL_DMAEx_ConfigMuxRequestGenerator function. Functions HAL_DMAEx_EnableMuxRequestGenerator and HAL_DMAEx_DisableMuxRequestGenerator can then be used to respectively enable/disable the request generator. @endverbatim * @{ */ /** * @brief Configure the DMAMUX synchronization parameters for a given DMA channel (instance). * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA channel. * @param pSyncConfig : pointer to HAL_DMA_MuxSyncConfigTypeDef : contains the DMAMUX synchronization parameters * @retval HAL status */ HAL_StatusTypeDef HAL_DMAEx_ConfigMuxSync(DMA_HandleTypeDef *hdma, HAL_DMA_MuxSyncConfigTypeDef *pSyncConfig) { /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); assert_param(IS_DMAMUX_SYNC_SIGNAL_ID(pSyncConfig->SyncSignalID)); assert_param(IS_DMAMUX_SYNC_POLARITY(pSyncConfig-> SyncPolarity)); assert_param(IS_DMAMUX_SYNC_STATE(pSyncConfig->SyncEnable)); assert_param(IS_DMAMUX_SYNC_EVENT(pSyncConfig->EventEnable)); assert_param(IS_DMAMUX_SYNC_REQUEST_NUMBER(pSyncConfig->RequestNumber)); /*Check if the DMA state is ready */ if (hdma->State == HAL_DMA_STATE_READY) { /* Process Locked */ __HAL_LOCK(hdma); /* Set the new synchronization parameters (and keep the request ID filled during the Init)*/ MODIFY_REG(hdma->DMAmuxChannel->CCR, \ (~DMAMUX_CxCR_DMAREQ_ID), \ ((pSyncConfig->SyncSignalID) << DMAMUX_CxCR_SYNC_ID_Pos) | ((pSyncConfig->RequestNumber - 1U) << DMAMUX_CxCR_NBREQ_Pos) | \ pSyncConfig->SyncPolarity | ((uint32_t)pSyncConfig->SyncEnable << DMAMUX_CxCR_SE_Pos) | \ ((uint32_t)pSyncConfig->EventEnable << DMAMUX_CxCR_EGE_Pos)); /* Process UnLocked */ __HAL_UNLOCK(hdma); return HAL_OK; } else { /*DMA State not Ready*/ return HAL_ERROR; } } /** * @brief Configure the DMAMUX request generator block used by the given DMA channel (instance). * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA channel. * @param pRequestGeneratorConfig : pointer to HAL_DMA_MuxRequestGeneratorConfigTypeDef : * contains the request generator parameters. * * @retval HAL status */ HAL_StatusTypeDef HAL_DMAEx_ConfigMuxRequestGenerator(DMA_HandleTypeDef *hdma, HAL_DMA_MuxRequestGeneratorConfigTypeDef *pRequestGeneratorConfig) { /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); assert_param(IS_DMAMUX_REQUEST_GEN_SIGNAL_ID(pRequestGeneratorConfig->SignalID)); assert_param(IS_DMAMUX_REQUEST_GEN_POLARITY(pRequestGeneratorConfig->Polarity)); assert_param(IS_DMAMUX_REQUEST_GEN_REQUEST_NUMBER(pRequestGeneratorConfig->RequestNumber)); /* check if the DMA state is ready and DMA is using a DMAMUX request generator block */ if ((hdma->State == HAL_DMA_STATE_READY) && (hdma->DMAmuxRequestGen != 0U)) { /* Process Locked */ __HAL_LOCK(hdma); /* Set the request generator new parameters */ hdma->DMAmuxRequestGen->RGCR = pRequestGeneratorConfig->SignalID | \ ((pRequestGeneratorConfig->RequestNumber - 1U) << (POSITION_VAL(DMAMUX_RGxCR_GNBREQ) & 0x1FU)) | \ pRequestGeneratorConfig->Polarity; /* Process UnLocked */ __HAL_UNLOCK(hdma); return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Enable the DMAMUX request generator block used by the given DMA channel (instance). * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMAEx_EnableMuxRequestGenerator(DMA_HandleTypeDef *hdma) { /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); /* check if the DMA state is ready and DMA is using a DMAMUX request generator block */ if ((hdma->State != HAL_DMA_STATE_RESET) && (hdma->DMAmuxRequestGen != 0)) { /* Enable the request generator*/ hdma->DMAmuxRequestGen->RGCR |= DMAMUX_RGxCR_GE; return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Disable the DMAMUX request generator block used by the given DMA channel (instance). * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMAEx_DisableMuxRequestGenerator(DMA_HandleTypeDef *hdma) { /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); /* check if the DMA state is ready and DMA is using a DMAMUX request generator block */ if ((hdma->State != HAL_DMA_STATE_RESET) && (hdma->DMAmuxRequestGen != 0)) { /* Disable the request generator*/ hdma->DMAmuxRequestGen->RGCR &= ~DMAMUX_RGxCR_GE; return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Handles DMAMUX interrupt request. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA channel. * @retval None */ void HAL_DMAEx_MUX_IRQHandler(DMA_HandleTypeDef *hdma) { /* Check for DMAMUX Synchronization overrun */ if ((hdma->DMAmuxChannelStatus->CSR & hdma->DMAmuxChannelStatusMask) != 0U) { /* Disable the synchro overrun interrupt */ hdma->DMAmuxChannel->CCR &= ~DMAMUX_CxCR_SOIE; /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_SYNC; if (hdma->XferErrorCallback != NULL) { /* Transfer error callback */ hdma->XferErrorCallback(hdma); } } if (hdma->DMAmuxRequestGen != 0) { /* if using a DMAMUX request generator block Check for DMAMUX request generator overrun */ if ((hdma->DMAmuxRequestGenStatus->RGSR & hdma->DMAmuxRequestGenStatusMask) != 0U) { /* Disable the request gen overrun interrupt */ hdma->DMAmuxRequestGen->RGCR &= ~DMAMUX_RGxCR_OIE; /* Clear the DMAMUX request generator overrun flag */ hdma->DMAmuxRequestGenStatus->RGCFR = hdma->DMAmuxRequestGenStatusMask; /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_REQGEN; if (hdma->XferErrorCallback != NULL) { /* Transfer error callback */ hdma->XferErrorCallback(hdma); } } } } /** * @} */ /** * @} */ #endif /* HAL_DMA_MODULE_ENABLED */ /** * @} */ /** * @} */
10,365
C
33.668896
138
0.606753
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_hal_exti.c
/** ****************************************************************************** * @file stm32g4xx_hal_exti.c * @author MCD Application Team * @brief EXTI HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Extended Interrupts and events controller (EXTI) peripheral: * functionalities of the General Purpose Input/Output (EXTI) peripheral: * + Initialization and de-initialization 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 ============================================================================== ##### EXTI Peripheral features ##### ============================================================================== [..] (+) Each Exti line can be configured within this driver. (+) Exti line can be configured in 3 different modes (++) Interrupt (++) Event (++) Both of them (+) Configurable Exti lines can be configured with 3 different triggers (++) Rising (++) Falling (++) Both of them (+) When set in interrupt mode, configurable Exti lines have two different interrupt pending registers which allow to distinguish which transition occurs: (++) Rising edge pending interrupt (++) Falling (+) Exti lines 0 to 15 are linked to gpio pin number 0 to 15. Gpio port can be selected through multiplexer. ##### How to use this driver ##### ============================================================================== [..] (#) Configure the EXTI line using HAL_EXTI_SetConfigLine(). (++) Choose the interrupt line number by setting "Line" member from EXTI_ConfigTypeDef structure. (++) Configure the interrupt and/or event mode using "Mode" member from EXTI_ConfigTypeDef structure. (++) For configurable lines, configure rising and/or falling trigger "Trigger" member from EXTI_ConfigTypeDef structure. (++) For Exti lines linked to gpio, choose gpio port using "GPIOSel" member from GPIO_InitTypeDef structure. (#) Get current Exti configuration of a dedicated line using HAL_EXTI_GetConfigLine(). (++) Provide exiting handle as parameter. (++) Provide pointer on EXTI_ConfigTypeDef structure as second parameter. (#) Clear Exti configuration of a dedicated line using HAL_EXTI_GetConfigLine(). (++) Provide exiting handle as parameter. (#) Register callback to treat Exti interrupts using HAL_EXTI_RegisterCallback(). (++) Provide exiting handle as first parameter. (++) Provide which callback will be registered using one value from EXTI_CallbackIDTypeDef. (++) Provide callback function pointer. (#) Get interrupt pending bit using HAL_EXTI_GetPending(). (#) Clear interrupt pending bit using HAL_EXTI_ClearPending(). (#) Generate software interrupt using HAL_EXTI_GenerateSWI(). @endverbatim */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup EXTI * @{ */ /** MISRA C:2012 deviation rule has been granted for following rule: * Rule-18.1_b - Medium: Array `EXTICR' 1st subscript interval [0,7] may be out * of bounds [0,3] in following API : * HAL_EXTI_SetConfigLine * HAL_EXTI_GetConfigLine * HAL_EXTI_ClearConfigLine */ #ifdef HAL_EXTI_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private defines ------------------------------------------------------------*/ /** @defgroup EXTI_Private_Constants EXTI Private Constants * @{ */ #define EXTI_MODE_OFFSET 0x08U /* 0x20: offset between MCU IMR/EMR registers */ #define EXTI_CONFIG_OFFSET 0x08U /* 0x20: offset between MCU Rising/Falling configuration registers */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup EXTI_Exported_Functions * @{ */ /** @addtogroup EXTI_Exported_Functions_Group1 * @brief Configuration functions * @verbatim =============================================================================== ##### Configuration functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Set configuration of a dedicated Exti line. * @param hexti Exti handle. * @param pExtiConfig Pointer on EXTI configuration to be set. * @retval HAL Status. */ HAL_StatusTypeDef HAL_EXTI_SetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) { __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; uint32_t offset; /* Check null pointer */ if ((hexti == NULL) || (pExtiConfig == NULL)) { return HAL_ERROR; } /* Check parameters */ assert_param(IS_EXTI_LINE(pExtiConfig->Line)); assert_param(IS_EXTI_MODE(pExtiConfig->Mode)); /* Assign line number to handle */ hexti->Line = pExtiConfig->Line; /* Compute line register offset */ offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* Compute line position */ linepos = (pExtiConfig->Line & EXTI_PIN_MASK); /* Compute line mask */ maskline = (1uL << linepos); /* Configure triggers for configurable lines */ if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) { assert_param(IS_EXTI_TRIGGER(pExtiConfig->Trigger)); /* Configure rising trigger */ regaddr = (&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = *regaddr; /* Mask or set line */ if ((pExtiConfig->Trigger & EXTI_TRIGGER_RISING) != 0x00u) { regval |= maskline; } else { regval &= ~maskline; } /* Store rising trigger mode */ *regaddr = regval; /* Configure falling trigger */ regaddr = (&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = *regaddr; /* Mask or set line */ if ((pExtiConfig->Trigger & EXTI_TRIGGER_FALLING) != 0x00u) { regval |= maskline; } else { regval &= ~maskline; } /* Store falling trigger mode */ *regaddr = regval; /* Configure gpio port selection in case of gpio exti line */ if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) { assert_param(IS_EXTI_GPIO_PORT(pExtiConfig->GPIOSel)); assert_param(IS_EXTI_GPIO_PIN(linepos)); regval = SYSCFG->EXTICR[linepos >> 2u]; regval &= ~(SYSCFG_EXTICR1_EXTI0 << (SYSCFG_EXTICR1_EXTI1_Pos * (linepos & 0x03u))); regval |= (pExtiConfig->GPIOSel << (SYSCFG_EXTICR1_EXTI1_Pos * (linepos & 0x03u))); SYSCFG->EXTICR[linepos >> 2u] = regval; } } /* Configure interrupt mode : read current mode */ regaddr = (&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); regval = *regaddr; /* Mask or set line */ if ((pExtiConfig->Mode & EXTI_MODE_INTERRUPT) != 0x00u) { regval |= maskline; } else { regval &= ~maskline; } /* Store interrupt mode */ *regaddr = regval; /* Configure event mode : read current mode */ regaddr = (&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); regval = *regaddr; /* Mask or set line */ if ((pExtiConfig->Mode & EXTI_MODE_EVENT) != 0x00u) { regval |= maskline; } else { regval &= ~maskline; } /* Store event mode */ *regaddr = regval; return HAL_OK; } /** * @brief Get configuration of a dedicated Exti line. * @param hexti Exti handle. * @param pExtiConfig Pointer on structure to store Exti configuration. * @retval HAL Status. */ HAL_StatusTypeDef HAL_EXTI_GetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) { __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; uint32_t offset; /* Check null pointer */ if ((hexti == NULL) || (pExtiConfig == NULL)) { return HAL_ERROR; } /* Check the parameter */ assert_param(IS_EXTI_LINE(hexti->Line)); /* Store handle line number to configuration structure */ pExtiConfig->Line = hexti->Line; /* Compute line register offset and line mask */ offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* Compute line position */ linepos = (pExtiConfig->Line & EXTI_PIN_MASK); /* Compute mask */ maskline = (1uL << linepos); /* 1] Get core mode : interrupt */ regaddr = (&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); regval = *regaddr; /* Check if selected line is enable */ if ((regval & maskline) != 0x00u) { pExtiConfig->Mode = EXTI_MODE_INTERRUPT; } else { pExtiConfig->Mode = EXTI_MODE_NONE; } /* Get event mode */ regaddr = (&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); regval = *regaddr; /* Check if selected line is enable */ if ((regval & maskline) != 0x00u) { pExtiConfig->Mode |= EXTI_MODE_EVENT; } /* Get default Trigger and GPIOSel configuration */ pExtiConfig->Trigger = EXTI_TRIGGER_NONE; pExtiConfig->GPIOSel = 0x00u; /* 2] Get trigger for configurable lines : rising */ if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) { regaddr = (&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = *regaddr; /* Check if configuration of selected line is enable */ if ((regval & maskline) != 0x00u) { pExtiConfig->Trigger = EXTI_TRIGGER_RISING; } /* Get falling configuration */ regaddr = (&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = *regaddr; /* Check if configuration of selected line is enable */ if ((regval & maskline) != 0x00u) { pExtiConfig->Trigger |= EXTI_TRIGGER_FALLING; } /* Get Gpio port selection for gpio lines */ if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) { assert_param(IS_EXTI_GPIO_PIN(linepos)); regval = SYSCFG->EXTICR[linepos >> 2u]; pExtiConfig->GPIOSel = ((regval >> (SYSCFG_EXTICR1_EXTI1_Pos * ((linepos & 0x03u))))); } } return HAL_OK; } /** * @brief Clear whole configuration of a dedicated Exti line. * @param hexti Exti handle. * @retval HAL Status. */ HAL_StatusTypeDef HAL_EXTI_ClearConfigLine(EXTI_HandleTypeDef *hexti) { __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; uint32_t offset; /* Check null pointer */ if (hexti == NULL) { return HAL_ERROR; } /* Check the parameter */ assert_param(IS_EXTI_LINE(hexti->Line)); /* compute line register offset and line mask */ offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* compute line position */ linepos = (hexti->Line & EXTI_PIN_MASK); /* compute line mask */ maskline = (1uL << linepos); /* 1] Clear interrupt mode */ regaddr = (&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); regval = (*regaddr & ~maskline); *regaddr = regval; /* 2] Clear event mode */ regaddr = (&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); regval = (*regaddr & ~maskline); *regaddr = regval; /* 3] Clear triggers in case of configurable lines */ if ((hexti->Line & EXTI_CONFIG) != 0x00u) { regaddr = (&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = (*regaddr & ~maskline); *regaddr = regval; regaddr = (&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); regval = (*regaddr & ~maskline); *regaddr = regval; /* Get Gpio port selection for gpio lines */ if ((hexti->Line & EXTI_GPIO) == EXTI_GPIO) { assert_param(IS_EXTI_GPIO_PIN(linepos)); regval = SYSCFG->EXTICR[linepos >> 2u]; regval &= ~(SYSCFG_EXTICR1_EXTI0 << (SYSCFG_EXTICR1_EXTI1_Pos * (linepos & 0x03u))); SYSCFG->EXTICR[linepos >> 2u] = regval; } } return HAL_OK; } /** * @brief Register callback for a dedicated Exti line. * @param hexti Exti handle. * @param CallbackID User callback identifier. * This parameter can be one of @arg @ref EXTI_CallbackIDTypeDef values. * @param pPendingCbfn function pointer to be stored as callback. * @retval HAL Status. */ HAL_StatusTypeDef HAL_EXTI_RegisterCallback(EXTI_HandleTypeDef *hexti, EXTI_CallbackIDTypeDef CallbackID, void (*pPendingCbfn)(void)) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_EXTI_CB(CallbackID)); switch (CallbackID) { /* set common callback */ case HAL_EXTI_COMMON_CB_ID: hexti->PendingCallback = pPendingCbfn; break; default: hexti->PendingCallback = NULL; status = HAL_ERROR; break; } return status; } /** * @brief Store line number as handle private field. * @param hexti Exti handle. * @param ExtiLine Exti line number. * This parameter can be from 0 to @ref EXTI_LINE_NB. * @retval HAL Status. */ HAL_StatusTypeDef HAL_EXTI_GetHandle(EXTI_HandleTypeDef *hexti, uint32_t ExtiLine) { /* Check the parameters */ assert_param(IS_EXTI_LINE(ExtiLine)); /* Check null pointer */ if (hexti == NULL) { return HAL_ERROR; } else { /* Store line number as handle private field */ hexti->Line = ExtiLine; return HAL_OK; } } /** * @} */ /** @addtogroup EXTI_Exported_Functions_Group2 * @brief EXTI IO functions. * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Handle EXTI interrupt request. * @param hexti Exti handle. * @retval none. */ void HAL_EXTI_IRQHandler(EXTI_HandleTypeDef *hexti) { __IO uint32_t *regaddr; uint32_t regval; uint32_t maskline; uint32_t offset; /* Compute line register offset */ offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* compute line mask */ maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); /* Get pending bit */ regaddr = (&EXTI->PR1 + (EXTI_CONFIG_OFFSET * offset)); regval = (*regaddr & maskline); if (regval != 0x00u) { /* Clear pending bit */ *regaddr = maskline; /* Call pending callback */ if (hexti->PendingCallback != NULL) { hexti->PendingCallback(); } } } /** * @brief Get interrupt pending bit of a dedicated line. * @param hexti Exti handle. * @param Edge unused * @retval 1 if interrupt is pending else 0. */ uint32_t HAL_EXTI_GetPending(EXTI_HandleTypeDef *hexti, uint32_t Edge) { __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; uint32_t offset; /* Check parameters */ assert_param(IS_EXTI_LINE(hexti->Line)); assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); UNUSED(Edge); /* Compute line register offset */ offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* Compute line position */ linepos = (hexti->Line & EXTI_PIN_MASK); /* Compute line mask */ maskline = (1uL << linepos); /* Get pending bit */ regaddr = (&EXTI->PR1 + (EXTI_CONFIG_OFFSET * offset)); /* return 1 if bit is set else 0 */ regval = ((*regaddr & maskline) >> linepos); return regval; } /** * @brief Clear interrupt pending bit of a dedicated line. * @param hexti Exti handle. * @param Edge unused * @retval None. */ void HAL_EXTI_ClearPending(EXTI_HandleTypeDef *hexti, uint32_t Edge) { __IO uint32_t *regaddr; uint32_t maskline; uint32_t offset; /* Check parameters */ assert_param(IS_EXTI_LINE(hexti->Line)); assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); UNUSED(Edge); /* Compute line register offset */ offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* Compute line mask */ maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); /* Get pending register address */ regaddr = (&EXTI->PR1 + (EXTI_CONFIG_OFFSET * offset)); /* Clear Pending bit */ *regaddr = maskline; } /** * @brief Generate a software interrupt for a dedicated line. * @param hexti Exti handle. * @retval None. */ void HAL_EXTI_GenerateSWI(EXTI_HandleTypeDef *hexti) { __IO uint32_t *regaddr; uint32_t maskline; uint32_t offset; /* Check parameter */ assert_param(IS_EXTI_LINE(hexti->Line)); assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); /* compute line register offset */ offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); /* compute line mask */ maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); regaddr = (&EXTI->SWIER1 + (EXTI_CONFIG_OFFSET * offset)); *regaddr = maskline; } /** * @} */ /** * @} */ #endif /* HAL_EXTI_MODULE_ENABLED */ /** * @} */ /** * @} */
17,426
C
26.229687
133
0.584988
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_pwr_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_pwr_ex.c * @author MCD Application Team * @brief Extended PWR HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Power Controller (PWR) peripheral: * + Extended Initialization and de-initialization functions * + Extended 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup PWREx PWREx * @brief PWR Extended HAL module driver * @{ */ #ifdef HAL_PWR_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G474xx) || defined (STM32G483xx) || defined (STM32G484xx) #define PWR_PORTF_AVAILABLE_PINS 0x0000FFFFU /* PF0..PF15 */ #define PWR_PORTG_AVAILABLE_PINS 0x000007FFU /* PG0..PG10 */ #elif defined (STM32G431xx) || defined (STM32G441xx) || defined (STM32GBK1CB) || defined (STM32G491xx) || defined (STM32G4A1xx) #define PWR_PORTF_AVAILABLE_PINS 0x00000607U /* PF0..PF2 and PF9 and PF10 */ #define PWR_PORTG_AVAILABLE_PINS 0x00000400U /* PG10 */ #endif /** @defgroup PWR_Extended_Private_Defines PWR Extended Private Defines * @{ */ /** @defgroup PWREx_PVM_Mode_Mask PWR PVM Mode Mask * @{ */ #define PVM_MODE_IT 0x00010000U /*!< Mask for interruption yielded by PVM threshold crossing */ #define PVM_MODE_EVT 0x00020000U /*!< Mask for event yielded by PVM threshold crossing */ #define PVM_RISING_EDGE 0x00000001U /*!< Mask for rising edge set as PVM trigger */ #define PVM_FALLING_EDGE 0x00000002U /*!< Mask for falling edge set as PVM trigger */ /** * @} */ /** @defgroup PWREx_TimeOut_Value PWR Extended Flag Setting Time Out Value * @{ */ #define PWR_FLAG_SETTING_DELAY_US 50UL /*!< Time out value for REGLPF and VOSF flags setting */ /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Functions PWR Extended Exported Functions * @{ */ /** @defgroup PWREx_Exported_Functions_Group1 Extended Peripheral Control functions * @brief Extended Peripheral Control functions * @verbatim =============================================================================== ##### Extended Peripheral Initialization and de-initialization functions ##### =============================================================================== [..] @endverbatim * @{ */ /** * @brief Return Voltage Scaling Range. * @retval VOS bit field (PWR_REGULATOR_VOLTAGE_SCALE1 or PWR_REGULATOR_VOLTAGE_SCALE2 * or PWR_REGULATOR_VOLTAGE_SCALE1_BOOST when applicable) */ uint32_t HAL_PWREx_GetVoltageRange(void) { if (READ_BIT(PWR->CR1, PWR_CR1_VOS) == PWR_REGULATOR_VOLTAGE_SCALE2) { return PWR_REGULATOR_VOLTAGE_SCALE2; } else if (READ_BIT(PWR->CR5, PWR_CR5_R1MODE) == PWR_CR5_R1MODE) { /* PWR_CR5_R1MODE bit set means that Range 1 Boost is disabled */ return PWR_REGULATOR_VOLTAGE_SCALE1; } else { return PWR_REGULATOR_VOLTAGE_SCALE1_BOOST; } } /** * @brief Configure the main internal regulator output voltage. * @param VoltageScaling: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption. * This parameter can be one of the following values: * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE1_BOOST when available, Regulator voltage output range 1 boost mode, * typical output voltage at 1.28 V, * system frequency up to 170 MHz. * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE1 Regulator voltage output range 1 mode, * typical output voltage at 1.2 V, * system frequency up to 150 MHz. * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE2 Regulator voltage output range 2 mode, * typical output voltage at 1.0 V, * system frequency up to 26 MHz. * @note When moving from Range 1 to Range 2, the system frequency must be decreased to * a value below 26 MHz before calling HAL_PWREx_ControlVoltageScaling() API. * When moving from Range 2 to Range 1, the system frequency can be increased to * a value up to 150 MHz after calling HAL_PWREx_ControlVoltageScaling() API. * When moving from Range 1 to Boost Mode Range 1, the system frequency can be increased to * a value up to 170 MHz after calling HAL_PWREx_ControlVoltageScaling() API. * @note When moving from Range 2 to Range 1, the API waits for VOSF flag to be * cleared before returning the status. If the flag is not cleared within * 50 microseconds, HAL_TIMEOUT status is reported. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling) { uint32_t wait_loop_index; assert_param(IS_PWR_VOLTAGE_SCALING_RANGE(VoltageScaling)); if (VoltageScaling == PWR_REGULATOR_VOLTAGE_SCALE1_BOOST) { /* If current range is range 2 */ if (READ_BIT(PWR->CR1, PWR_CR1_VOS) == PWR_REGULATOR_VOLTAGE_SCALE2) { /* Make sure Range 1 Boost is enabled */ CLEAR_BIT(PWR->CR5, PWR_CR5_R1MODE); /* Set Range 1 */ MODIFY_REG(PWR->CR1, PWR_CR1_VOS, PWR_REGULATOR_VOLTAGE_SCALE1); /* Wait until VOSF is cleared */ wait_loop_index = ((PWR_FLAG_SETTING_DELAY_US * SystemCoreClock) / 1000000U) + 1U; while ((HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_VOSF)) && (wait_loop_index != 0U)) { wait_loop_index--; } if (HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_VOSF)) { return HAL_TIMEOUT; } } /* If current range is range 1 normal or boost mode */ else { /* Enable Range 1 Boost (no issue if bit already reset) */ CLEAR_BIT(PWR->CR5, PWR_CR5_R1MODE); } } else if (VoltageScaling == PWR_REGULATOR_VOLTAGE_SCALE1) { /* If current range is range 2 */ if (READ_BIT(PWR->CR1, PWR_CR1_VOS) == PWR_REGULATOR_VOLTAGE_SCALE2) { /* Make sure Range 1 Boost is disabled */ SET_BIT(PWR->CR5, PWR_CR5_R1MODE); /* Set Range 1 */ MODIFY_REG(PWR->CR1, PWR_CR1_VOS, PWR_REGULATOR_VOLTAGE_SCALE1); /* Wait until VOSF is cleared */ wait_loop_index = ((PWR_FLAG_SETTING_DELAY_US * SystemCoreClock) / 1000000U) + 1U; while ((HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_VOSF)) && (wait_loop_index != 0U)) { wait_loop_index--; } if (HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_VOSF)) { return HAL_TIMEOUT; } } /* If current range is range 1 normal or boost mode */ else { /* Disable Range 1 Boost (no issue if bit already set) */ SET_BIT(PWR->CR5, PWR_CR5_R1MODE); } } else { /* Set Range 2 */ MODIFY_REG(PWR->CR1, PWR_CR1_VOS, PWR_REGULATOR_VOLTAGE_SCALE2); /* No need to wait for VOSF to be cleared for this transition */ /* PWR_CR5_R1MODE bit setting has no effect in Range 2 */ } return HAL_OK; } /** * @brief Enable battery charging. * When VDD is present, charge the external battery on VBAT through an internal resistor. * @param ResistorSelection: specifies the resistor impedance. * This parameter can be one of the following values: * @arg @ref PWR_BATTERY_CHARGING_RESISTOR_5 5 kOhms resistor * @arg @ref PWR_BATTERY_CHARGING_RESISTOR_1_5 1.5 kOhms resistor * @retval None */ void HAL_PWREx_EnableBatteryCharging(uint32_t ResistorSelection) { assert_param(IS_PWR_BATTERY_RESISTOR_SELECT(ResistorSelection)); /* Specify resistor selection */ MODIFY_REG(PWR->CR4, PWR_CR4_VBRS, ResistorSelection); /* Enable battery charging */ SET_BIT(PWR->CR4, PWR_CR4_VBE); } /** * @brief Disable battery charging. * @retval None */ void HAL_PWREx_DisableBatteryCharging(void) { CLEAR_BIT(PWR->CR4, PWR_CR4_VBE); } /** * @brief Enable Internal Wake-up Line. * @retval None */ void HAL_PWREx_EnableInternalWakeUpLine(void) { SET_BIT(PWR->CR3, PWR_CR3_EIWF); } /** * @brief Disable Internal Wake-up Line. * @retval None */ void HAL_PWREx_DisableInternalWakeUpLine(void) { CLEAR_BIT(PWR->CR3, PWR_CR3_EIWF); } /** * @brief Enable GPIO pull-up state in Standby and Shutdown modes. * @note Set the relevant PUy bits of PWR_PUCRx register to configure the I/O in * pull-up state in Standby and Shutdown modes. * @note This state is effective in Standby and Shutdown modes only if APC bit * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. * @note The configuration is lost when exiting the Shutdown mode due to the * power-on reset, maintained when exiting the Standby mode. * @note To avoid any conflict at Standby and Shutdown modes exits, the corresponding * PDy bit of PWR_PDCRx register is cleared unless it is reserved. * @note Even if a PUy bit to set is reserved, the other PUy bits entered as input * parameter at the same time are set. * @param GPIO: Specify the IO port. This parameter can be PWR_GPIO_A, ..., PWR_GPIO_G * (or PWR_GPIO_I depending on the devices) to select the GPIO peripheral. * @param GPIONumber: Specify the I/O pins numbers. * This parameter can be one of the following values: * PWR_GPIO_BIT_0, ..., PWR_GPIO_BIT_15 (except for the port where less * I/O pins are available) or the logical OR of several of them to set * several bits for a given port in a single API call. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber) { HAL_StatusTypeDef status = HAL_OK; assert_param(IS_PWR_GPIO(GPIO)); assert_param(IS_PWR_GPIO_BIT_NUMBER(GPIONumber)); switch (GPIO) { case PWR_GPIO_A: SET_BIT(PWR->PUCRA, (GPIONumber & (~(PWR_GPIO_BIT_14)))); CLEAR_BIT(PWR->PDCRA, (GPIONumber & (~(PWR_GPIO_BIT_13|PWR_GPIO_BIT_15)))); break; case PWR_GPIO_B: SET_BIT(PWR->PUCRB, GPIONumber); CLEAR_BIT(PWR->PDCRB, (GPIONumber & (~(PWR_GPIO_BIT_4)))); break; case PWR_GPIO_C: SET_BIT(PWR->PUCRC, GPIONumber); CLEAR_BIT(PWR->PDCRC, GPIONumber); break; case PWR_GPIO_D: SET_BIT(PWR->PUCRD, GPIONumber); CLEAR_BIT(PWR->PDCRD, GPIONumber); break; case PWR_GPIO_E: SET_BIT(PWR->PUCRE, GPIONumber); CLEAR_BIT(PWR->PDCRE, GPIONumber); break; case PWR_GPIO_F: SET_BIT(PWR->PUCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); CLEAR_BIT(PWR->PDCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); break; case PWR_GPIO_G: SET_BIT(PWR->PUCRG, (GPIONumber & PWR_PORTG_AVAILABLE_PINS)); CLEAR_BIT(PWR->PDCRG, ((GPIONumber & PWR_PORTG_AVAILABLE_PINS) & (~(PWR_GPIO_BIT_10)))); break; default: status = HAL_ERROR; break; } return status; } /** * @brief Disable GPIO pull-up state in Standby mode and Shutdown modes. * @note Reset the relevant PUy bits of PWR_PUCRx register used to configure the I/O * in pull-up state in Standby and Shutdown modes. * @note Even if a PUy bit to reset is reserved, the other PUy bits entered as input * parameter at the same time are reset. * @param GPIO: Specifies the IO port. This parameter can be PWR_GPIO_A, ..., PWR_GPIO_G * (or PWR_GPIO_I depending on the devices) to select the GPIO peripheral. * @param GPIONumber: Specify the I/O pins numbers. * This parameter can be one of the following values: * PWR_GPIO_BIT_0, ..., PWR_GPIO_BIT_15 (except for the port where less * I/O pins are available) or the logical OR of several of them to reset * several bits for a given port in a single API call. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber) { HAL_StatusTypeDef status = HAL_OK; assert_param(IS_PWR_GPIO(GPIO)); assert_param(IS_PWR_GPIO_BIT_NUMBER(GPIONumber)); switch (GPIO) { case PWR_GPIO_A: CLEAR_BIT(PWR->PUCRA, (GPIONumber & (~(PWR_GPIO_BIT_14)))); break; case PWR_GPIO_B: CLEAR_BIT(PWR->PUCRB, GPIONumber); break; case PWR_GPIO_C: CLEAR_BIT(PWR->PUCRC, GPIONumber); break; case PWR_GPIO_D: CLEAR_BIT(PWR->PUCRD, GPIONumber); break; case PWR_GPIO_E: CLEAR_BIT(PWR->PUCRE, GPIONumber); break; case PWR_GPIO_F: CLEAR_BIT(PWR->PUCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); break; case PWR_GPIO_G: CLEAR_BIT(PWR->PUCRG, (GPIONumber & PWR_PORTG_AVAILABLE_PINS)); break; default: status = HAL_ERROR; break; } return status; } /** * @brief Enable GPIO pull-down state in Standby and Shutdown modes. * @note Set the relevant PDy bits of PWR_PDCRx register to configure the I/O in * pull-down state in Standby and Shutdown modes. * @note This state is effective in Standby and Shutdown modes only if APC bit * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. * @note The configuration is lost when exiting the Shutdown mode due to the * power-on reset, maintained when exiting the Standby mode. * @note To avoid any conflict at Standby and Shutdown modes exits, the corresponding * PUy bit of PWR_PUCRx register is cleared unless it is reserved. * @note Even if a PDy bit to set is reserved, the other PDy bits entered as input * parameter at the same time are set. * @param GPIO: Specify the IO port. This parameter can be PWR_GPIO_A..PWR_GPIO_G * (or PWR_GPIO_I depending on the devices) to select the GPIO peripheral. * @param GPIONumber: Specify the I/O pins numbers. * This parameter can be one of the following values: * PWR_GPIO_BIT_0, ..., PWR_GPIO_BIT_15 (except for the port where less * I/O pins are available) or the logical OR of several of them to set * several bits for a given port in a single API call. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumber) { HAL_StatusTypeDef status = HAL_OK; assert_param(IS_PWR_GPIO(GPIO)); assert_param(IS_PWR_GPIO_BIT_NUMBER(GPIONumber)); switch (GPIO) { case PWR_GPIO_A: SET_BIT(PWR->PDCRA, (GPIONumber & (~(PWR_GPIO_BIT_13|PWR_GPIO_BIT_15)))); CLEAR_BIT(PWR->PUCRA, (GPIONumber & (~(PWR_GPIO_BIT_14)))); break; case PWR_GPIO_B: SET_BIT(PWR->PDCRB, (GPIONumber & (~(PWR_GPIO_BIT_4)))); CLEAR_BIT(PWR->PUCRB, GPIONumber); break; case PWR_GPIO_C: SET_BIT(PWR->PDCRC, GPIONumber); CLEAR_BIT(PWR->PUCRC, GPIONumber); break; case PWR_GPIO_D: SET_BIT(PWR->PDCRD, GPIONumber); CLEAR_BIT(PWR->PUCRD, GPIONumber); break; case PWR_GPIO_E: SET_BIT(PWR->PDCRE, GPIONumber); CLEAR_BIT(PWR->PUCRE, GPIONumber); break; case PWR_GPIO_F: SET_BIT(PWR->PDCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); CLEAR_BIT(PWR->PUCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); break; case PWR_GPIO_G: SET_BIT(PWR->PDCRG, ((GPIONumber & PWR_PORTG_AVAILABLE_PINS) & (~(PWR_GPIO_BIT_10)))); CLEAR_BIT(PWR->PUCRG, (GPIONumber & PWR_PORTG_AVAILABLE_PINS)); break; default: status = HAL_ERROR; break; } return status; } /** * @brief Disable GPIO pull-down state in Standby and Shutdown modes. * @note Reset the relevant PDy bits of PWR_PDCRx register used to configure the I/O * in pull-down state in Standby and Shutdown modes. * @note Even if a PDy bit to reset is reserved, the other PDy bits entered as input * parameter at the same time are reset. * @param GPIO: Specifies the IO port. This parameter can be PWR_GPIO_A..PWR_GPIO_G * (or PWR_GPIO_I depending on the devices) to select the GPIO peripheral. * @param GPIONumber: Specify the I/O pins numbers. * This parameter can be one of the following values: * PWR_GPIO_BIT_0, ..., PWR_GPIO_BIT_15 (except for the port where less * I/O pins are available) or the logical OR of several of them to reset * several bits for a given port in a single API call. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumber) { HAL_StatusTypeDef status = HAL_OK; assert_param(IS_PWR_GPIO(GPIO)); assert_param(IS_PWR_GPIO_BIT_NUMBER(GPIONumber)); switch (GPIO) { case PWR_GPIO_A: CLEAR_BIT(PWR->PDCRA, (GPIONumber & (~(PWR_GPIO_BIT_13|PWR_GPIO_BIT_15)))); break; case PWR_GPIO_B: CLEAR_BIT(PWR->PDCRB, (GPIONumber & (~(PWR_GPIO_BIT_4)))); break; case PWR_GPIO_C: CLEAR_BIT(PWR->PDCRC, GPIONumber); break; case PWR_GPIO_D: CLEAR_BIT(PWR->PDCRD, GPIONumber); break; case PWR_GPIO_E: CLEAR_BIT(PWR->PDCRE, GPIONumber); break; case PWR_GPIO_F: CLEAR_BIT(PWR->PDCRF, (GPIONumber & PWR_PORTF_AVAILABLE_PINS)); break; case PWR_GPIO_G: CLEAR_BIT(PWR->PDCRG, ((GPIONumber & PWR_PORTG_AVAILABLE_PINS) & (~(PWR_GPIO_BIT_10)))); break; default: status = HAL_ERROR; break; } return status; } /** * @brief Enable pull-up and pull-down configuration. * @note When APC bit is set, the I/O pull-up and pull-down configurations defined in * PWR_PUCRx and PWR_PDCRx registers are applied in Standby and Shutdown modes. * @note Pull-up set by PUy bit of PWR_PUCRx register is not activated if the corresponding * PDy bit of PWR_PDCRx register is also set (pull-down configuration priority is higher). * HAL_PWREx_EnableGPIOPullUp() and HAL_PWREx_EnableGPIOPullDown() API's ensure there * is no conflict when setting PUy or PDy bit. * @retval None */ void HAL_PWREx_EnablePullUpPullDownConfig(void) { SET_BIT(PWR->CR3, PWR_CR3_APC); } /** * @brief Disable pull-up and pull-down configuration. * @note When APC bit is cleared, the I/O pull-up and pull-down configurations defined in * PWR_PUCRx and PWR_PDCRx registers are not applied in Standby and Shutdown modes. * @retval None */ void HAL_PWREx_DisablePullUpPullDownConfig(void) { CLEAR_BIT(PWR->CR3, PWR_CR3_APC); } /** * @brief Enable SRAM2 content retention in Standby mode. * @note When RRS bit is set, SRAM2 is powered by the low-power regulator in * Standby mode and its content is kept. * @retval None */ void HAL_PWREx_EnableSRAM2ContentRetention(void) { SET_BIT(PWR->CR3, PWR_CR3_RRS); } /** * @brief Disable SRAM2 content retention in Standby mode. * @note When RRS bit is reset, SRAM2 is powered off in Standby mode * and its content is lost. * @retval None */ void HAL_PWREx_DisableSRAM2ContentRetention(void) { CLEAR_BIT(PWR->CR3, PWR_CR3_RRS); } #if defined(PWR_CR2_PVME1) /** * @brief Enable the Power Voltage Monitoring 1: VDDA versus FASTCOMP minimum voltage. * @retval None */ void HAL_PWREx_EnablePVM1(void) { SET_BIT(PWR->CR2, PWR_PVM_1); } /** * @brief Disable the Power Voltage Monitoring 1: VDDA versus FASTCOMP minimum voltage. * @retval None */ void HAL_PWREx_DisablePVM1(void) { CLEAR_BIT(PWR->CR2, PWR_PVM_1); } #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) /** * @brief Enable the Power Voltage Monitoring 2: VDDA versus FASTDAC minimum voltage. * @retval None */ void HAL_PWREx_EnablePVM2(void) { SET_BIT(PWR->CR2, PWR_PVM_2); } /** * @brief Disable the Power Voltage Monitoring 2: VDDA versus FASTDAC minimum voltage. * @retval None */ void HAL_PWREx_DisablePVM2(void) { CLEAR_BIT(PWR->CR2, PWR_PVM_2); } #endif /* PWR_CR2_PVME2 */ /** * @brief Enable the Power Voltage Monitoring 3: VDDA versus ADC minimum voltage 1.62V. * @retval None */ void HAL_PWREx_EnablePVM3(void) { SET_BIT(PWR->CR2, PWR_PVM_3); } /** * @brief Disable the Power Voltage Monitoring 3: VDDA versus ADC minimum voltage 1.62V. * @retval None */ void HAL_PWREx_DisablePVM3(void) { CLEAR_BIT(PWR->CR2, PWR_PVM_3); } /** * @brief Enable the Power Voltage Monitoring 4: VDDA versus OPAMP/DAC minimum voltage 1.8V. * @retval None */ void HAL_PWREx_EnablePVM4(void) { SET_BIT(PWR->CR2, PWR_PVM_4); } /** * @brief Disable the Power Voltage Monitoring 4: VDDA versus OPAMP/DAC minimum voltage 1.8V. * @retval None */ void HAL_PWREx_DisablePVM4(void) { CLEAR_BIT(PWR->CR2, PWR_PVM_4); } /** * @brief Configure the Peripheral Voltage Monitoring (PVM). * @param sConfigPVM: pointer to a PWR_PVMTypeDef structure that contains the * PVM configuration information. * @note The API configures a single PVM according to the information contained * in the input structure. To configure several PVMs, the API must be singly * called for each PVM used. * @note Refer to the electrical characteristics of your device datasheet for * more details about the voltage thresholds corresponding to each * detection level and to each monitored supply. * @retval HAL status */ HAL_StatusTypeDef HAL_PWREx_ConfigPVM(PWR_PVMTypeDef *sConfigPVM) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_PWR_PVM_TYPE(sConfigPVM->PVMType)); assert_param(IS_PWR_PVM_MODE(sConfigPVM->Mode)); /* Configure EXTI 35 to 38 interrupts if so required: scan through PVMType to detect which PVMx is set and configure the corresponding EXTI line accordingly. */ switch (sConfigPVM->PVMType) { #if defined(PWR_CR2_PVME1) case PWR_PVM_1: /* Clear any previous config. Keep it clear if no event or IT mode is selected */ __HAL_PWR_PVM1_EXTI_DISABLE_EVENT(); __HAL_PWR_PVM1_EXTI_DISABLE_IT(); __HAL_PWR_PVM1_EXTI_DISABLE_FALLING_EDGE(); __HAL_PWR_PVM1_EXTI_DISABLE_RISING_EDGE(); /* Configure interrupt mode */ if((sConfigPVM->Mode & PVM_MODE_IT) == PVM_MODE_IT) { __HAL_PWR_PVM1_EXTI_ENABLE_IT(); } /* Configure event mode */ if((sConfigPVM->Mode & PVM_MODE_EVT) == PVM_MODE_EVT) { __HAL_PWR_PVM1_EXTI_ENABLE_EVENT(); } /* Configure the edge */ if((sConfigPVM->Mode & PVM_RISING_EDGE) == PVM_RISING_EDGE) { __HAL_PWR_PVM1_EXTI_ENABLE_RISING_EDGE(); } if((sConfigPVM->Mode & PVM_FALLING_EDGE) == PVM_FALLING_EDGE) { __HAL_PWR_PVM1_EXTI_ENABLE_FALLING_EDGE(); } break; #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) case PWR_PVM_2: /* Clear any previous config. Keep it clear if no event or IT mode is selected */ __HAL_PWR_PVM2_EXTI_DISABLE_EVENT(); __HAL_PWR_PVM2_EXTI_DISABLE_IT(); __HAL_PWR_PVM2_EXTI_DISABLE_FALLING_EDGE(); __HAL_PWR_PVM2_EXTI_DISABLE_RISING_EDGE(); /* Configure interrupt mode */ if((sConfigPVM->Mode & PVM_MODE_IT) == PVM_MODE_IT) { __HAL_PWR_PVM2_EXTI_ENABLE_IT(); } /* Configure event mode */ if((sConfigPVM->Mode & PVM_MODE_EVT) == PVM_MODE_EVT) { __HAL_PWR_PVM2_EXTI_ENABLE_EVENT(); } /* Configure the edge */ if((sConfigPVM->Mode & PVM_RISING_EDGE) == PVM_RISING_EDGE) { __HAL_PWR_PVM2_EXTI_ENABLE_RISING_EDGE(); } if((sConfigPVM->Mode & PVM_FALLING_EDGE) == PVM_FALLING_EDGE) { __HAL_PWR_PVM2_EXTI_ENABLE_FALLING_EDGE(); } break; #endif /* PWR_CR2_PVME2 */ case PWR_PVM_3: /* Clear any previous config. Keep it clear if no event or IT mode is selected */ __HAL_PWR_PVM3_EXTI_DISABLE_EVENT(); __HAL_PWR_PVM3_EXTI_DISABLE_IT(); __HAL_PWR_PVM3_EXTI_DISABLE_FALLING_EDGE(); __HAL_PWR_PVM3_EXTI_DISABLE_RISING_EDGE(); /* Configure interrupt mode */ if((sConfigPVM->Mode & PVM_MODE_IT) == PVM_MODE_IT) { __HAL_PWR_PVM3_EXTI_ENABLE_IT(); } /* Configure event mode */ if((sConfigPVM->Mode & PVM_MODE_EVT) == PVM_MODE_EVT) { __HAL_PWR_PVM3_EXTI_ENABLE_EVENT(); } /* Configure the edge */ if((sConfigPVM->Mode & PVM_RISING_EDGE) == PVM_RISING_EDGE) { __HAL_PWR_PVM3_EXTI_ENABLE_RISING_EDGE(); } if((sConfigPVM->Mode & PVM_FALLING_EDGE) == PVM_FALLING_EDGE) { __HAL_PWR_PVM3_EXTI_ENABLE_FALLING_EDGE(); } break; case PWR_PVM_4: /* Clear any previous config. Keep it clear if no event or IT mode is selected */ __HAL_PWR_PVM4_EXTI_DISABLE_EVENT(); __HAL_PWR_PVM4_EXTI_DISABLE_IT(); __HAL_PWR_PVM4_EXTI_DISABLE_FALLING_EDGE(); __HAL_PWR_PVM4_EXTI_DISABLE_RISING_EDGE(); /* Configure interrupt mode */ if((sConfigPVM->Mode & PVM_MODE_IT) == PVM_MODE_IT) { __HAL_PWR_PVM4_EXTI_ENABLE_IT(); } /* Configure event mode */ if((sConfigPVM->Mode & PVM_MODE_EVT) == PVM_MODE_EVT) { __HAL_PWR_PVM4_EXTI_ENABLE_EVENT(); } /* Configure the edge */ if((sConfigPVM->Mode & PVM_RISING_EDGE) == PVM_RISING_EDGE) { __HAL_PWR_PVM4_EXTI_ENABLE_RISING_EDGE(); } if((sConfigPVM->Mode & PVM_FALLING_EDGE) == PVM_FALLING_EDGE) { __HAL_PWR_PVM4_EXTI_ENABLE_FALLING_EDGE(); } break; default: status = HAL_ERROR; break; } return status; } /** * @brief Enter Low-power Run mode * @note In Low-power Run mode, all I/O pins keep the same state as in Run mode. * @note When Regulator is set to PWR_LOWPOWERREGULATOR_ON, the user can optionally configure the * Flash in power-down monde in setting the RUN_PD bit in FLASH_ACR register. * Additionally, the clock frequency must be reduced below 2 MHz. * Setting RUN_PD in FLASH_ACR then appropriately reducing the clock frequency must * be done before calling HAL_PWREx_EnableLowPowerRunMode() API. * @retval None */ void HAL_PWREx_EnableLowPowerRunMode(void) { /* Set Regulator parameter */ SET_BIT(PWR->CR1, PWR_CR1_LPR); } /** * @brief Exit Low-power Run mode. * @note Before HAL_PWREx_DisableLowPowerRunMode() completion, the function checks that * REGLPF has been properly reset (otherwise, HAL_PWREx_DisableLowPowerRunMode * returns HAL_TIMEOUT status). The system clock frequency can then be * increased above 2 MHz. * @retval HAL Status */ HAL_StatusTypeDef HAL_PWREx_DisableLowPowerRunMode(void) { uint32_t wait_loop_index; /* Clear LPR bit */ CLEAR_BIT(PWR->CR1, PWR_CR1_LPR); /* Wait until REGLPF is reset */ wait_loop_index = (PWR_FLAG_SETTING_DELAY_US * (SystemCoreClock / 1000000U)); while ((HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_REGLPF)) && (wait_loop_index != 0U)) { wait_loop_index--; } if (HAL_IS_BIT_SET(PWR->SR2, PWR_SR2_REGLPF)) { return HAL_TIMEOUT; } return HAL_OK; } /** * @brief Enter Stop 0 mode. * @note In Stop 0 mode, main and low voltage regulators are ON. * @note In Stop 0 mode, all I/O pins keep the same state as in Run mode. * @note All clocks in the VCORE domain are stopped; the PLL, the HSI * and the HSE oscillators are disabled. Some peripherals with the wakeup capability * (I2Cx, USARTx and LPUART) can switch on the HSI to receive a frame, and switch off the HSI * after receiving the frame if it is not a wakeup frame. In this case, the HSI clock is propagated * only to the peripheral requesting it. * SRAM1, SRAM2 and register contents are preserved. * The BOR is available. * @note When exiting Stop 0 mode by issuing an interrupt or a wakeup event, * the HSI RC oscillator is selected as system clock if STOPWUCK bit in RCC_CFGR register * is set; the HSI oscillator is selected if STOPWUCK is cleared. * @note By keeping the internal regulator ON during Stop 0 mode, the consumption * is higher although the startup time is reduced. * @param STOPEntry specifies if Stop mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg @ref PWR_STOPENTRY_WFI Enter Stop mode with WFI instruction * @arg @ref PWR_STOPENTRY_WFE Enter Stop mode with WFE instruction * @retval None */ void HAL_PWREx_EnterSTOP0Mode(uint8_t STOPEntry) { /* Check the parameters */ assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); /* Stop 0 mode with Main Regulator */ MODIFY_REG(PWR->CR1, PWR_CR1_LPMS, PWR_CR1_LPMS_STOP0); /* Set SLEEPDEEP bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* Select Stop mode entry --------------------------------------------------*/ if(STOPEntry == PWR_STOPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } /* Reset SLEEPDEEP bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); } /** * @brief Enter Stop 1 mode. * @note In Stop 1 mode, only low power voltage regulator is ON. * @note In Stop 1 mode, all I/O pins keep the same state as in Run mode. * @note All clocks in the VCORE domain are stopped; the PLL, the HSI * and the HSE oscillators are disabled. Some peripherals with the wakeup capability * (I2Cx, USARTx and LPUART) can switch on the HSI to receive a frame, and switch off the HSI * after receiving the frame if it is not a wakeup frame. In this case, the HSI clock is propagated * only to the peripheral requesting it. * SRAM1, SRAM2 and register contents are preserved. * The BOR is available. * @note When exiting Stop 1 mode by issuing an interrupt or a wakeup event, * the HSI RC oscillator is selected as system clock if STOPWUCK bit in RCC_CFGR register * is set. * @note Due to low power mode, an additional startup delay is incurred when waking up from Stop 1 mode. * @param STOPEntry specifies if Stop mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg @ref PWR_STOPENTRY_WFI Enter Stop mode with WFI instruction * @arg @ref PWR_STOPENTRY_WFE Enter Stop mode with WFE instruction * @retval None */ void HAL_PWREx_EnterSTOP1Mode(uint8_t STOPEntry) { /* Check the parameters */ assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); /* Stop 1 mode with Low-Power Regulator */ MODIFY_REG(PWR->CR1, PWR_CR1_LPMS, PWR_CR1_LPMS_STOP1); /* Set SLEEPDEEP bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* Select Stop mode entry --------------------------------------------------*/ if(STOPEntry == PWR_STOPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } /* Reset SLEEPDEEP bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); } /** * @brief Enter Shutdown mode. * @note In Shutdown mode, the PLL, the HSI, the LSI and the HSE oscillators are switched * off. The voltage regulator is disabled and Vcore domain is powered off. * SRAM1, SRAM2 and registers contents are lost except for registers in the Backup domain. * The BOR is not available. * @note The I/Os can be configured either with a pull-up or pull-down or can be kept in analog state. * @retval None */ void HAL_PWREx_EnterSHUTDOWNMode(void) { /* Set Shutdown mode */ MODIFY_REG(PWR->CR1, PWR_CR1_LPMS, PWR_CR1_LPMS_SHUTDOWN); /* Set SLEEPDEEP bit of Cortex System Control Register */ SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* This option is used to ensure that store operations are completed */ #if defined ( __CC_ARM) __force_stores(); #endif /* Request Wait For Interrupt */ __WFI(); } /** * @brief This function handles the PWR PVD/PVMx interrupt request. * @note This API should be called under the PVD_PVM_IRQHandler(). * @retval None */ void HAL_PWREx_PVD_PVM_IRQHandler(void) { /* Check PWR exti flag */ if(__HAL_PWR_PVD_EXTI_GET_FLAG() != 0U) { /* PWR PVD interrupt user callback */ HAL_PWR_PVDCallback(); /* Clear PVD exti pending bit */ __HAL_PWR_PVD_EXTI_CLEAR_FLAG(); } /* Next, successively check PVMx exti flags */ #if defined(PWR_CR2_PVME1) if(__HAL_PWR_PVM1_EXTI_GET_FLAG() != 0U) { /* PWR PVM1 interrupt user callback */ HAL_PWREx_PVM1Callback(); /* Clear PVM1 exti pending bit */ __HAL_PWR_PVM1_EXTI_CLEAR_FLAG(); } #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) if(__HAL_PWR_PVM2_EXTI_GET_FLAG() != 0U) { /* PWR PVM2 interrupt user callback */ HAL_PWREx_PVM2Callback(); /* Clear PVM2 exti pending bit */ __HAL_PWR_PVM2_EXTI_CLEAR_FLAG(); } #endif /* PWR_CR2_PVME2 */ if(__HAL_PWR_PVM3_EXTI_GET_FLAG() != 0U) { /* PWR PVM3 interrupt user callback */ HAL_PWREx_PVM3Callback(); /* Clear PVM3 exti pending bit */ __HAL_PWR_PVM3_EXTI_CLEAR_FLAG(); } if(__HAL_PWR_PVM4_EXTI_GET_FLAG() != 0U) { /* PWR PVM4 interrupt user callback */ HAL_PWREx_PVM4Callback(); /* Clear PVM4 exti pending bit */ __HAL_PWR_PVM4_EXTI_CLEAR_FLAG(); } } #if defined(PWR_CR2_PVME1) /** * @brief PWR PVM1 interrupt callback * @retval None */ __weak void HAL_PWREx_PVM1Callback(void) { /* NOTE : This function should not be modified; when the callback is needed, HAL_PWREx_PVM1Callback() API can be implemented in the user file */ } #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) /** * @brief PWR PVM2 interrupt callback * @retval None */ __weak void HAL_PWREx_PVM2Callback(void) { /* NOTE : This function should not be modified; when the callback is needed, HAL_PWREx_PVM2Callback() API can be implemented in the user file */ } #endif /* PWR_CR2_PVME2 */ /** * @brief PWR PVM3 interrupt callback * @retval None */ __weak void HAL_PWREx_PVM3Callback(void) { /* NOTE : This function should not be modified; when the callback is needed, HAL_PWREx_PVM3Callback() API can be implemented in the user file */ } /** * @brief PWR PVM4 interrupt callback * @retval None */ __weak void HAL_PWREx_PVM4Callback(void) { /* NOTE : This function should not be modified; when the callback is needed, HAL_PWREx_PVM4Callback() API can be implemented in the user file */ } #if defined(PWR_CR3_UCPD_STDBY) /** * @brief Enable UCPD configuration memorization in Standby. * @retval None */ void HAL_PWREx_EnableUCPDStandbyMode(void) { /* Memorize UCPD configuration when entering standby mode */ SET_BIT(PWR->CR3, PWR_CR3_UCPD_STDBY); } /** * @brief Disable UCPD configuration memorization in Standby. * @note This function must be called on exiting the Standby mode and before any UCPD * configuration update. * @retval None */ void HAL_PWREx_DisableUCPDStandbyMode(void) { /* Write 0 immediately after Standby exit when using UCPD, and before writing any UCPD registers */ CLEAR_BIT(PWR->CR3, PWR_CR3_UCPD_STDBY); } #endif /* PWR_CR3_UCPD_STDBY */ #if defined(PWR_CR3_UCPD_DBDIS) /** * @brief Enable the USB Type-C dead battery pull-down behavior * on UCPDx_CC1 and UCPDx_CC2 pins * @retval None */ void HAL_PWREx_EnableUCPDDeadBattery(void) { /* Write 0 to enable the USB Type-C dead battery pull-down behavior */ CLEAR_BIT(PWR->CR3, PWR_CR3_UCPD_DBDIS); } /** * @brief Disable the USB Type-C dead battery pull-down behavior * on UCPDx_CC1 and UCPDx_CC2 pins * @note After exiting reset, the USB Type-C dead battery behavior will be enabled, * which may have a pull-down effect on CC1 and CC2 pins. * It is recommended to disable it in all cases, either to stop this pull-down * or to hand over control to the UCPD (which should therefore be * initialized before doing the disable). * @retval None */ void HAL_PWREx_DisableUCPDDeadBattery(void) { /* Write 1 to disable the USB Type-C dead battery pull-down behavior */ SET_BIT(PWR->CR3, PWR_CR3_UCPD_DBDIS); } #endif /* PWR_CR3_UCPD_DBDIS */ /** * @} */ /** * @} */ #endif /* HAL_PWR_MODULE_ENABLED */ /** * @} */ /** * @} */
37,944
C
31.075232
127
0.626239
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_uart.c
/** ****************************************************************************** * @file stm32g4xx_hal_uart.c * @author MCD Application Team * @brief UART HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). * + Initialization and de-initialization functions * + IO operation functions * + Peripheral Control functions * * ****************************************************************************** * @attention * * Copyright (c) 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 UART HAL driver can be used as follows: (#) Declare a UART_HandleTypeDef handle structure (eg. UART_HandleTypeDef huart). (#) Initialize the UART low level resources by implementing the HAL_UART_MspInit() API: (++) Enable the USARTx interface clock. (++) UART pins configuration: (+++) Enable the clock for the UART GPIOs. (+++) Configure these UART pins as alternate function pull-up. (++) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT() and HAL_UART_Receive_IT() APIs): (+++) Configure the USARTx interrupt priority. (+++) Enable the NVIC USART IRQ handle. (++) UART interrupts handling: -@@- The specific UART interrupts (Transmission complete interrupt, RXNE interrupt, RX/TX FIFOs related interrupts and Error Interrupts) are managed using the macros __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the transmit and receive processes. (++) DMA Configuration if you need to use DMA process (HAL_UART_Transmit_DMA() and HAL_UART_Receive_DMA() APIs): (+++) Declare a DMA handle structure for the Tx/Rx channel. (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx channel. (+++) Associate the initialized DMA handle to the UART DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel. (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Prescaler value , Hardware flow control and Mode (Receiver/Transmitter) in the huart handle Init structure. (#) If required, program UART advanced features (TX/RX pins swap, auto Baud rate detection,...) in the huart handle AdvancedInit structure. (#) For the UART asynchronous mode, initialize the UART registers by calling the HAL_UART_Init() API. (#) For the UART Half duplex mode, initialize the UART registers by calling the HAL_HalfDuplex_Init() API. (#) For the UART LIN (Local Interconnection Network) mode, initialize the UART registers by calling the HAL_LIN_Init() API. (#) For the UART Multiprocessor mode, initialize the UART registers by calling the HAL_MultiProcessor_Init() API. (#) For the UART RS485 Driver Enabled mode, initialize the UART registers by calling the HAL_RS485Ex_Init() API. [..] (@) These API's (HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init(), HAL_MultiProcessor_Init(), also configure the low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customized HAL_UART_MspInit() API. ##### Callback registration ##### ================================== [..] The compilation define USE_HAL_UART_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. [..] Use Function HAL_UART_RegisterCallback() to register a user callback. Function HAL_UART_RegisterCallback() allows to register following callbacks: (+) TxHalfCpltCallback : Tx Half Complete Callback. (+) TxCpltCallback : Tx Complete Callback. (+) RxHalfCpltCallback : Rx Half Complete Callback. (+) RxCpltCallback : Rx Complete Callback. (+) ErrorCallback : Error Callback. (+) AbortCpltCallback : Abort Complete Callback. (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. (+) WakeupCallback : Wakeup Callback. (+) RxFifoFullCallback : Rx Fifo Full Callback. (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. (+) MspInitCallback : UART MspInit. (+) MspDeInitCallback : UART MspDeInit. This function takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. [..] Use function HAL_UART_UnRegisterCallback() to reset a callback to the default weak (surcharged) function. HAL_UART_UnRegisterCallback() takes as parameters the HAL peripheral handle, and the Callback ID. This function allows to reset following callbacks: (+) TxHalfCpltCallback : Tx Half Complete Callback. (+) TxCpltCallback : Tx Complete Callback. (+) RxHalfCpltCallback : Rx Half Complete Callback. (+) RxCpltCallback : Rx Complete Callback. (+) ErrorCallback : Error Callback. (+) AbortCpltCallback : Abort Complete Callback. (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. (+) WakeupCallback : Wakeup Callback. (+) RxFifoFullCallback : Rx Fifo Full Callback. (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. (+) MspInitCallback : UART MspInit. (+) MspDeInitCallback : UART MspDeInit. [..] For specific callback RxEventCallback, use dedicated registration/reset functions: respectively HAL_UART_RegisterRxEventCallback() , HAL_UART_UnRegisterRxEventCallback(). [..] By default, after the HAL_UART_Init() and when the state is HAL_UART_STATE_RESET all callbacks are set to the corresponding weak (surcharged) functions: examples HAL_UART_TxCpltCallback(), HAL_UART_RxHalfCpltCallback(). Exception done for MspInit and MspDeInit functions that are respectively reset to the legacy weak (surcharged) functions in the HAL_UART_Init() and HAL_UART_DeInit() only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the HAL_UART_Init() and HAL_UART_DeInit() keep and use the user MspInit/MspDeInit callbacks (registered beforehand). [..] Callbacks can be registered/unregistered in HAL_UART_STATE_READY state only. Exception done MspInit/MspDeInit that can be registered/unregistered in HAL_UART_STATE_READY or HAL_UART_STATE_RESET state, thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. In that case first register the MspInit/MspDeInit user callbacks using HAL_UART_RegisterCallback() before calling HAL_UART_DeInit() or HAL_UART_Init() function. [..] When The compilation define USE_HAL_UART_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration feature is not available and weak (surcharged) callbacks are used. @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup UART UART * @brief HAL UART module driver * @{ */ #ifdef HAL_UART_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup UART_Private_Constants UART Private Constants * @{ */ #define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | \ USART_CR1_OVER8 | USART_CR1_FIFOEN)) /*!< UART or USART CR1 fields of parameters set by UART_SetConfig API */ #define USART_CR3_FIELDS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT | USART_CR3_TXFTCFG | \ USART_CR3_RXFTCFG)) /*!< UART or USART CR3 fields of parameters set by UART_SetConfig API */ #define LPUART_BRR_MIN 0x00000300U /* LPUART BRR minimum authorized value */ #define LPUART_BRR_MAX 0x000FFFFFU /* LPUART BRR maximum authorized value */ #define UART_BRR_MIN 0x10U /* UART BRR minimum authorized value */ #define UART_BRR_MAX 0x0000FFFFU /* UART BRR maximum authorized value */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @addtogroup UART_Private_Functions * @{ */ static void UART_EndTxTransfer(UART_HandleTypeDef *huart); static void UART_EndRxTransfer(UART_HandleTypeDef *huart); static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); static void UART_DMAError(DMA_HandleTypeDef *hdma); static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma); static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); static void UART_TxISR_8BIT(UART_HandleTypeDef *huart); static void UART_TxISR_16BIT(UART_HandleTypeDef *huart); static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); static void UART_EndTransmit_IT(UART_HandleTypeDef *huart); static void UART_RxISR_8BIT(UART_HandleTypeDef *huart); static void UART_RxISR_16BIT(UART_HandleTypeDef *huart); static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @addtogroup UART_Private_variables * @{ */ const uint16_t UARTPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; /** * @} */ /* Exported Constants --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup UART_Exported_Functions UART Exported Functions * @{ */ /** @defgroup UART_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to initialize the USARTx or the UARTy in asynchronous mode. (+) For the asynchronous mode the parameters below can be configured: (++) Baud Rate (++) Word Length (++) Stop Bit (++) Parity: If the parity is enabled, then the MSB bit of the data written in the data register is transmitted but is changed by the parity bit. (++) Hardware flow control (++) Receiver/transmitter modes (++) Over Sampling Method (++) One-Bit Sampling Method (+) For the asynchronous mode, the following advanced features can be configured as well: (++) TX and/or RX pin level inversion (++) data logical level inversion (++) RX and TX pins swap (++) RX overrun detection disabling (++) DMA disabling on RX error (++) MSB first on communication line (++) auto Baud rate detection [..] The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init()and HAL_MultiProcessor_Init()API follow respectively the UART asynchronous, UART Half duplex, UART LIN mode and UART multiprocessor mode configuration procedures (details for the procedures are available in reference manual). @endverbatim Depending on the frame length defined by the M1 and M0 bits (7-bit, 8-bit or 9-bit), the possible UART formats are listed in the following table. Table 1. UART frame format. +-----------------------------------------------------------------------+ | M1 bit | M0 bit | PCE bit | UART frame | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 0 | | SB | 8 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 0 | | SB | 9 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 0 | | SB | 7 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | +-----------------------------------------------------------------------+ * @{ */ /** * @brief Initialize the UART mode according to the specified * parameters in the UART_InitTypeDef and initialize the associated handle. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } if (huart->Init.HwFlowCtl != UART_HWCONTROL_NONE) { /* Check the parameters */ assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance)); } else { /* Check the parameters */ assert_param((IS_UART_INSTANCE(huart->Instance)) || (IS_LPUART_INSTANCE(huart->Instance))); } if (huart->gState == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) UART_InitCallbacksToDefault(huart); if (huart->MspInitCallback == NULL) { huart->MspInitCallback = HAL_UART_MspInit; } /* Init the low level hardware */ huart->MspInitCallback(huart); #else /* Init the low level hardware : GPIO, CLOCK */ HAL_UART_MspInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } huart->gState = HAL_UART_STATE_BUSY; __HAL_UART_DISABLE(huart); /* Set the UART Communication parameters */ if (UART_SetConfig(huart) == HAL_ERROR) { return HAL_ERROR; } if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) { UART_AdvFeatureConfig(huart); } /* In asynchronous mode, the following bits must be kept cleared: - LINEN and CLKEN bits in the USART_CR2 register, - SCEN, HDSEL and IREN bits in the USART_CR3 register.*/ CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ return (UART_CheckIdleState(huart)); } /** * @brief Initialize the half-duplex mode according to the specified * parameters in the UART_InitTypeDef and creates the associated handle. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check UART instance */ assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance)); if (huart->gState == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) UART_InitCallbacksToDefault(huart); if (huart->MspInitCallback == NULL) { huart->MspInitCallback = HAL_UART_MspInit; } /* Init the low level hardware */ huart->MspInitCallback(huart); #else /* Init the low level hardware : GPIO, CLOCK */ HAL_UART_MspInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } huart->gState = HAL_UART_STATE_BUSY; __HAL_UART_DISABLE(huart); /* Set the UART Communication parameters */ if (UART_SetConfig(huart) == HAL_ERROR) { return HAL_ERROR; } if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) { UART_AdvFeatureConfig(huart); } /* In half-duplex mode, the following bits must be kept cleared: - LINEN and CLKEN bits in the USART_CR2 register, - SCEN and IREN bits in the USART_CR3 register.*/ CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); CLEAR_BIT(huart->Instance->CR3, (USART_CR3_IREN | USART_CR3_SCEN)); /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ SET_BIT(huart->Instance->CR3, USART_CR3_HDSEL); __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ return (UART_CheckIdleState(huart)); } /** * @brief Initialize the LIN mode according to the specified * parameters in the UART_InitTypeDef and creates the associated handle. * @param huart UART handle. * @param BreakDetectLength Specifies the LIN break detection length. * This parameter can be one of the following values: * @arg @ref UART_LINBREAKDETECTLENGTH_10B 10-bit break detection * @arg @ref UART_LINBREAKDETECTLENGTH_11B 11-bit break detection * @retval HAL status */ HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check the LIN UART instance */ assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); /* Check the Break detection length parameter */ assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); /* LIN mode limited to 16-bit oversampling only */ if (huart->Init.OverSampling == UART_OVERSAMPLING_8) { return HAL_ERROR; } /* LIN mode limited to 8-bit data length */ if (huart->Init.WordLength != UART_WORDLENGTH_8B) { return HAL_ERROR; } if (huart->gState == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) UART_InitCallbacksToDefault(huart); if (huart->MspInitCallback == NULL) { huart->MspInitCallback = HAL_UART_MspInit; } /* Init the low level hardware */ huart->MspInitCallback(huart); #else /* Init the low level hardware : GPIO, CLOCK */ HAL_UART_MspInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } huart->gState = HAL_UART_STATE_BUSY; __HAL_UART_DISABLE(huart); /* Set the UART Communication parameters */ if (UART_SetConfig(huart) == HAL_ERROR) { return HAL_ERROR; } if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) { UART_AdvFeatureConfig(huart); } /* In LIN mode, the following bits must be kept cleared: - LINEN and CLKEN bits in the USART_CR2 register, - SCEN and IREN bits in the USART_CR3 register.*/ CLEAR_BIT(huart->Instance->CR2, USART_CR2_CLKEN); CLEAR_BIT(huart->Instance->CR3, (USART_CR3_HDSEL | USART_CR3_IREN | USART_CR3_SCEN)); /* Enable the LIN mode by setting the LINEN bit in the CR2 register */ SET_BIT(huart->Instance->CR2, USART_CR2_LINEN); /* Set the USART LIN Break detection length. */ MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength); __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ return (UART_CheckIdleState(huart)); } /** * @brief Initialize the multiprocessor mode according to the specified * parameters in the UART_InitTypeDef and initialize the associated handle. * @param huart UART handle. * @param Address UART node address (4-, 6-, 7- or 8-bit long). * @param WakeUpMethod Specifies the UART wakeup method. * This parameter can be one of the following values: * @arg @ref UART_WAKEUPMETHOD_IDLELINE WakeUp by an idle line detection * @arg @ref UART_WAKEUPMETHOD_ADDRESSMARK WakeUp by an address mark * @note If the user resorts to idle line detection wake up, the Address parameter * is useless and ignored by the initialization function. * @note If the user resorts to address mark wake up, the address length detection * is configured by default to 4 bits only. For the UART to be able to * manage 6-, 7- or 8-bit long addresses detection, the API * HAL_MultiProcessorEx_AddressLength_Set() must be called after * HAL_MultiProcessor_Init(). * @retval HAL status */ HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check the wake up method parameter */ assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); if (huart->gState == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) UART_InitCallbacksToDefault(huart); if (huart->MspInitCallback == NULL) { huart->MspInitCallback = HAL_UART_MspInit; } /* Init the low level hardware */ huart->MspInitCallback(huart); #else /* Init the low level hardware : GPIO, CLOCK */ HAL_UART_MspInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } huart->gState = HAL_UART_STATE_BUSY; __HAL_UART_DISABLE(huart); /* Set the UART Communication parameters */ if (UART_SetConfig(huart) == HAL_ERROR) { return HAL_ERROR; } if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) { UART_AdvFeatureConfig(huart); } /* In multiprocessor mode, the following bits must be kept cleared: - LINEN and CLKEN bits in the USART_CR2 register, - SCEN, HDSEL and IREN bits in the USART_CR3 register. */ CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); if (WakeUpMethod == UART_WAKEUPMETHOD_ADDRESSMARK) { /* If address mark wake up method is chosen, set the USART address node */ MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)Address << UART_CR2_ADDRESS_LSB_POS)); } /* Set the wake up method by setting the WAKE bit in the CR1 register */ MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod); __HAL_UART_ENABLE(huart); /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ return (UART_CheckIdleState(huart)); } /** * @brief DeInitialize the UART peripheral. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart) { /* Check the UART handle allocation */ if (huart == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param((IS_UART_INSTANCE(huart->Instance)) || (IS_LPUART_INSTANCE(huart->Instance))); huart->gState = HAL_UART_STATE_BUSY; __HAL_UART_DISABLE(huart); huart->Instance->CR1 = 0x0U; huart->Instance->CR2 = 0x0U; huart->Instance->CR3 = 0x0U; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) if (huart->MspDeInitCallback == NULL) { huart->MspDeInitCallback = HAL_UART_MspDeInit; } /* DeInit the low level hardware */ huart->MspDeInitCallback(huart); #else /* DeInit the low level hardware */ HAL_UART_MspDeInit(huart); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ huart->ErrorCode = HAL_UART_ERROR_NONE; huart->gState = HAL_UART_STATE_RESET; huart->RxState = HAL_UART_STATE_RESET; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Initialize the UART MSP. * @param huart UART handle. * @retval None */ __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_MspInit can be implemented in the user file */ } /** * @brief DeInitialize the UART MSP. * @param huart UART handle. * @retval None */ __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_MspDeInit can be implemented in the user file */ } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /** * @brief Register a User UART Callback * To be used instead of the weak predefined callback * @param huart uart handle * @param CallbackID ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID * @param pCallback pointer to the Callback function * @retval HAL status */ HAL_StatusTypeDef HAL_UART_RegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID, pUART_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; return HAL_ERROR; } __HAL_LOCK(huart); if (huart->gState == HAL_UART_STATE_READY) { switch (CallbackID) { case HAL_UART_TX_HALFCOMPLETE_CB_ID : huart->TxHalfCpltCallback = pCallback; break; case HAL_UART_TX_COMPLETE_CB_ID : huart->TxCpltCallback = pCallback; break; case HAL_UART_RX_HALFCOMPLETE_CB_ID : huart->RxHalfCpltCallback = pCallback; break; case HAL_UART_RX_COMPLETE_CB_ID : huart->RxCpltCallback = pCallback; break; case HAL_UART_ERROR_CB_ID : huart->ErrorCallback = pCallback; break; case HAL_UART_ABORT_COMPLETE_CB_ID : huart->AbortCpltCallback = pCallback; break; case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : huart->AbortTransmitCpltCallback = pCallback; break; case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : huart->AbortReceiveCpltCallback = pCallback; break; case HAL_UART_WAKEUP_CB_ID : huart->WakeupCallback = pCallback; break; case HAL_UART_RX_FIFO_FULL_CB_ID : huart->RxFifoFullCallback = pCallback; break; case HAL_UART_TX_FIFO_EMPTY_CB_ID : huart->TxFifoEmptyCallback = pCallback; break; case HAL_UART_MSPINIT_CB_ID : huart->MspInitCallback = pCallback; break; case HAL_UART_MSPDEINIT_CB_ID : huart->MspDeInitCallback = pCallback; break; default : huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; break; } } else if (huart->gState == HAL_UART_STATE_RESET) { switch (CallbackID) { case HAL_UART_MSPINIT_CB_ID : huart->MspInitCallback = pCallback; break; case HAL_UART_MSPDEINIT_CB_ID : huart->MspDeInitCallback = pCallback; break; default : huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; break; } } else { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; } __HAL_UNLOCK(huart); return status; } /** * @brief Unregister an UART Callback * UART callaback is redirected to the weak predefined callback * @param huart uart handle * @param CallbackID ID of the callback to be unregistered * This parameter can be one of the following values: * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID * @retval HAL status */ HAL_StatusTypeDef HAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID) { HAL_StatusTypeDef status = HAL_OK; __HAL_LOCK(huart); if (HAL_UART_STATE_READY == huart->gState) { switch (CallbackID) { case HAL_UART_TX_HALFCOMPLETE_CB_ID : huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ break; case HAL_UART_TX_COMPLETE_CB_ID : huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ break; case HAL_UART_RX_HALFCOMPLETE_CB_ID : huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ break; case HAL_UART_RX_COMPLETE_CB_ID : huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ break; case HAL_UART_ERROR_CB_ID : huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ break; case HAL_UART_ABORT_COMPLETE_CB_ID : huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ break; case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ break; case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ break; case HAL_UART_WAKEUP_CB_ID : huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ break; case HAL_UART_RX_FIFO_FULL_CB_ID : huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ break; case HAL_UART_TX_FIFO_EMPTY_CB_ID : huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ break; case HAL_UART_MSPINIT_CB_ID : huart->MspInitCallback = HAL_UART_MspInit; /* Legacy weak MspInitCallback */ break; case HAL_UART_MSPDEINIT_CB_ID : huart->MspDeInitCallback = HAL_UART_MspDeInit; /* Legacy weak MspDeInitCallback */ break; default : huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; break; } } else if (HAL_UART_STATE_RESET == huart->gState) { switch (CallbackID) { case HAL_UART_MSPINIT_CB_ID : huart->MspInitCallback = HAL_UART_MspInit; break; case HAL_UART_MSPDEINIT_CB_ID : huart->MspDeInitCallback = HAL_UART_MspDeInit; break; default : huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; break; } } else { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; } __HAL_UNLOCK(huart); return status; } /** * @brief Register a User UART Rx Event Callback * To be used instead of the weak predefined callback * @param huart Uart handle * @param pCallback Pointer to the Rx Event Callback function * @retval HAL status */ HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; return HAL_ERROR; } /* Process locked */ __HAL_LOCK(huart); if (huart->gState == HAL_UART_STATE_READY) { huart->RxEventCallback = pCallback; } else { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(huart); return status; } /** * @brief UnRegister the UART Rx Event Callback * UART Rx Event Callback is redirected to the weak HAL_UARTEx_RxEventCallback() predefined callback * @param huart Uart handle * @retval HAL status */ HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(huart); if (huart->gState == HAL_UART_STATE_READY) { huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak UART Rx Event Callback */ } else { huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(huart); return status; } #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup UART_Exported_Functions_Group2 IO operation functions * @brief UART Transmit/Receive functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== This subsection provides a set of functions allowing to manage the UART asynchronous and Half duplex data transfers. (#) There are two mode of transfer: (+) Blocking mode: The communication is performed in polling mode. The HAL status of all data processing is returned by the same function after finishing transfer. (+) Non-Blocking mode: The communication is performed using Interrupts or DMA, These API's return the HAL status. The end of the data processing will be indicated through the dedicated UART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. The HAL_UART_TxCpltCallback(), HAL_UART_RxCpltCallback() user callbacks will be executed respectively at the end of the transmit or Receive process The HAL_UART_ErrorCallback()user callback will be executed when a communication error is detected (#) Blocking mode API's are : (+) HAL_UART_Transmit() (+) HAL_UART_Receive() (#) Non-Blocking mode API's with Interrupt are : (+) HAL_UART_Transmit_IT() (+) HAL_UART_Receive_IT() (+) HAL_UART_IRQHandler() (#) Non-Blocking mode API's with DMA are : (+) HAL_UART_Transmit_DMA() (+) HAL_UART_Receive_DMA() (+) HAL_UART_DMAPause() (+) HAL_UART_DMAResume() (+) HAL_UART_DMAStop() (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: (+) HAL_UART_TxHalfCpltCallback() (+) HAL_UART_TxCpltCallback() (+) HAL_UART_RxHalfCpltCallback() (+) HAL_UART_RxCpltCallback() (+) HAL_UART_ErrorCallback() (#) Non-Blocking mode transfers could be aborted using Abort API's : (+) HAL_UART_Abort() (+) HAL_UART_AbortTransmit() (+) HAL_UART_AbortReceive() (+) HAL_UART_Abort_IT() (+) HAL_UART_AbortTransmit_IT() (+) HAL_UART_AbortReceive_IT() (#) For Abort services based on interrupts (HAL_UART_Abortxxx_IT), a set of Abort Complete Callbacks are provided: (+) HAL_UART_AbortCpltCallback() (+) HAL_UART_AbortTransmitCpltCallback() (+) HAL_UART_AbortReceiveCpltCallback() (#) A Rx Event Reception Callback (Rx event notification) is available for Non_Blocking modes of enhanced reception services: (+) HAL_UARTEx_RxEventCallback() (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. Errors are handled as follows : (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, and HAL_UART_ErrorCallback() user callback is executed. Transfer is kept ongoing on UART side. If user wants to abort it, Abort services should be called by user. (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. Error code is set to allow user to identify error type, and HAL_UART_ErrorCallback() user callback is executed. -@- In the Half duplex communication, it is forbidden to run the transmit and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX can't be useful. @endverbatim * @{ */ /** * @brief Send an amount of data in blocking mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pData. * @note When FIFO mode is enabled, writing a data in the TDR register adds one * data to the TXFIFO. Write operations to the TDR register are performed * when TXFNF flag is set. From hardware perspective, TXFNF flag and * TXE are mapped on the same bit-field. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be sent. * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout) { const uint8_t *pdata8bits; const uint16_t *pdata16bits; uint32_t tickstart; /* Check that a Tx process is not already ongoing */ if (huart->gState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; huart->gState = HAL_UART_STATE_BUSY_TX; /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); huart->TxXferSize = Size; huart->TxXferCount = Size; /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { pdata8bits = NULL; pdata16bits = (const uint16_t *) pData; } else { pdata8bits = pData; pdata16bits = NULL; } __HAL_UNLOCK(huart); while (huart->TxXferCount > 0U) { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (pdata8bits == NULL) { huart->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU); pdata16bits++; } else { huart->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU); pdata8bits++; } huart->TxXferCount--; } if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } /* At end of Tx process, restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in blocking mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pData. * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO * is not empty. Read operations from the RDR register are performed when * RXFNE flag is set. From hardware perspective, RXFNE flag and * RXNE are mapped on the same bit-field. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint8_t *pdata8bits; uint16_t *pdata16bits; uint16_t uhMask; uint32_t tickstart; /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; huart->RxState = HAL_UART_STATE_BUSY_RX; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); huart->RxXferSize = Size; huart->RxXferCount = Size; /* Computation of UART mask to apply to RDR register */ UART_MASK_COMPUTATION(huart); uhMask = huart->Mask; /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { pdata8bits = NULL; pdata16bits = (uint16_t *) pData; } else { pdata8bits = pData; pdata16bits = NULL; } __HAL_UNLOCK(huart); /* as long as data have to be received */ while (huart->RxXferCount > 0U) { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (pdata8bits == NULL) { *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); pdata16bits++; } else { *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); pdata8bits++; } huart->RxXferCount--; } /* At end of Rx process, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Send an amount of data in interrupt mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pData. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be sent. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) { /* Check that a Tx process is not already ongoing */ if (huart->gState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); huart->pTxBuffPtr = pData; huart->TxXferSize = Size; huart->TxXferCount = Size; huart->TxISR = NULL; huart->ErrorCode = HAL_UART_ERROR_NONE; huart->gState = HAL_UART_STATE_BUSY_TX; /* Configure Tx interrupt processing */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { /* Set the Tx ISR function pointer according to the data word length */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { huart->TxISR = UART_TxISR_16BIT_FIFOEN; } else { huart->TxISR = UART_TxISR_8BIT_FIFOEN; } __HAL_UNLOCK(huart); /* Enable the TX FIFO threshold interrupt */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); } else { /* Set the Tx ISR function pointer according to the data word length */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { huart->TxISR = UART_TxISR_16BIT; } else { huart->TxISR = UART_TxISR_8BIT; } __HAL_UNLOCK(huart); /* Enable the Transmit Data Register Empty interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); } return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in interrupt mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pData. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); /* Set Reception type to Standard reception */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; if (!(IS_LPUART_INSTANCE(huart->Instance))) { /* Check that USART RTOEN bit is set */ if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) { /* Enable the UART Receiver Timeout Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); } } return (UART_Start_Receive_IT(huart, pData, Size)); } else { return HAL_BUSY; } } /** * @brief Send an amount of data in DMA mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pData. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be sent. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) { /* Check that a Tx process is not already ongoing */ if (huart->gState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); huart->pTxBuffPtr = pData; huart->TxXferSize = Size; huart->TxXferCount = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; huart->gState = HAL_UART_STATE_BUSY_TX; if (huart->hdmatx != NULL) { /* Set the UART DMA transfer complete callback */ huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt; /* Set the UART DMA Half transfer complete callback */ huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt; /* Set the DMA error callback */ huart->hdmatx->XferErrorCallback = UART_DMAError; /* Set the DMA abort callback */ huart->hdmatx->XferAbortCallback = NULL; /* Enable the UART transmit DMA channel */ if (HAL_DMA_Start_IT(huart->hdmatx, (uint32_t)huart->pTxBuffPtr, (uint32_t)&huart->Instance->TDR, Size) != HAL_OK) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; __HAL_UNLOCK(huart); /* Restore huart->gState to ready */ huart->gState = HAL_UART_STATE_READY; return HAL_ERROR; } } /* Clear the TC flag in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_TCF); __HAL_UNLOCK(huart); /* Enable the DMA transfer for transmit request by setting the DMAT bit in the UART CR3 register */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in DMA mode. * @note When the UART parity is enabled (PCE = 1), the received data contain * the parity bit (MSB position). * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pData. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { /* Check that a Rx process is not already ongoing */ if (huart->RxState == HAL_UART_STATE_READY) { if ((pData == NULL) || (Size == 0U)) { return HAL_ERROR; } __HAL_LOCK(huart); /* Set Reception type to Standard reception */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; if (!(IS_LPUART_INSTANCE(huart->Instance))) { /* Check that USART RTOEN bit is set */ if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) { /* Enable the UART Receiver Timeout Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); } } return (UART_Start_Receive_DMA(huart, pData, Size)); } else { return HAL_BUSY; } } /** * @brief Pause the DMA Transfer. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) { const HAL_UART_StateTypeDef gstate = huart->gState; const HAL_UART_StateTypeDef rxstate = huart->RxState; __HAL_LOCK(huart); if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && (gstate == HAL_UART_STATE_BUSY_TX)) { /* Disable the UART DMA Tx request */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); } if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && (rxstate == HAL_UART_STATE_BUSY_RX)) { /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Disable the UART DMA Rx request */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); } __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Resume the DMA Transfer. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) { __HAL_LOCK(huart); if (huart->gState == HAL_UART_STATE_BUSY_TX) { /* Enable the UART DMA Tx request */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); } if (huart->RxState == HAL_UART_STATE_BUSY_RX) { /* Clear the Overrun flag before resuming the Rx transfer */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ if (huart->Init.Parity != UART_PARITY_NONE) { ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); } ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Enable the UART DMA Rx request */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); } __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Stop the DMA Transfer. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) { /* The Lock is not implemented on this API to allow the user application to call the HAL UART API under callbacks HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback() / HAL_UART_TxHalfCpltCallback / HAL_UART_RxHalfCpltCallback: indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of the stream and the corresponding call back is executed. */ const HAL_UART_StateTypeDef gstate = huart->gState; const HAL_UART_StateTypeDef rxstate = huart->RxState; /* Stop UART DMA Tx request if ongoing */ if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && (gstate == HAL_UART_STATE_BUSY_TX)) { ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Abort the UART DMA Tx channel */ if (huart->hdmatx != NULL) { if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } UART_EndTxTransfer(huart); } /* Stop UART DMA Rx request if ongoing */ if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && (rxstate == HAL_UART_STATE_BUSY_RX)) { ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel */ if (huart->hdmarx != NULL) { if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } UART_EndRxTransfer(huart); } return HAL_OK; } /** * @brief Abort ongoing transfers (blocking mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Tx and Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) * - Set handle State to READY * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart) { /* Disable TXE, TC, RXNE, PE, RXFT, TXFT and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE); /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); } /* Abort the UART DMA Tx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) { /* Disable the UART DMA Tx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ if (huart->hdmatx != NULL) { /* Set the UART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ huart->hdmatx->XferAbortCallback = NULL; if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Abort the UART DMA Rx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* Disable the UART DMA Rx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ if (huart->hdmarx != NULL) { /* Set the UART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ huart->hdmarx->XferAbortCallback = NULL; if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Reset Tx and Rx transfer counters */ huart->TxXferCount = 0U; huart->RxXferCount = 0U; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->gState and huart->RxState to Ready */ huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; huart->ErrorCode = HAL_UART_ERROR_NONE; return HAL_OK; } /** * @brief Abort ongoing Transmit transfer (blocking mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Tx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) * - Set handle State to READY * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart) { /* Disable TCIE, TXEIE and TXFTIE interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); /* Abort the UART DMA Tx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) { /* Disable the UART DMA Tx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ if (huart->hdmatx != NULL) { /* Set the UART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ huart->hdmatx->XferAbortCallback = NULL; if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Reset Tx transfer counter */ huart->TxXferCount = 0U; /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; return HAL_OK; } /** * @brief Abort ongoing Receive transfer (blocking mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) * - Set handle State to READY * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart) { /* Disable PEIE, EIE, RXNEIE and RXFTIE interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE); /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); } /* Abort the UART DMA Rx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* Disable the UART DMA Rx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ if (huart->hdmarx != NULL) { /* Set the UART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ huart->hdmarx->XferAbortCallback = NULL; if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) { if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Reset Rx transfer counter */ huart->RxXferCount = 0U; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; return HAL_OK; } /** * @brief Abort ongoing transfers (Interrupt mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Tx and Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) * - Set handle State to READY * - At abort completion, call user abort complete callback * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be * considered as completed only when user abort complete callback is executed (not when exiting function). * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart) { uint32_t abortcplt = 1U; /* Disable interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_TCIE | USART_CR1_RXNEIE_RXFNEIE | USART_CR1_TXEIE_TXFNFIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); } /* If DMA Tx and/or DMA Rx Handles are associated to UART Handle, DMA Abort complete callbacks should be initialised before any call to DMA Abort functions */ /* DMA Tx Handle is valid */ if (huart->hdmatx != NULL) { /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. Otherwise, set it to NULL */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) { huart->hdmatx->XferAbortCallback = UART_DMATxAbortCallback; } else { huart->hdmatx->XferAbortCallback = NULL; } } /* DMA Rx Handle is valid */ if (huart->hdmarx != NULL) { /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. Otherwise, set it to NULL */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { huart->hdmarx->XferAbortCallback = UART_DMARxAbortCallback; } else { huart->hdmarx->XferAbortCallback = NULL; } } /* Abort the UART DMA Tx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) { /* Disable DMA Tx at UART level */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ if (huart->hdmatx != NULL) { /* UART Tx DMA Abort callback has already been initialised : will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ /* Abort DMA TX */ if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) { huart->hdmatx->XferAbortCallback = NULL; } else { abortcplt = 0U; } } } /* Abort the UART DMA Rx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* Disable the UART DMA Rx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ if (huart->hdmarx != NULL) { /* UART Rx DMA Abort callback has already been initialised : will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ /* Abort DMA RX */ if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) { huart->hdmarx->XferAbortCallback = NULL; abortcplt = 1U; } else { abortcplt = 0U; } } } /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ if (abortcplt == 1U) { /* Reset Tx and Rx transfer counters */ huart->TxXferCount = 0U; huart->RxXferCount = 0U; /* Clear ISR function pointers */ huart->RxISR = NULL; huart->TxISR = NULL; /* Reset errorCode */ huart->ErrorCode = HAL_UART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->gState and huart->RxState to Ready */ huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort complete callback */ huart->AbortCpltCallback(huart); #else /* Call legacy weak Abort complete callback */ HAL_UART_AbortCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } return HAL_OK; } /** * @brief Abort ongoing Transmit transfer (Interrupt mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Tx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) * - Set handle State to READY * - At abort completion, call user abort complete callback * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be * considered as completed only when user abort complete callback is executed (not when exiting function). * @retval HAL status */ HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart) { /* Disable interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); /* Abort the UART DMA Tx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) { /* Disable the UART DMA Tx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ if (huart->hdmatx != NULL) { /* Set the UART DMA Abort callback : will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ huart->hdmatx->XferAbortCallback = UART_DMATxOnlyAbortCallback; /* Abort DMA TX */ if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) { /* Call Directly huart->hdmatx->XferAbortCallback function in case of error */ huart->hdmatx->XferAbortCallback(huart->hdmatx); } } else { /* Reset Tx transfer counter */ huart->TxXferCount = 0U; /* Clear TxISR function pointers */ huart->TxISR = NULL; /* Restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Transmit Complete Callback */ huart->AbortTransmitCpltCallback(huart); #else /* Call legacy weak Abort Transmit Complete Callback */ HAL_UART_AbortTransmitCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } else { /* Reset Tx transfer counter */ huart->TxXferCount = 0U; /* Clear TxISR function pointers */ huart->TxISR = NULL; /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Transmit Complete Callback */ huart->AbortTransmitCpltCallback(huart); #else /* Call legacy weak Abort Transmit Complete Callback */ HAL_UART_AbortTransmitCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } return HAL_OK; } /** * @brief Abort ongoing Receive transfer (Interrupt mode). * @param huart UART handle. * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable UART Interrupts (Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) * - Set handle State to READY * - At abort completion, call user abort complete callback * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be * considered as completed only when user abort complete callback is executed (not when exiting function). * @retval HAL status */ HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart) { /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); } /* Abort the UART DMA Rx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* Disable the UART DMA Rx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ if (huart->hdmarx != NULL) { /* Set the UART DMA Abort callback : will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ huart->hdmarx->XferAbortCallback = UART_DMARxOnlyAbortCallback; /* Abort DMA RX */ if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) { /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ huart->hdmarx->XferAbortCallback(huart->hdmarx); } } else { /* Reset Rx transfer counter */ huart->RxXferCount = 0U; /* Clear RxISR function pointer */ huart->pRxBuffPtr = NULL; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Receive Complete Callback */ huart->AbortReceiveCpltCallback(huart); #else /* Call legacy weak Abort Receive Complete Callback */ HAL_UART_AbortReceiveCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } else { /* Reset Rx transfer counter */ huart->RxXferCount = 0U; /* Clear RxISR function pointer */ huart->pRxBuffPtr = NULL; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Receive Complete Callback */ huart->AbortReceiveCpltCallback(huart); #else /* Call legacy weak Abort Receive Complete Callback */ HAL_UART_AbortReceiveCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } return HAL_OK; } /** * @brief Handle UART interrupt request. * @param huart UART handle. * @retval None */ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) { uint32_t isrflags = READ_REG(huart->Instance->ISR); uint32_t cr1its = READ_REG(huart->Instance->CR1); uint32_t cr3its = READ_REG(huart->Instance->CR3); uint32_t errorflags; uint32_t errorcode; /* If no error occurs */ errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF)); if (errorflags == 0U) { /* UART in mode Receiver ---------------------------------------------------*/ if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_RXFTIE) != 0U))) { if (huart->RxISR != NULL) { huart->RxISR(huart); } return; } } /* If some errors occur */ if ((errorflags != 0U) && ((((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE)) != 0U)))) { /* UART parity error interrupt occurred -------------------------------------*/ if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); huart->ErrorCode |= HAL_UART_ERROR_PE; } /* UART frame error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); huart->ErrorCode |= HAL_UART_ERROR_FE; } /* UART noise error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); huart->ErrorCode |= HAL_UART_ERROR_NE; } /* UART Over-Run interrupt occurred -----------------------------------------*/ if (((isrflags & USART_ISR_ORE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); huart->ErrorCode |= HAL_UART_ERROR_ORE; } /* UART Receiver Timeout interrupt occurred ---------------------------------*/ if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); huart->ErrorCode |= HAL_UART_ERROR_RTO; } /* Call UART Error Call back function if need be ----------------------------*/ if (huart->ErrorCode != HAL_UART_ERROR_NONE) { /* UART in mode Receiver --------------------------------------------------*/ if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_RXFTIE) != 0U))) { if (huart->RxISR != NULL) { huart->RxISR(huart); } } /* If Error is to be considered as blocking : - Receiver Timeout error in Reception - Overrun error in Reception - any error occurs in DMA mode reception */ errorcode = huart->ErrorCode; if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) || ((errorcode & (HAL_UART_ERROR_RTO | HAL_UART_ERROR_ORE)) != 0U)) { /* Blocking error : transfer is aborted Set the UART state ready to be able to start again the process, Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ UART_EndRxTransfer(huart); /* Abort the UART DMA Rx channel if enabled */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* Disable the UART DMA Rx request if enabled */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Abort the UART DMA Rx channel */ if (huart->hdmarx != NULL) { /* Set the UART DMA Abort callback : will lead to call HAL_UART_ErrorCallback() at end of DMA abort procedure */ huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError; /* Abort DMA RX */ if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) { /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ huart->hdmarx->XferAbortCallback(huart->hdmarx); } } else { /* Call user error callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } else { /* Call user error callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } else { /* Non Blocking error : transfer could go on. Error is notified to user through user error callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ huart->ErrorCode = HAL_UART_ERROR_NONE; } } return; } /* End if some error occurs */ /* Check current reception Mode : If Reception till IDLE event has been selected : */ if ((huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) && ((isrflags & USART_ISR_IDLE) != 0U) && ((cr1its & USART_ISR_IDLE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); /* Check if DMA mode is enabled in UART */ if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) { /* DMA mode enabled */ /* Check received length : If all expected data are received, do nothing, (DMA cplt callback will be called). Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ uint16_t nb_remaining_rx_data = (uint16_t) __HAL_DMA_GET_COUNTER(huart->hdmarx); if ((nb_remaining_rx_data > 0U) && (nb_remaining_rx_data < huart->RxXferSize)) { /* Reception is not complete */ huart->RxXferCount = nb_remaining_rx_data; /* In Normal mode, end DMA xfer and HAL UART Rx process*/ if (HAL_IS_BIT_CLR(huart->hdmarx->Instance->CCR, DMA_CCR_CIRC)) { /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Disable the DMA transfer for the receiver request by resetting the DMAR bit in the UART CR3 register */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* At end of Rx process, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); /* Last bytes received, so no need as the abort is immediate */ (void)HAL_DMA_Abort(huart->hdmarx); } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } return; } else { /* DMA mode not enabled */ /* Check received length : If all expected data are received, do nothing. Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ uint16_t nb_rx_data = huart->RxXferSize - huart->RxXferCount; if ((huart->RxXferCount > 0U) && (nb_rx_data > 0U)) { /* Disable the UART Parity Error Interrupt and RXNE interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); /* Disable the UART Error Interrupt:(Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* Rx process is completed, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Clear RxISR function pointer */ huart->RxISR = NULL; ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxEventCallback(huart, nb_rx_data); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, nb_rx_data); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } return; } } /* UART wakeup from Stop mode interrupt occurred ---------------------------*/ if (((isrflags & USART_ISR_WUF) != 0U) && ((cr3its & USART_CR3_WUFIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_WUF); /* UART Rx state is not reset as a reception process might be ongoing. If UART handle state fields need to be reset to READY, this could be done in Wakeup callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Wakeup Callback */ huart->WakeupCallback(huart); #else /* Call legacy weak Wakeup Callback */ HAL_UARTEx_WakeupCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ return; } /* UART in mode Transmitter ------------------------------------------------*/ if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) || ((cr3its & USART_CR3_TXFTIE) != 0U))) { if (huart->TxISR != NULL) { huart->TxISR(huart); } return; } /* UART in mode Transmitter (transmission end) -----------------------------*/ if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) { UART_EndTransmit_IT(huart); return; } /* UART TX Fifo Empty occurred ----------------------------------------------*/ if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) { #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Tx Fifo Empty Callback */ huart->TxFifoEmptyCallback(huart); #else /* Call legacy weak Tx Fifo Empty Callback */ HAL_UARTEx_TxFifoEmptyCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ return; } /* UART RX Fifo Full occurred ----------------------------------------------*/ if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) { #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Rx Fifo Full Callback */ huart->RxFifoFullCallback(huart); #else /* Call legacy weak Rx Fifo Full Callback */ HAL_UARTEx_RxFifoFullCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ return; } } /** * @brief Tx Transfer completed callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_TxCpltCallback can be implemented in the user file. */ } /** * @brief Tx Half Transfer completed callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE: This function should not be modified, when the callback is needed, the HAL_UART_TxHalfCpltCallback can be implemented in the user file. */ } /** * @brief Rx Transfer completed callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_RxCpltCallback can be implemented in the user file. */ } /** * @brief Rx Half Transfer completed callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE: This function should not be modified, when the callback is needed, the HAL_UART_RxHalfCpltCallback can be implemented in the user file. */ } /** * @brief UART error callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_ErrorCallback can be implemented in the user file. */ } /** * @brief UART Abort Complete callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_AbortCpltCallback can be implemented in the user file. */ } /** * @brief UART Abort Complete callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_AbortTransmitCpltCallback can be implemented in the user file. */ } /** * @brief UART Abort Receive Complete callback. * @param huart UART handle. * @retval None */ __weak void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_AbortReceiveCpltCallback can be implemented in the user file. */ } /** * @brief Reception Event Callback (Rx event notification called after use of advanced reception service). * @param huart UART handle * @param Size Number of data available in application reception buffer (indicates a position in * reception buffer until which, data are available) * @retval None */ __weak void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); UNUSED(Size); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UARTEx_RxEventCallback can be implemented in the user file. */ } /** * @} */ /** @defgroup UART_Exported_Functions_Group3 Peripheral Control functions * @brief UART control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the UART. (+) HAL_UART_ReceiverTimeout_Config() API allows to configure the receiver timeout value on the fly (+) HAL_UART_EnableReceiverTimeout() API enables the receiver timeout feature (+) HAL_UART_DisableReceiverTimeout() API disables the receiver timeout feature (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode (+) HAL_MultiProcessor_DisableMuteMode() API disables mute mode (+) HAL_MultiProcessor_EnterMuteMode() API enters mute mode (+) UART_SetConfig() API configures the UART peripheral (+) UART_AdvFeatureConfig() API optionally configures the UART advanced features (+) UART_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization (+) HAL_HalfDuplex_EnableTransmitter() API disables receiver and enables transmitter (+) HAL_HalfDuplex_EnableReceiver() API disables transmitter and enables receiver (+) HAL_LIN_SendBreak() API transmits the break characters @endverbatim * @{ */ /** * @brief Update on the fly the receiver timeout value in RTOR register. * @param huart Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param TimeoutValue receiver timeout value in number of baud blocks. The timeout * value must be less or equal to 0x0FFFFFFFF. * @retval None */ void HAL_UART_ReceiverTimeout_Config(UART_HandleTypeDef *huart, uint32_t TimeoutValue) { if (!(IS_LPUART_INSTANCE(huart->Instance))) { assert_param(IS_UART_RECEIVER_TIMEOUT_VALUE(TimeoutValue)); MODIFY_REG(huart->Instance->RTOR, USART_RTOR_RTO, TimeoutValue); } } /** * @brief Enable the UART receiver timeout feature. * @param huart Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_EnableReceiverTimeout(UART_HandleTypeDef *huart) { if (!(IS_LPUART_INSTANCE(huart->Instance))) { if (huart->gState == HAL_UART_STATE_READY) { /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Set the USART RTOEN bit */ SET_BIT(huart->Instance->CR2, USART_CR2_RTOEN); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } else { return HAL_BUSY; } } else { return HAL_ERROR; } } /** * @brief Disable the UART receiver timeout feature. * @param huart Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DisableReceiverTimeout(UART_HandleTypeDef *huart) { if (!(IS_LPUART_INSTANCE(huart->Instance))) { if (huart->gState == HAL_UART_STATE_READY) { /* Process Locked */ __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Clear the USART RTOEN bit */ CLEAR_BIT(huart->Instance->CR2, USART_CR2_RTOEN); huart->gState = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_OK; } else { return HAL_BUSY; } } else { return HAL_ERROR; } } /** * @brief Enable UART in mute mode (does not mean UART enters mute mode; * to enter mute mode, HAL_MultiProcessor_EnterMuteMode() API must be called). * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart) { __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Enable USART mute mode by setting the MME bit in the CR1 register */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_MME); huart->gState = HAL_UART_STATE_READY; return (UART_CheckIdleState(huart)); } /** * @brief Disable UART mute mode (does not mean the UART actually exits mute mode * as it may not have been in mute mode at this very moment). * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart) { __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Disable USART mute mode by clearing the MME bit in the CR1 register */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_MME); huart->gState = HAL_UART_STATE_READY; return (UART_CheckIdleState(huart)); } /** * @brief Enter UART mute mode (means UART actually enters mute mode). * @note To exit from mute mode, HAL_MultiProcessor_DisableMuteMode() API must be called. * @param huart UART handle. * @retval None */ void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) { __HAL_UART_SEND_REQ(huart, UART_MUTE_MODE_REQUEST); } /** * @brief Enable the UART transmitter and disable the UART receiver. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) { __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Clear TE and RE bits */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TE); huart->gState = HAL_UART_STATE_READY; __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Enable the UART receiver and disable the UART transmitter. * @param huart UART handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) { __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Clear TE and RE bits */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RE); huart->gState = HAL_UART_STATE_READY; __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief Transmit break characters. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) { /* Check the parameters */ assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); __HAL_LOCK(huart); huart->gState = HAL_UART_STATE_BUSY; /* Send break characters */ __HAL_UART_SEND_REQ(huart, UART_SENDBREAK_REQUEST); huart->gState = HAL_UART_STATE_READY; __HAL_UNLOCK(huart); return HAL_OK; } /** * @} */ /** @defgroup UART_Exported_Functions_Group4 Peripheral State and Error functions * @brief UART Peripheral State functions * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### ============================================================================== [..] This subsection provides functions allowing to : (+) Return the UART handle state. (+) Return the UART handle error code @endverbatim * @{ */ /** * @brief Return the UART handle state. * @param huart Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART. * @retval HAL state */ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart) { uint32_t temp1; uint32_t temp2; temp1 = huart->gState; temp2 = huart->RxState; return (HAL_UART_StateTypeDef)(temp1 | temp2); } /** * @brief Return the UART handle error code. * @param huart Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART. * @retval UART Error Code */ uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart) { return huart->ErrorCode; } /** * @} */ /** * @} */ /** @defgroup UART_Private_Functions UART Private Functions * @{ */ /** * @brief Initialize the callbacks to their default values. * @param huart UART handle. * @retval none */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart) { /* Init the UART Callback settings */ huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak RxEventCallback */ } #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ /** * @brief Configure the UART peripheral. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart) { uint32_t tmpreg; uint16_t brrtemp; UART_ClockSourceTypeDef clocksource; uint32_t usartdiv; HAL_StatusTypeDef ret = HAL_OK; uint32_t lpuart_ker_ck_pres; uint32_t pclk; /* Check the parameters */ assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); if (UART_INSTANCE_LOWPOWER(huart)) { assert_param(IS_LPUART_STOPBITS(huart->Init.StopBits)); } else { assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); assert_param(IS_UART_ONE_BIT_SAMPLE(huart->Init.OneBitSampling)); } assert_param(IS_UART_PARITY(huart->Init.Parity)); assert_param(IS_UART_MODE(huart->Init.Mode)); assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl)); assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); assert_param(IS_UART_PRESCALER(huart->Init.ClockPrescaler)); /*-------------------------- USART CR1 Configuration -----------------------*/ /* Clear M, PCE, PS, TE, RE and OVER8 bits and configure * the UART Word Length, Parity, Mode and oversampling: * set the M bits according to huart->Init.WordLength value * set PCE and PS bits according to huart->Init.Parity value * set TE and RE bits according to huart->Init.Mode value * set OVER8 bit according to huart->Init.OverSampling value */ tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling ; MODIFY_REG(huart->Instance->CR1, USART_CR1_FIELDS, tmpreg); /*-------------------------- USART CR2 Configuration -----------------------*/ /* Configure the UART Stop Bits: Set STOP[13:12] bits according * to huart->Init.StopBits value */ MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits); /*-------------------------- USART CR3 Configuration -----------------------*/ /* Configure * - UART HardWare Flow Control: set CTSE and RTSE bits according * to huart->Init.HwFlowCtl value * - one-bit sampling method versus three samples' majority rule according * to huart->Init.OneBitSampling (not applicable to LPUART) */ tmpreg = (uint32_t)huart->Init.HwFlowCtl; if (!(UART_INSTANCE_LOWPOWER(huart))) { tmpreg |= huart->Init.OneBitSampling; } MODIFY_REG(huart->Instance->CR3, USART_CR3_FIELDS, tmpreg); /*-------------------------- USART PRESC Configuration -----------------------*/ /* Configure * - UART Clock Prescaler : set PRESCALER according to huart->Init.ClockPrescaler value */ MODIFY_REG(huart->Instance->PRESC, USART_PRESC_PRESCALER, huart->Init.ClockPrescaler); /*-------------------------- USART BRR Configuration -----------------------*/ UART_GETCLOCKSOURCE(huart, clocksource); /* Check LPUART instance */ if (UART_INSTANCE_LOWPOWER(huart)) { /* Retrieve frequency clock */ switch (clocksource) { case UART_CLOCKSOURCE_PCLK1: pclk = HAL_RCC_GetPCLK1Freq(); break; case UART_CLOCKSOURCE_HSI: pclk = (uint32_t) HSI_VALUE; break; case UART_CLOCKSOURCE_SYSCLK: pclk = HAL_RCC_GetSysClockFreq(); break; case UART_CLOCKSOURCE_LSE: pclk = (uint32_t) LSE_VALUE; break; default: pclk = 0U; ret = HAL_ERROR; break; } /* If proper clock source reported */ if (pclk != 0U) { /* Compute clock after Prescaler */ lpuart_ker_ck_pres = (pclk / UARTPrescTable[huart->Init.ClockPrescaler]); /* Ensure that Frequency clock is in the range [3 * baudrate, 4096 * baudrate] */ if ((lpuart_ker_ck_pres < (3U * huart->Init.BaudRate)) || (lpuart_ker_ck_pres > (4096U * huart->Init.BaudRate))) { ret = HAL_ERROR; } else { /* Check computed UsartDiv value is in allocated range (it is forbidden to write values lower than 0x300 in the LPUART_BRR register) */ usartdiv = (uint32_t)(UART_DIV_LPUART(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); if ((usartdiv >= LPUART_BRR_MIN) && (usartdiv <= LPUART_BRR_MAX)) { huart->Instance->BRR = usartdiv; } else { ret = HAL_ERROR; } } /* if ( (lpuart_ker_ck_pres < (3 * huart->Init.BaudRate) ) || (lpuart_ker_ck_pres > (4096 * huart->Init.BaudRate) )) */ } /* if (pclk != 0) */ } /* Check UART Over Sampling to set Baud Rate Register */ else if (huart->Init.OverSampling == UART_OVERSAMPLING_8) { switch (clocksource) { case UART_CLOCKSOURCE_PCLK1: pclk = HAL_RCC_GetPCLK1Freq(); break; case UART_CLOCKSOURCE_PCLK2: pclk = HAL_RCC_GetPCLK2Freq(); break; case UART_CLOCKSOURCE_HSI: pclk = (uint32_t) HSI_VALUE; break; case UART_CLOCKSOURCE_SYSCLK: pclk = HAL_RCC_GetSysClockFreq(); break; case UART_CLOCKSOURCE_LSE: pclk = (uint32_t) LSE_VALUE; break; default: pclk = 0U; ret = HAL_ERROR; break; } /* USARTDIV must be greater than or equal to 0d16 */ if (pclk != 0U) { usartdiv = (uint32_t)(UART_DIV_SAMPLING8(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) { brrtemp = (uint16_t)(usartdiv & 0xFFF0U); brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); huart->Instance->BRR = brrtemp; } else { ret = HAL_ERROR; } } } else { switch (clocksource) { case UART_CLOCKSOURCE_PCLK1: pclk = HAL_RCC_GetPCLK1Freq(); break; case UART_CLOCKSOURCE_PCLK2: pclk = HAL_RCC_GetPCLK2Freq(); break; case UART_CLOCKSOURCE_HSI: pclk = (uint32_t) HSI_VALUE; break; case UART_CLOCKSOURCE_SYSCLK: pclk = HAL_RCC_GetSysClockFreq(); break; case UART_CLOCKSOURCE_LSE: pclk = (uint32_t) LSE_VALUE; break; default: pclk = 0U; ret = HAL_ERROR; break; } if (pclk != 0U) { /* USARTDIV must be greater than or equal to 0d16 */ usartdiv = (uint32_t)(UART_DIV_SAMPLING16(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) { huart->Instance->BRR = (uint16_t)usartdiv; } else { ret = HAL_ERROR; } } } /* Initialize the number of data to process during RX/TX ISR execution */ huart->NbTxDataToProcess = 1; huart->NbRxDataToProcess = 1; /* Clear ISR function pointers */ huart->RxISR = NULL; huart->TxISR = NULL; return ret; } /** * @brief Configure the UART peripheral advanced features. * @param huart UART handle. * @retval None */ void UART_AdvFeatureConfig(UART_HandleTypeDef *huart) { /* Check whether the set of advanced features to configure is properly set */ assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit)); /* if required, configure TX pin active level inversion */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) { assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert)); MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert); } /* if required, configure RX pin active level inversion */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) { assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert)); MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert); } /* if required, configure data inversion */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) { assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert)); MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert); } /* if required, configure RX/TX pins swap */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) { assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap)); MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap); } /* if required, configure RX overrun detection disabling */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) { assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable)); MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable); } /* if required, configure DMA disabling on reception error */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) { assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError)); MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError); } /* if required, configure auto Baud rate detection scheme */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) { assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(huart->Instance)); assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable)); MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable); /* set auto Baudrate detection parameters if detection is enabled */ if (huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) { assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode)); MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode); } } /* if required, configure MSB first on communication line */ if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) { assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst)); MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst); } } /** * @brief Check the UART Idle State. * @param huart UART handle. * @retval HAL status */ HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart) { uint32_t tickstart; /* Initialize the UART ErrorCode */ huart->ErrorCode = HAL_UART_ERROR_NONE; /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); /* Check if the Transmitter is enabled */ if ((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) { /* Wait until TEACK flag is set */ if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) { /* Timeout occurred */ return HAL_TIMEOUT; } } /* Check if the Receiver is enabled */ if ((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) { /* Wait until REACK flag is set */ if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) { /* Timeout occurred */ return HAL_TIMEOUT; } } /* Initialize the UART State */ huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; __HAL_UNLOCK(huart); return HAL_OK; } /** * @brief This function handles UART Communication Timeout. It waits * until a flag is no longer in the specified status. * @param huart UART handle. * @param Flag Specifies the UART flag to check * @param Status The actual Flag status (SET or RESET) * @param Tickstart Tick start value * @param Timeout Timeout duration * @retval HAL status */ HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) { /* Wait until flag is set */ while ((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) { /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; __HAL_UNLOCK(huart); return HAL_TIMEOUT; } if (READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) { if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RTOF) == SET) { /* Clear Receiver Timeout flag*/ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ErrorCode = HAL_UART_ERROR_RTO; /* Process Unlocked */ __HAL_UNLOCK(huart); return HAL_TIMEOUT; } } } } return HAL_OK; } /** * @brief Start Receive operation in interrupt mode. * @note This function could be called by all HAL UART API providing reception in Interrupt mode. * @note When calling this function, parameters validity is considered as already checked, * i.e. Rx State, buffer address, ... * UART Handle is assumed as Locked. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { huart->pRxBuffPtr = pData; huart->RxXferSize = Size; huart->RxXferCount = Size; huart->RxISR = NULL; /* Computation of UART mask to apply to RDR register */ UART_MASK_COMPUTATION(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; huart->RxState = HAL_UART_STATE_BUSY_RX; /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Configure Rx interrupt processing */ if ((huart->FifoMode == UART_FIFOMODE_ENABLE) && (Size >= huart->NbRxDataToProcess)) { /* Set the Rx ISR function pointer according to the data word length */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { huart->RxISR = UART_RxISR_16BIT_FIFOEN; } else { huart->RxISR = UART_RxISR_8BIT_FIFOEN; } __HAL_UNLOCK(huart); /* Enable the UART Parity Error interrupt and RX FIFO Threshold interrupt */ if (huart->Init.Parity != UART_PARITY_NONE) { ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); } ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); } else { /* Set the Rx ISR function pointer according to the data word length */ if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) { huart->RxISR = UART_RxISR_16BIT; } else { huart->RxISR = UART_RxISR_8BIT; } __HAL_UNLOCK(huart); /* Enable the UART Parity Error interrupt and Data Register Not Empty interrupt */ if (huart->Init.Parity != UART_PARITY_NONE) { ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); } else { ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); } } return HAL_OK; } /** * @brief Start Receive operation in DMA mode. * @note This function could be called by all HAL UART API providing reception in DMA mode. * @note When calling this function, parameters validity is considered as already checked, * i.e. Rx State, buffer address, ... * UART Handle is assumed as Locked. * @param huart UART handle. * @param pData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { huart->pRxBuffPtr = pData; huart->RxXferSize = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; huart->RxState = HAL_UART_STATE_BUSY_RX; if (huart->hdmarx != NULL) { /* Set the UART DMA transfer complete callback */ huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt; /* Set the UART DMA Half transfer complete callback */ huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt; /* Set the DMA error callback */ huart->hdmarx->XferErrorCallback = UART_DMAError; /* Set the DMA abort callback */ huart->hdmarx->XferAbortCallback = NULL; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->RDR, (uint32_t)huart->pRxBuffPtr, Size) != HAL_OK) { /* Set error code to DMA */ huart->ErrorCode = HAL_UART_ERROR_DMA; __HAL_UNLOCK(huart); /* Restore huart->RxState to ready */ huart->RxState = HAL_UART_STATE_READY; return HAL_ERROR; } } __HAL_UNLOCK(huart); /* Enable the UART Parity Error Interrupt */ if (huart->Init.Parity != UART_PARITY_NONE) { ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); } /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Enable the DMA transfer for the receiver request by setting the DMAR bit in the UART CR3 register */ ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); return HAL_OK; } /** * @brief End ongoing Tx transfer on UART peripheral (following error detection or Transmit completion). * @param huart UART handle. * @retval None */ static void UART_EndTxTransfer(UART_HandleTypeDef *huart) { /* Disable TXEIE, TCIE, TXFT interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_TXFTIE)); /* At end of Tx process, restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; } /** * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). * @param huart UART handle. * @retval None */ static void UART_EndRxTransfer(UART_HandleTypeDef *huart) { /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* In case of reception waiting for IDLE event, disable also the IDLE IE interrupt source */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); } /* At end of Rx process, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Reset RxIsr function pointer */ huart->RxISR = NULL; } /** * @brief DMA UART transmit process complete callback. * @param hdma DMA handle. * @retval None */ static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); /* DMA Normal mode */ if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { huart->TxXferCount = 0U; /* Disable the DMA transfer for transmit request by resetting the DMAT bit in the UART CR3 register */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); /* Enable the UART Transmit Complete Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); } /* DMA Circular mode */ else { #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Tx complete callback*/ huart->TxCpltCallback(huart); #else /*Call legacy weak Tx complete callback*/ HAL_UART_TxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } /** * @brief DMA UART transmit process half complete callback. * @param hdma DMA handle. * @retval None */ static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Tx Half complete callback*/ huart->TxHalfCpltCallback(huart); #else /*Call legacy weak Tx Half complete callback*/ HAL_UART_TxHalfCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART receive process complete callback. * @param hdma DMA handle. * @retval None */ static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); /* DMA Normal mode */ if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { huart->RxXferCount = 0U; /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Disable the DMA transfer for the receiver request by resetting the DMAR bit in the UART CR3 register */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* At end of Rx process, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; /* If Reception till IDLE event has been selected, Disable IDLE Interrupt */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); } } /* Check current reception Mode : If Reception till IDLE event has been selected : use Rx Event callback */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } else { /* In other cases : use Rx Complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxCpltCallback(huart); #else /*Call legacy weak Rx complete callback*/ HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } /** * @brief DMA UART receive process half complete callback. * @param hdma DMA handle. * @retval None */ static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); /* Check current reception Mode : If Reception till IDLE event has been selected : use Rx Event callback */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize / 2U); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize / 2U); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } else { /* In other cases : use Rx Half Complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Half complete callback*/ huart->RxHalfCpltCallback(huart); #else /*Call legacy weak Rx Half complete callback*/ HAL_UART_RxHalfCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } /** * @brief DMA UART communication error callback. * @param hdma DMA handle. * @retval None */ static void UART_DMAError(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); const HAL_UART_StateTypeDef gstate = huart->gState; const HAL_UART_StateTypeDef rxstate = huart->RxState; /* Stop UART DMA Tx request if ongoing */ if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && (gstate == HAL_UART_STATE_BUSY_TX)) { huart->TxXferCount = 0U; UART_EndTxTransfer(huart); } /* Stop UART DMA Rx request if ongoing */ if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && (rxstate == HAL_UART_STATE_BUSY_RX)) { huart->RxXferCount = 0U; UART_EndRxTransfer(huart); } huart->ErrorCode |= HAL_UART_ERROR_DMA; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART communication abort callback, when initiated by HAL services on Error * (To be called at end of DMA Abort procedure following error occurrence). * @param hdma DMA handle. * @retval None */ static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); huart->RxXferCount = 0U; huart->TxXferCount = 0U; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART Tx communication abort callback, when initiated by user * (To be called at end of DMA Tx Abort procedure following user abort request). * @note When this callback is executed, User Abort complete call back is called only if no * Abort still ongoing for Rx DMA Handle. * @param hdma DMA handle. * @retval None */ static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); huart->hdmatx->XferAbortCallback = NULL; /* Check if an Abort process is still ongoing */ if (huart->hdmarx != NULL) { if (huart->hdmarx->XferAbortCallback != NULL) { return; } } /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ huart->TxXferCount = 0U; huart->RxXferCount = 0U; /* Reset errorCode */ huart->ErrorCode = HAL_UART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Restore huart->gState and huart->RxState to Ready */ huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Call user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort complete callback */ huart->AbortCpltCallback(huart); #else /* Call legacy weak Abort complete callback */ HAL_UART_AbortCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART Rx communication abort callback, when initiated by user * (To be called at end of DMA Rx Abort procedure following user abort request). * @note When this callback is executed, User Abort complete call back is called only if no * Abort still ongoing for Tx DMA Handle. * @param hdma DMA handle. * @retval None */ static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); huart->hdmarx->XferAbortCallback = NULL; /* Check if an Abort process is still ongoing */ if (huart->hdmatx != NULL) { if (huart->hdmatx->XferAbortCallback != NULL) { return; } } /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ huart->TxXferCount = 0U; huart->RxXferCount = 0U; /* Reset errorCode */ huart->ErrorCode = HAL_UART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->gState and huart->RxState to Ready */ huart->gState = HAL_UART_STATE_READY; huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Call user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort complete callback */ huart->AbortCpltCallback(huart); #else /* Call legacy weak Abort complete callback */ HAL_UART_AbortCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART Tx communication abort callback, when initiated by user by a call to * HAL_UART_AbortTransmit_IT API (Abort only Tx transfer) * (This callback is executed at end of DMA Tx Abort procedure following user abort request, * and leads to user Tx Abort Complete callback execution). * @param hdma DMA handle. * @retval None */ static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); huart->TxXferCount = 0U; /* Flush the whole TX FIFO (if needed) */ if (huart->FifoMode == UART_FIFOMODE_ENABLE) { __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); } /* Restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; /* Call user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Transmit Complete Callback */ huart->AbortTransmitCpltCallback(huart); #else /* Call legacy weak Abort Transmit Complete Callback */ HAL_UART_AbortTransmitCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief DMA UART Rx communication abort callback, when initiated by user by a call to * HAL_UART_AbortReceive_IT API (Abort only Rx transfer) * (This callback is executed at end of DMA Rx Abort procedure following user abort request, * and leads to user Rx Abort Complete callback execution). * @param hdma DMA handle. * @retval None */ static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; huart->RxXferCount = 0U; /* Clear the Error flags in the ICR register */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); /* Discard the received data */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); /* Restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Call user Abort complete callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /* Call registered Abort Receive Complete Callback */ huart->AbortReceiveCpltCallback(huart); #else /* Call legacy weak Abort Receive Complete Callback */ HAL_UART_AbortReceiveCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief TX interrupt handler for 7 or 8 bits data word length . * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Transmit_IT(). * @param huart UART handle. * @retval None */ static void UART_TxISR_8BIT(UART_HandleTypeDef *huart) { /* Check that a Tx process is ongoing */ if (huart->gState == HAL_UART_STATE_BUSY_TX) { if (huart->TxXferCount == 0U) { /* Disable the UART Transmit Data Register Empty Interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); /* Enable the UART Transmit Complete Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); } else { huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); huart->pTxBuffPtr++; huart->TxXferCount--; } } } /** * @brief TX interrupt handler for 9 bits data word length. * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Transmit_IT(). * @param huart UART handle. * @retval None */ static void UART_TxISR_16BIT(UART_HandleTypeDef *huart) { const uint16_t *tmp; /* Check that a Tx process is ongoing */ if (huart->gState == HAL_UART_STATE_BUSY_TX) { if (huart->TxXferCount == 0U) { /* Disable the UART Transmit Data Register Empty Interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); /* Enable the UART Transmit Complete Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); } else { tmp = (const uint16_t *) huart->pTxBuffPtr; huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); huart->pTxBuffPtr += 2U; huart->TxXferCount--; } } } /** * @brief TX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Transmit_IT(). * @param huart UART handle. * @retval None */ static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) { uint16_t nb_tx_data; /* Check that a Tx process is ongoing */ if (huart->gState == HAL_UART_STATE_BUSY_TX) { for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) { if (huart->TxXferCount == 0U) { /* Disable the TX FIFO threshold interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); /* Enable the UART Transmit Complete Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); break; /* force exit loop */ } else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) { huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); huart->pTxBuffPtr++; huart->TxXferCount--; } else { /* Nothing to do */ } } } } /** * @brief TX interrupt handler for 9 bits data word length and FIFO mode is enabled. * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Transmit_IT(). * @param huart UART handle. * @retval None */ static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) { const uint16_t *tmp; uint16_t nb_tx_data; /* Check that a Tx process is ongoing */ if (huart->gState == HAL_UART_STATE_BUSY_TX) { for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) { if (huart->TxXferCount == 0U) { /* Disable the TX FIFO threshold interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); /* Enable the UART Transmit Complete Interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); break; /* force exit loop */ } else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) { tmp = (const uint16_t *) huart->pTxBuffPtr; huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); huart->pTxBuffPtr += 2U; huart->TxXferCount--; } else { /* Nothing to do */ } } } } /** * @brief Wrap up transmission in non-blocking mode. * @param huart pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ static void UART_EndTransmit_IT(UART_HandleTypeDef *huart) { /* Disable the UART Transmit Complete Interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TCIE); /* Tx process is ended, restore huart->gState to Ready */ huart->gState = HAL_UART_STATE_READY; /* Cleat TxISR function pointer */ huart->TxISR = NULL; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Tx complete callback*/ huart->TxCpltCallback(huart); #else /*Call legacy weak Tx complete callback*/ HAL_UART_TxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } /** * @brief RX interrupt handler for 7 or 8 bits data word length . * @param huart UART handle. * @retval None */ static void UART_RxISR_8BIT(UART_HandleTypeDef *huart) { uint16_t uhMask = huart->Mask; uint16_t uhdata; /* Check that a Rx process is ongoing */ if (huart->RxState == HAL_UART_STATE_BUSY_RX) { uhdata = (uint16_t) READ_REG(huart->Instance->RDR); *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); huart->pRxBuffPtr++; huart->RxXferCount--; if (huart->RxXferCount == 0U) { /* Disable the UART Parity Error Interrupt and RXNE interrupts */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Rx process is completed, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; /* Clear RxISR function pointer */ huart->RxISR = NULL; /* Check current reception Mode : If Reception till IDLE event has been selected : */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { /* Set reception type to Standard */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Disable IDLE interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) { /* Clear IDLE Flag */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } else { /* Standard reception API called */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxCpltCallback(huart); #else /*Call legacy weak Rx complete callback*/ HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } } else { /* Clear RXNE interrupt flag */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); } } /** * @brief RX interrupt handler for 9 bits data word length . * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Receive_IT() * @param huart UART handle. * @retval None */ static void UART_RxISR_16BIT(UART_HandleTypeDef *huart) { uint16_t *tmp; uint16_t uhMask = huart->Mask; uint16_t uhdata; /* Check that a Rx process is ongoing */ if (huart->RxState == HAL_UART_STATE_BUSY_RX) { uhdata = (uint16_t) READ_REG(huart->Instance->RDR); tmp = (uint16_t *) huart->pRxBuffPtr ; *tmp = (uint16_t)(uhdata & uhMask); huart->pRxBuffPtr += 2U; huart->RxXferCount--; if (huart->RxXferCount == 0U) { /* Disable the UART Parity Error Interrupt and RXNE interrupt*/ ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); /* Rx process is completed, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; /* Clear RxISR function pointer */ huart->RxISR = NULL; /* Check current reception Mode : If Reception till IDLE event has been selected : */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { /* Set reception type to Standard */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Disable IDLE interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) { /* Clear IDLE Flag */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } else { /* Standard reception API called */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxCpltCallback(huart); #else /*Call legacy weak Rx complete callback*/ HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } } else { /* Clear RXNE interrupt flag */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); } } /** * @brief RX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Receive_IT() * @param huart UART handle. * @retval None */ static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) { uint16_t uhMask = huart->Mask; uint16_t uhdata; uint16_t nb_rx_data; uint16_t rxdatacount; uint32_t isrflags = READ_REG(huart->Instance->ISR); uint32_t cr1its = READ_REG(huart->Instance->CR1); uint32_t cr3its = READ_REG(huart->Instance->CR3); /* Check that a Rx process is ongoing */ if (huart->RxState == HAL_UART_STATE_BUSY_RX) { nb_rx_data = huart->NbRxDataToProcess; while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) { uhdata = (uint16_t) READ_REG(huart->Instance->RDR); *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); huart->pRxBuffPtr++; huart->RxXferCount--; isrflags = READ_REG(huart->Instance->ISR); /* If some non blocking errors occurred */ if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) { /* UART parity error interrupt occurred -------------------------------------*/ if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); huart->ErrorCode |= HAL_UART_ERROR_PE; } /* UART frame error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); huart->ErrorCode |= HAL_UART_ERROR_FE; } /* UART noise error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); huart->ErrorCode |= HAL_UART_ERROR_NE; } /* Call UART Error Call back function if need be ----------------------------*/ if (huart->ErrorCode != HAL_UART_ERROR_NONE) { /* Non Blocking error : transfer could go on. Error is notified to user through user error callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ huart->ErrorCode = HAL_UART_ERROR_NONE; } } if (huart->RxXferCount == 0U) { /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* Rx process is completed, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; /* Clear RxISR function pointer */ huart->RxISR = NULL; /* Check current reception Mode : If Reception till IDLE event has been selected : */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { /* Set reception type to Standard */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Disable IDLE interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) { /* Clear IDLE Flag */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } else { /* Standard reception API called */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxCpltCallback(huart); #else /*Call legacy weak Rx complete callback*/ HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } } /* When remaining number of bytes to receive is less than the RX FIFO threshold, next incoming frames are processed as if FIFO mode was disabled (i.e. one interrupt per received frame). */ rxdatacount = huart->RxXferCount; if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) { /* Disable the UART RXFT interrupt*/ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); /* Update the RxISR function pointer */ huart->RxISR = UART_RxISR_8BIT; /* Enable the UART Data Register Not Empty interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); } } else { /* Clear RXNE interrupt flag */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); } } /** * @brief RX interrupt handler for 9 bits data word length and FIFO mode is enabled. * @note Function is called under interruption only, once * interruptions have been enabled by HAL_UART_Receive_IT() * @param huart UART handle. * @retval None */ static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) { uint16_t *tmp; uint16_t uhMask = huart->Mask; uint16_t uhdata; uint16_t nb_rx_data; uint16_t rxdatacount; uint32_t isrflags = READ_REG(huart->Instance->ISR); uint32_t cr1its = READ_REG(huart->Instance->CR1); uint32_t cr3its = READ_REG(huart->Instance->CR3); /* Check that a Rx process is ongoing */ if (huart->RxState == HAL_UART_STATE_BUSY_RX) { nb_rx_data = huart->NbRxDataToProcess; while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) { uhdata = (uint16_t) READ_REG(huart->Instance->RDR); tmp = (uint16_t *) huart->pRxBuffPtr ; *tmp = (uint16_t)(uhdata & uhMask); huart->pRxBuffPtr += 2U; huart->RxXferCount--; isrflags = READ_REG(huart->Instance->ISR); /* If some non blocking errors occurred */ if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) { /* UART parity error interrupt occurred -------------------------------------*/ if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); huart->ErrorCode |= HAL_UART_ERROR_PE; } /* UART frame error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); huart->ErrorCode |= HAL_UART_ERROR_FE; } /* UART noise error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); huart->ErrorCode |= HAL_UART_ERROR_NE; } /* Call UART Error Call back function if need be ----------------------------*/ if (huart->ErrorCode != HAL_UART_ERROR_NONE) { /* Non Blocking error : transfer could go on. Error is notified to user through user error callback */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered error callback*/ huart->ErrorCallback(huart); #else /*Call legacy weak error callback*/ HAL_UART_ErrorCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ huart->ErrorCode = HAL_UART_ERROR_NONE; } } if (huart->RxXferCount == 0U) { /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* Rx process is completed, restore huart->RxState to Ready */ huart->RxState = HAL_UART_STATE_READY; /* Clear RxISR function pointer */ huart->RxISR = NULL; /* Check current reception Mode : If Reception till IDLE event has been selected : */ if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { /* Set reception type to Standard */ huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; /* Disable IDLE interrupt */ ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) { /* Clear IDLE Flag */ __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); } #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Event callback*/ huart->RxEventCallback(huart, huart->RxXferSize); #else /*Call legacy weak Rx Event callback*/ HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } else { /* Standard reception API called */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx complete callback*/ huart->RxCpltCallback(huart); #else /*Call legacy weak Rx complete callback*/ HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } } } /* When remaining number of bytes to receive is less than the RX FIFO threshold, next incoming frames are processed as if FIFO mode was disabled (i.e. one interrupt per received frame). */ rxdatacount = huart->RxXferCount; if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) { /* Disable the UART RXFT interrupt*/ ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); /* Update the RxISR function pointer */ huart->RxISR = UART_RxISR_16BIT; /* Enable the UART Data Register Not Empty interrupt */ ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); } } else { /* Clear RXNE interrupt flag */ __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); } } /** * @} */ #endif /* HAL_UART_MODULE_ENABLED */ /** * @} */ /** * @} */
155,479
C
32.697443
147
0.630059
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_hal_tim_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_tim_ex.c * @author MCD Application Team * @brief TIM HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Timer Extended peripheral: * + Time Hall Sensor Interface Initialization * + Time Hall Sensor Interface Start * + Time Complementary signal break and dead time configuration * + Time Master and Slave synchronization configuration * + Time Output Compare/PWM Channel Configuration (for channels 5 and 6) * + Time OCRef clear configuration * + Timer remapping capabilities configuration * + Timer encoder index configuration ****************************************************************************** * @attention * * Copyright (c) 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 ============================================================================== ##### TIMER Extended features ##### ============================================================================== [..] The Timer Extended features include: (#) Complementary outputs with programmable dead-time for : (++) Output Compare (++) PWM generation (Edge and Center-aligned Mode) (++) One-pulse mode output (#) Synchronization circuit to control the timer with external signals and to interconnect several timers together. (#) Break input to put the timer output signals in reset state or in a known state. (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for positioning purposes (#) In case of Pulse on compare, configure pulse length and delay (#) Encoder index configuration ##### How to use this driver ##### ============================================================================== [..] (#) Initialize the TIM low level resources by implementing the following functions depending on the selected feature: (++) Hall Sensor output : HAL_TIMEx_HallSensor_MspInit() (#) Initialize the TIM low level resources : (##) Enable the TIM interface clock using __HAL_RCC_TIMx_CLK_ENABLE(); (##) TIM pins configuration (+++) Enable the clock for the TIM GPIOs using the following function: __HAL_RCC_GPIOx_CLK_ENABLE(); (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); (#) The external Clock can be configured, if needed (the default clock is the internal clock from the APBx), using the following function: HAL_TIM_ConfigClockSource, the clock configuration should be done before any start function. (#) Configure the TIM in the desired functioning mode using one of the initialization function of this driver: (++) HAL_TIMEx_HallSensor_Init() and HAL_TIMEx_ConfigCommutEvent(): to use the Timer Hall Sensor Interface and the commutation event with the corresponding Interrupt and DMA request if needed (Note that One Timer is used to interface with the Hall sensor Interface and another Timer should be used to use the commutation event). (#) In case of Pulse On Compare: (++) HAL_TIMEx_OC_ConfigPulseOnCompare(): to configure pulse width and prescaler (#) Activate the TIM peripheral using one of the start functions: (++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), HAL_TIMEx_OCN_Start_IT() (++) Complementary PWM generation : HAL_TIMEx_PWMN_Start(), HAL_TIMEx_PWMN_Start_DMA(), HAL_TIMEx_PWMN_Start_IT() (++) Complementary One-pulse mode output : HAL_TIMEx_OnePulseN_Start(), HAL_TIMEx_OnePulseN_Start_IT() (++) Hall Sensor output : HAL_TIMEx_HallSensor_Start(), HAL_TIMEx_HallSensor_Start_DMA(), HAL_TIMEx_HallSensor_Start_IT(). @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup TIMEx TIMEx * @brief TIM Extended HAL module driver * @{ */ #ifdef HAL_TIM_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup TIMEx_Private_Constants TIM Extended Private Constants * @{ */ /* Timeout for break input rearm */ #define TIM_BREAKINPUT_REARM_TIMEOUT 5UL /* 5 milliseconds */ /** * @} */ /* End of private constants --------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma); static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma); static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState); /* Exported functions --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Functions TIM Extended Exported Functions * @{ */ /** @defgroup TIMEx_Exported_Functions_Group1 Extended Timer Hall Sensor functions * @brief Timer Hall Sensor functions * @verbatim ============================================================================== ##### Timer Hall Sensor functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure TIM HAL Sensor. (+) De-initialize TIM HAL Sensor. (+) Start the Hall Sensor Interface. (+) Stop the Hall Sensor Interface. (+) Start the Hall Sensor Interface and enable interrupts. (+) Stop the Hall Sensor Interface and disable interrupts. (+) Start the Hall Sensor Interface and enable DMA transfers. (+) Stop the Hall Sensor Interface and disable DMA transfers. @endverbatim * @{ */ /** * @brief Initializes the TIM Hall Sensor Interface and initialize the associated handle. * @note When the timer instance is initialized in Hall Sensor Interface mode, * timer channels 1 and channel 2 are reserved and cannot be used for * other purpose. * @param htim TIM Hall Sensor Interface handle * @param sConfig TIM Hall Sensor configuration structure * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef *sConfig) { TIM_OC_InitTypeDef OC_Config; /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy week callbacks */ TIM_ResetCallback(htim); if (htim->HallSensor_MspInitCallback == NULL) { htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->HallSensor_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIMEx_HallSensor_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Configure the Time base in the Encoder Mode */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Configure the Channel 1 as Input Channel to interface with the three Outputs of the Hall sensor */ TIM_TI1_SetConfig(htim->Instance, sConfig->IC1Polarity, TIM_ICSELECTION_TRC, sConfig->IC1Filter); /* Reset the IC1PSC Bits */ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC; /* Set the IC1PSC value */ htim->Instance->CCMR1 |= sConfig->IC1Prescaler; /* Enable the Hall sensor interface (XOR function of the three inputs) */ htim->Instance->CR2 |= TIM_CR2_TI1S; /* Select the TIM_TS_TI1F_ED signal as Input trigger for the TIM */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= TIM_TS_TI1F_ED; /* Use the TIM_TS_TI1F_ED signal to reset the TIM counter each edge detection */ htim->Instance->SMCR &= ~TIM_SMCR_SMS; htim->Instance->SMCR |= TIM_SLAVEMODE_RESET; /* Program channel 2 in PWM 2 mode with the desired Commutation_Delay*/ OC_Config.OCFastMode = TIM_OCFAST_DISABLE; OC_Config.OCIdleState = TIM_OCIDLESTATE_RESET; OC_Config.OCMode = TIM_OCMODE_PWM2; OC_Config.OCNIdleState = TIM_OCNIDLESTATE_RESET; OC_Config.OCNPolarity = TIM_OCNPOLARITY_HIGH; OC_Config.OCPolarity = TIM_OCPOLARITY_HIGH; OC_Config.Pulse = sConfig->Commutation_Delay; TIM_OC2_SetConfig(htim->Instance, &OC_Config); /* Select OC2REF as trigger output on TRGO: write the MMS bits in the TIMx_CR2 register to 101 */ htim->Instance->CR2 &= ~TIM_CR2_MMS; htim->Instance->CR2 |= TIM_TRGO_OC2REF; /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM Hall Sensor interface * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->HallSensor_MspDeInitCallback == NULL) { htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; } /* DeInit the low level hardware */ htim->HallSensor_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ HAL_TIMEx_HallSensor_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Change the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM Hall Sensor MSP. * @param htim TIM Hall Sensor Interface handle * @retval None */ __weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_HallSensor_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM Hall Sensor MSP. * @param htim TIM Hall Sensor Interface handle * @retval None */ __weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_HallSensor_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM Hall Sensor Interface. * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Input Capture channel 1 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Hall sensor Interface. * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channels 1, 2 and 3 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Hall Sensor Interface in interrupt mode. * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the capture compare Interrupts 1 event */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); /* Enable the Input Capture channel 1 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Hall Sensor Interface in interrupt mode. * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channel 1 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); /* Disable the capture compare Interrupts event */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Hall Sensor Interface in DMA mode. * @param htim TIM Hall Sensor Interface handle * @param pData The destination Buffer address. * @param Length The length of data to be transferred from TIM peripheral to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) { uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Set the TIM channel state */ if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } /* Enable the Input Capture channel 1 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); /* Set the DMA Input Capture 1 Callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel for Capture 1*/ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the capture compare 1 Interrupt */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Hall Sensor Interface in DMA mode. * @param htim TIM Hall Sensor Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channel 1 (in the Hall Sensor Interface the three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); /* Disable the capture compare Interrupts 1 event */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group2 Extended Timer Complementary Output Compare functions * @brief Timer Complementary Output Compare functions * @verbatim ============================================================================== ##### Timer Complementary Output Compare functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Start the Complementary Output Compare/PWM. (+) Stop the Complementary Output Compare/PWM. (+) Start the Complementary Output Compare/PWM and enable interrupts. (+) Stop the Complementary Output Compare/PWM and disable interrupts. (+) Start the Complementary Output Compare/PWM and enable DMA transfers. (+) Stop the Complementary Output Compare/PWM and disable DMA transfers. @endverbatim * @{ */ /** * @brief Starts the TIM Output Compare signal generation on the complementary * output. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Check the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Output Compare signal generation on the complementary * output. * @param htim TIM handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Disable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Output Compare signal generation in interrupt mode * on the complementary output. * @param htim TIM OC handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Check the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); switch (Channel) { case TIM_CHANNEL_1: { /* Enable the TIM Output Compare interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Enable the TIM Output Compare interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Enable the TIM Output Compare interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Enable the TIM Output Compare interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the TIM Break interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK); /* Enable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM Output Compare signal generation in interrupt mode * on the complementary output. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpccer; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Output Compare interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Disable the TIM Output Compare interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Disable the TIM Output Compare interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Disable the TIM Output Compare interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE | TIM_CCER_CC4NE)) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @brief Starts the TIM Output Compare signal generation in DMA mode * on the complementary output. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param pData The source Buffer address. * @param Length The length of data to be transferred from memory to TIM peripheral * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Set the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) { return HAL_BUSY; } else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Output Compare DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); break; } case TIM_CHANNEL_2: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Output Compare DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); break; } case TIM_CHANNEL_3: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Output Compare DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); break; } case TIM_CHANNEL_4: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Output Compare DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM Output Compare signal generation in DMA mode * on the complementary output. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Output Compare DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_CHANNEL_2: { /* Disable the TIM Output Compare DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_CHANNEL_3: { /* Disable the TIM Output Compare DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_CHANNEL_4: { /* Disable the TIM Output Compare interrupt */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Capture compare channel N */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group3 Extended Timer Complementary PWM functions * @brief Timer Complementary PWM functions * @verbatim ============================================================================== ##### Timer Complementary PWM functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Start the Complementary PWM. (+) Stop the Complementary PWM. (+) Start the Complementary PWM and enable interrupts. (+) Stop the Complementary PWM and disable interrupts. (+) Start the Complementary PWM and enable DMA transfers. (+) Stop the Complementary PWM and disable DMA transfers. (+) Start the Complementary Input Capture measurement. (+) Stop the Complementary Input Capture. (+) Start the Complementary Input Capture and enable interrupts. (+) Stop the Complementary Input Capture and disable interrupts. (+) Start the Complementary Input Capture and enable DMA transfers. (+) Stop the Complementary Input Capture and disable DMA transfers. (+) Start the Complementary One Pulse generation. (+) Stop the Complementary One Pulse. (+) Start the Complementary One Pulse and enable interrupts. (+) Stop the Complementary One Pulse and disable interrupts. @endverbatim * @{ */ /** * @brief Starts the PWM signal generation on the complementary output. * @param htim TIM handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Check the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the PWM signal generation on the complementary output. * @param htim TIM handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Disable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the PWM signal generation in interrupt mode on the * complementary output. * @param htim TIM handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Check the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); switch (Channel) { case TIM_CHANNEL_1: { /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Enable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Enable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the TIM Break interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK); /* Enable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the PWM signal generation in interrupt mode on the * complementary output. * @param htim TIM handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpccer; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE | TIM_CCER_CC4NE)) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @brief Starts the TIM PWM signal generation in DMA mode on the * complementary output * @param htim TIM handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param pData The source Buffer address. * @param Length The length of data to be transferred from memory to TIM peripheral * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); /* Set the TIM complementary channel state */ if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) { return HAL_BUSY; } else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); break; } case TIM_CHANNEL_2: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); break; } case TIM_CHANNEL_3: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); break; } case TIM_CHANNEL_4: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM PWM signal generation in DMA mode on the complementary * output * @param htim TIM handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the complementary PWM output */ TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM complementary channel state */ TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group4 Extended Timer Complementary One Pulse functions * @brief Timer Complementary One Pulse functions * @verbatim ============================================================================== ##### Timer Complementary One Pulse functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Start the Complementary One Pulse generation. (+) Stop the Complementary One Pulse. (+) Start the Complementary One Pulse and enable interrupts. (+) Stop the Complementary One Pulse and disable interrupts. @endverbatim * @{ */ /** * @brief Starts the TIM One Pulse signal generation on the complementary * output. * @note OutputChannel must match the pulse output channel chosen when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel pulse output channel to enable * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the complementary One Pulse output channel and the Input Capture channel */ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM One Pulse signal generation on the complementary * output. * @note OutputChannel must match the pulse output channel chosen when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel pulse output channel to disable * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); /* Disable the complementary One Pulse output channel and the Input Capture channel */ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM One Pulse signal generation in interrupt mode on the * complementary channel. * @note OutputChannel must match the pulse output channel chosen when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel pulse output channel to enable * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); /* Enable the complementary One Pulse output channel and the Input Capture channel */ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); /* Enable the Main Output */ __HAL_TIM_MOE_ENABLE(htim); /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM One Pulse signal generation in interrupt mode on the * complementary channel. * @note OutputChannel must match the pulse output channel chosen when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel pulse output channel to disable * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); /* Disable the complementary One Pulse output channel and the Input Capture channel */ TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group5 Extended Peripheral Control functions * @brief Peripheral Control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Configure the commutation event in case of use of the Hall sensor interface. (+) Configure Output channels for OC and PWM mode. (+) Configure Complementary channels, break features and dead time. (+) Configure Master synchronization. (+) Configure timer remapping capabilities. (+) Select timer input source. (+) Enable or disable channel grouping. (+) Configure Pulse on compare. (+) Configure Encoder index. @endverbatim * @{ */ /** * @brief Configure the TIM commutation event sequence. * @note This function is mandatory to use the commutation event in order to * update the configuration at each commutation detection on the TRGI input of the Timer, * the typical use of this feature is with the use of another Timer(interface Timer) * configured in Hall sensor interface, this interface Timer will generate the * commutation at its TRGO output (connected to Timer used in this function) each time * the TI1 of the Interface Timer detect a commutation at its input TI1. * @param htim TIM handle * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor * This parameter can be one of the following values: * @arg TIM_TS_ITR0: Internal trigger 0 selected * @arg TIM_TS_ITR1: Internal trigger 1 selected * @arg TIM_TS_ITR2: Internal trigger 2 selected * @arg TIM_TS_ITR3: Internal trigger 3 selected * @arg TIM_TS_ITR4: Internal trigger 4 selected (*) * @arg TIM_TS_ITR5: Internal trigger 5 selected * @arg TIM_TS_ITR6: Internal trigger 6 selected * @arg TIM_TS_ITR7: Internal trigger 7 selected * @arg TIM_TS_ITR8: Internal trigger 8 selected * @arg TIM_TS_ITR9: Internal trigger 9 selected (*) * @arg TIM_TS_ITR10: Internal trigger 10 selected * @arg TIM_TS_ITR11: Internal trigger 11 selected * @arg TIM_TS_NONE: No trigger is needed * * (*) Value not defined in all devices. * * @param CommutationSource the Commutation Event source * This parameter can be one of the following values: * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) { /* Check the parameters */ assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); __HAL_LOCK(htim); #if defined(TIM5) && defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR10) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM5) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR11)) #else if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #endif /* TIM5 && TIM20 */ { /* Select the Input trigger */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= InputTrigger; } /* Select the Capture Compare preload feature */ htim->Instance->CR2 |= TIM_CR2_CCPC; /* Select the Commutation event source */ htim->Instance->CR2 &= ~TIM_CR2_CCUS; htim->Instance->CR2 |= CommutationSource; /* Disable Commutation Interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); /* Disable Commutation DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configure the TIM commutation event sequence with interrupt. * @note This function is mandatory to use the commutation event in order to * update the configuration at each commutation detection on the TRGI input of the Timer, * the typical use of this feature is with the use of another Timer(interface Timer) * configured in Hall sensor interface, this interface Timer will generate the * commutation at its TRGO output (connected to Timer used in this function) each time * the TI1 of the Interface Timer detect a commutation at its input TI1. * @param htim TIM handle * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor * This parameter can be one of the following values: * @arg TIM_TS_ITR0: Internal trigger 0 selected * @arg TIM_TS_ITR1: Internal trigger 1 selected * @arg TIM_TS_ITR2: Internal trigger 2 selected * @arg TIM_TS_ITR3: Internal trigger 3 selected * @arg TIM_TS_ITR4: Internal trigger 4 selected (*) * @arg TIM_TS_ITR5: Internal trigger 5 selected * @arg TIM_TS_ITR6: Internal trigger 6 selected * @arg TIM_TS_ITR7: Internal trigger 7 selected * @arg TIM_TS_ITR8: Internal trigger 8 selected * @arg TIM_TS_ITR9: Internal trigger 9 selected (*) * @arg TIM_TS_ITR10: Internal trigger 10 selected * @arg TIM_TS_ITR11: Internal trigger 11 selected * @arg TIM_TS_NONE: No trigger is needed * * (*) Value not defined in all devices. * * @param CommutationSource the Commutation Event source * This parameter can be one of the following values: * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) { /* Check the parameters */ assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); __HAL_LOCK(htim); #if defined(TIM5) && defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR10) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM5) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR11)) #else if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #endif /* TIM5 && TIM20 */ { /* Select the Input trigger */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= InputTrigger; } /* Select the Capture Compare preload feature */ htim->Instance->CR2 |= TIM_CR2_CCPC; /* Select the Commutation event source */ htim->Instance->CR2 &= ~TIM_CR2_CCUS; htim->Instance->CR2 |= CommutationSource; /* Disable Commutation DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); /* Enable the Commutation Interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_COM); __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configure the TIM commutation event sequence with DMA. * @note This function is mandatory to use the commutation event in order to * update the configuration at each commutation detection on the TRGI input of the Timer, * the typical use of this feature is with the use of another Timer(interface Timer) * configured in Hall sensor interface, this interface Timer will generate the * commutation at its TRGO output (connected to Timer used in this function) each time * the TI1 of the Interface Timer detect a commutation at its input TI1. * @note The user should configure the DMA in his own software, in This function only the COMDE bit is set * @param htim TIM handle * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor * This parameter can be one of the following values: * @arg TIM_TS_ITR0: Internal trigger 0 selected * @arg TIM_TS_ITR1: Internal trigger 1 selected * @arg TIM_TS_ITR2: Internal trigger 2 selected * @arg TIM_TS_ITR3: Internal trigger 3 selected * @arg TIM_TS_ITR4: Internal trigger 4 selected (*) * @arg TIM_TS_ITR5: Internal trigger 5 selected * @arg TIM_TS_ITR6: Internal trigger 6 selected * @arg TIM_TS_ITR7: Internal trigger 7 selected * @arg TIM_TS_ITR8: Internal trigger 8 selected * @arg TIM_TS_ITR9: Internal trigger 9 selected (*) * @arg TIM_TS_ITR10: Internal trigger 10 selected * @arg TIM_TS_ITR11: Internal trigger 11 selected * @arg TIM_TS_NONE: No trigger is needed * * (*) Value not defined in all devices. * * @param CommutationSource the Commutation Event source * This parameter can be one of the following values: * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) { /* Check the parameters */ assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); __HAL_LOCK(htim); #if defined(TIM5) && defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR10) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM5) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR4) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #elif defined(TIM20) if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR9) || (InputTrigger == TIM_TS_ITR11)) #else if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3) || (InputTrigger == TIM_TS_ITR5) || (InputTrigger == TIM_TS_ITR6) || (InputTrigger == TIM_TS_ITR7) || (InputTrigger == TIM_TS_ITR8) || (InputTrigger == TIM_TS_ITR11)) #endif /* TIM5 && TIM20 */ { /* Select the Input trigger */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= InputTrigger; } /* Select the Capture Compare preload feature */ htim->Instance->CR2 |= TIM_CR2_CCPC; /* Select the Commutation event source */ htim->Instance->CR2 &= ~TIM_CR2_CCUS; htim->Instance->CR2 |= CommutationSource; /* Enable the Commutation DMA Request */ /* Set the DMA Commutation Callback */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError; /* Disable Commutation Interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); /* Enable the Commutation DMA Request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_COM); __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configures the TIM in master mode. * @param htim TIM handle. * @param sMasterConfig pointer to a TIM_MasterConfigTypeDef structure that * contains the selected trigger output (TRGO) and the Master/Slave * mode. * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef *sMasterConfig) { uint32_t tmpcr2; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger)); assert_param(IS_TIM_MSM_STATE(sMasterConfig->MasterSlaveMode)); /* Check input state */ __HAL_LOCK(htim); /* Change the handler state */ htim->State = HAL_TIM_STATE_BUSY; /* Get the TIMx CR2 register value */ tmpcr2 = htim->Instance->CR2; /* Get the TIMx SMCR register value */ tmpsmcr = htim->Instance->SMCR; /* If the timer supports ADC synchronization through TRGO2, set the master mode selection 2 */ if (IS_TIM_TRGO2_INSTANCE(htim->Instance)) { /* Check the parameters */ assert_param(IS_TIM_TRGO2_SOURCE(sMasterConfig->MasterOutputTrigger2)); /* Clear the MMS2 bits */ tmpcr2 &= ~TIM_CR2_MMS2; /* Select the TRGO2 source*/ tmpcr2 |= sMasterConfig->MasterOutputTrigger2; } /* Reset the MMS Bits */ tmpcr2 &= ~TIM_CR2_MMS; /* Select the TRGO source */ tmpcr2 |= sMasterConfig->MasterOutputTrigger; /* Update TIMx CR2 */ htim->Instance->CR2 = tmpcr2; if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { /* Reset the MSM Bit */ tmpsmcr &= ~TIM_SMCR_MSM; /* Set master mode */ tmpsmcr |= sMasterConfig->MasterSlaveMode; /* Update TIMx SMCR */ htim->Instance->SMCR = tmpsmcr; } /* Change the htim state */ htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State * and the AOE(automatic output enable). * @param htim TIM handle * @param sBreakDeadTimeConfig pointer to a TIM_ConfigBreakDeadConfigTypeDef structure that * contains the BDTR Register configuration information for the TIM peripheral. * @note Interrupts can be generated when an active level is detected on the * break input, the break 2 input or the system break input. Break * interrupt can be enabled by calling the @ref __HAL_TIM_ENABLE_IT macro. * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) { /* Keep this variable initialized to 0 as it is used to configure BDTR register */ uint32_t tmpbdtr = 0U; /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_OSSR_STATE(sBreakDeadTimeConfig->OffStateRunMode)); assert_param(IS_TIM_OSSI_STATE(sBreakDeadTimeConfig->OffStateIDLEMode)); assert_param(IS_TIM_LOCK_LEVEL(sBreakDeadTimeConfig->LockLevel)); assert_param(IS_TIM_DEADTIME(sBreakDeadTimeConfig->DeadTime)); assert_param(IS_TIM_BREAK_STATE(sBreakDeadTimeConfig->BreakState)); assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->BreakFilter)); assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); /* Check input state */ __HAL_LOCK(htim); /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, the OSSI State, the dead time value and the Automatic Output Enable Bit */ /* Set the BDTR bits */ MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, sBreakDeadTimeConfig->DeadTime); MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, sBreakDeadTimeConfig->LockLevel); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, sBreakDeadTimeConfig->OffStateIDLEMode); MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, sBreakDeadTimeConfig->OffStateRunMode); MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, sBreakDeadTimeConfig->BreakState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, sBreakDeadTimeConfig->BreakPolarity); MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, sBreakDeadTimeConfig->AutomaticOutput); MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, (sBreakDeadTimeConfig->BreakFilter << TIM_BDTR_BKF_Pos)); if (IS_TIM_ADVANCED_INSTANCE(htim->Instance)) { /* Check the parameters */ assert_param(IS_TIM_BREAK_AFMODE(sBreakDeadTimeConfig->BreakAFMode)); /* Set BREAK AF mode */ MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, sBreakDeadTimeConfig->BreakAFMode); } if (IS_TIM_BKIN2_INSTANCE(htim->Instance)) { /* Check the parameters */ assert_param(IS_TIM_BREAK2_STATE(sBreakDeadTimeConfig->Break2State)); assert_param(IS_TIM_BREAK2_POLARITY(sBreakDeadTimeConfig->Break2Polarity)); assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->Break2Filter)); /* Set the BREAK2 input related BDTR bits */ MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (sBreakDeadTimeConfig->Break2Filter << TIM_BDTR_BK2F_Pos)); MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, sBreakDeadTimeConfig->Break2State); MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, sBreakDeadTimeConfig->Break2Polarity); if (IS_TIM_ADVANCED_INSTANCE(htim->Instance)) { /* Check the parameters */ assert_param(IS_TIM_BREAK2_AFMODE(sBreakDeadTimeConfig->Break2AFMode)); /* Set BREAK2 AF mode */ MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, sBreakDeadTimeConfig->Break2AFMode); } } /* Set TIMx_BDTR */ htim->Instance->BDTR = tmpbdtr; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configures the break input source. * @param htim TIM handle. * @param BreakInput Break input to configure * This parameter can be one of the following values: * @arg TIM_BREAKINPUT_BRK: Timer break input * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input * @param sBreakInputConfig Break input source configuration * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput, TIMEx_BreakInputConfigTypeDef *sBreakInputConfig) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmporx; uint32_t bkin_enable_mask; uint32_t bkin_polarity_mask; uint32_t bkin_enable_bitpos; uint32_t bkin_polarity_bitpos; /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_BREAKINPUT(BreakInput)); assert_param(IS_TIM_BREAKINPUTSOURCE(sBreakInputConfig->Source)); assert_param(IS_TIM_BREAKINPUTSOURCE_STATE(sBreakInputConfig->Enable)); assert_param(IS_TIM_BREAKINPUTSOURCE_POLARITY(sBreakInputConfig->Polarity)); /* Check input state */ __HAL_LOCK(htim); switch (sBreakInputConfig->Source) { case TIM_BREAKINPUTSOURCE_BKIN: { bkin_enable_mask = TIM1_AF1_BKINE; bkin_enable_bitpos = TIM1_AF1_BKINE_Pos; bkin_polarity_mask = TIM1_AF1_BKINP; bkin_polarity_bitpos = TIM1_AF1_BKINP_Pos; break; } case TIM_BREAKINPUTSOURCE_COMP1: { bkin_enable_mask = TIM1_AF1_BKCMP1E; bkin_enable_bitpos = TIM1_AF1_BKCMP1E_Pos; bkin_polarity_mask = TIM1_AF1_BKCMP1P; bkin_polarity_bitpos = TIM1_AF1_BKCMP1P_Pos; break; } case TIM_BREAKINPUTSOURCE_COMP2: { bkin_enable_mask = TIM1_AF1_BKCMP2E; bkin_enable_bitpos = TIM1_AF1_BKCMP2E_Pos; bkin_polarity_mask = TIM1_AF1_BKCMP2P; bkin_polarity_bitpos = TIM1_AF1_BKCMP2P_Pos; break; } case TIM_BREAKINPUTSOURCE_COMP3: { bkin_enable_mask = TIM1_AF1_BKCMP3E; bkin_enable_bitpos = TIM1_AF1_BKCMP3E_Pos; bkin_polarity_mask = TIM1_AF1_BKCMP3P; bkin_polarity_bitpos = TIM1_AF1_BKCMP3P_Pos; break; } case TIM_BREAKINPUTSOURCE_COMP4: { bkin_enable_mask = TIM1_AF1_BKCMP4E; bkin_enable_bitpos = TIM1_AF1_BKCMP4E_Pos; bkin_polarity_mask = TIM1_AF1_BKCMP4P; bkin_polarity_bitpos = TIM1_AF1_BKCMP4P_Pos; break; } #if defined (COMP5) case TIM_BREAKINPUTSOURCE_COMP5: { bkin_enable_mask = TIM1_AF1_BKCMP5E; bkin_enable_bitpos = TIM1_AF1_BKCMP5E_Pos; /* No palarity bit for this COMP. Variable bkin_polarity_mask keeps its default value 0 */ bkin_polarity_mask = 0U; bkin_polarity_bitpos = 0U; break; } #endif /* COMP5 */ #if defined (COMP6) case TIM_BREAKINPUTSOURCE_COMP6: { bkin_enable_mask = TIM1_AF1_BKCMP6E; bkin_enable_bitpos = TIM1_AF1_BKCMP6E_Pos; /* No palarity bit for this COMP. Variable bkin_polarity_mask keeps its default value 0 */ bkin_polarity_mask = 0U; bkin_polarity_bitpos = 0U; break; } #endif /* COMP7 */ #if defined (COMP7) case TIM_BREAKINPUTSOURCE_COMP7: { bkin_enable_mask = TIM1_AF1_BKCMP7E; bkin_enable_bitpos = TIM1_AF1_BKCMP7E_Pos; /* No palarity bit for this COMP. Variable bkin_polarity_mask keeps its default value 0 */ bkin_polarity_mask = 0U; bkin_polarity_bitpos = 0U; break; } #endif /* COMP7 */ default: { bkin_enable_mask = 0U; bkin_polarity_mask = 0U; bkin_enable_bitpos = 0U; bkin_polarity_bitpos = 0U; break; } } switch (BreakInput) { case TIM_BREAKINPUT_BRK: { /* Get the TIMx_AF1 register value */ tmporx = htim->Instance->AF1; /* Enable the break input */ tmporx &= ~bkin_enable_mask; tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; /* Set the break input polarity */ tmporx &= ~bkin_polarity_mask; tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; /* Set TIMx_AF1 */ htim->Instance->AF1 = tmporx; break; } case TIM_BREAKINPUT_BRK2: { /* Get the TIMx_AF2 register value */ tmporx = htim->Instance->AF2; /* Enable the break input */ tmporx &= ~bkin_enable_mask; tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; /* Set the break input polarity */ tmporx &= ~bkin_polarity_mask; tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; /* Set TIMx_AF2 */ htim->Instance->AF2 = tmporx; break; } default: status = HAL_ERROR; break; } __HAL_UNLOCK(htim); return status; } /** * @brief Configures the TIMx Remapping input capabilities. * @param htim TIM handle. * @param Remap specifies the TIM remapping source. * For TIM1, the parameter can take one of the following values: * @arg TIM_TIM1_ETR_GPIO TIM1 ETR is connected to GPIO * @arg TIM_TIM1_ETR_COMP1 TIM1 ETR is connected to COMP1 output * @arg TIM_TIM1_ETR_COMP2 TIM1 ETR is connected to COMP2 output * @arg TIM_TIM1_ETR_COMP3 TIM1 ETR is connected to COMP3 output * @arg TIM_TIM1_ETR_COMP4 TIM1 ETR is connected to COMP4 output * @arg TIM_TIM1_ETR_COMP5 TIM1 ETR is connected to COMP5 output (*) * @arg TIM_TIM1_ETR_COMP6 TIM1 ETR is connected to COMP6 output (*) * @arg TIM_TIM1_ETR_COMP7 TIM1 ETR is connected to COMP7 output (*) * @arg TIM_TIM1_ETR_ADC1_AWD1 TIM1 ETR is connected to ADC1 AWD1 * @arg TIM_TIM1_ETR_ADC1_AWD2 TIM1 ETR is connected to ADC1 AWD2 * @arg TIM_TIM1_ETR_ADC1_AWD3 TIM1 ETR is connected to ADC1 AWD3 * @arg TIM_TIM1_ETR_ADC4_AWD1 TIM1 ETR is connected to ADC4 AWD1 (*) * @arg TIM_TIM1_ETR_ADC4_AWD2 TIM1 ETR is connected to ADC4 AWD2 (*) * @arg TIM_TIM1_ETR_ADC4_AWD3 TIM1 ETR is connected to ADC4 AWD3 (*) * * For TIM2, the parameter can take one of the following values: * @arg TIM_TIM2_ETR_GPIO TIM2 ETR is connected to GPIO * @arg TIM_TIM2_ETR_COMP1 TIM2 ETR is connected to COMP1 output * @arg TIM_TIM2_ETR_COMP2 TIM2 ETR is connected to COMP2 output * @arg TIM_TIM2_ETR_COMP3 TIM2 ETR is connected to COMP3 output * @arg TIM_TIM2_ETR_COMP4 TIM2 ETR is connected to COMP4 output * @arg TIM_TIM2_ETR_COMP5 TIM2 ETR is connected to COMP5 output (*) * @arg TIM_TIM2_ETR_COMP6 TIM2 ETR is connected to COMP6 output (*) * @arg TIM_TIM2_ETR_COMP7 TIM2 ETR is connected to COMP7 output (*) * @arg TIM_TIM2_ETR_TIM3_ETR TIM2 ETR is connected to TIM3 ETR pin * @arg TIM_TIM2_ETR_TIM4_ETR TIM2 ETR is connected to TIM4 ETR pin * @arg TIM_TIM2_ETR_TIM5_ETR TIM2 ETR is connected to TIM5 ETR pin (*) * @arg TIM_TIM2_ETR_LSE * * For TIM3, the parameter can take one of the following values: * @arg TIM_TIM3_ETR_GPIO TIM3 ETR is connected to GPIO * @arg TIM_TIM3_ETR_COMP1 TIM3 ETR is connected to COMP1 output * @arg TIM_TIM3_ETR_COMP2 TIM3 ETR is connected to COMP2 output * @arg TIM_TIM3_ETR_COMP3 TIM3 ETR is connected to COMP3 output * @arg TIM_TIM3_ETR_COMP4 TIM3 ETR is connected to COMP4 output * @arg TIM_TIM3_ETR_COMP5 TIM3 ETR is connected to COMP5 output (*) * @arg TIM_TIM3_ETR_COMP6 TIM3 ETR is connected to COMP6 output (*) * @arg TIM_TIM3_ETR_COMP7 TIM3 ETR is connected to COMP7 output (*) * @arg TIM_TIM3_ETR_TIM2_ETR TIM3 ETR is connected to TIM2 ETR pin * @arg TIM_TIM3_ETR_TIM4_ETR TIM3 ETR is connected to TIM4 ETR pin * @arg TIM_TIM3_ETR_ADC2_AWD1 TIM3 ETR is connected to ADC2 AWD1 * @arg TIM_TIM3_ETR_ADC2_AWD2 TIM3 ETR is connected to ADC2 AWD2 * @arg TIM_TIM3_ETR_ADC2_AWD3 TIM3 ETR is connected to ADC2 AWD3 * * For TIM4, the parameter can take one of the following values: * @arg TIM_TIM4_ETR_GPIO TIM4 ETR is connected to GPIO * @arg TIM_TIM4_ETR_COMP1 TIM4 ETR is connected to COMP1 output * @arg TIM_TIM4_ETR_COMP2 TIM4 ETR is connected to COMP2 output * @arg TIM_TIM4_ETR_COMP3 TIM4 ETR is connected to COMP3 output * @arg TIM_TIM4_ETR_COMP4 TIM4 ETR is connected to COMP4 output * @arg TIM_TIM4_ETR_COMP5 TIM4 ETR is connected to COMP5 output (*) * @arg TIM_TIM4_ETR_COMP6 TIM4 ETR is connected to COMP6 output (*) * @arg TIM_TIM4_ETR_COMP7 TIM4 ETR is connected to COMP7 output (*) * @arg TIM_TIM4_ETR_TIM3_ETR TIM4 ETR is connected to TIM3 ETR pin * @arg TIM_TIM4_ETR_TIM5_ETR TIM4 ETR is connected to TIM5 ETR pin (*) * * For TIM5, the parameter can take one of the following values: (**) * @arg TIM_TIM5_ETR_GPIO TIM5 ETR is connected to GPIO (*) * @arg TIM_TIM5_ETR_COMP1 TIM5 ETR is connected to COMP1 output (*) * @arg TIM_TIM5_ETR_COMP2 TIM5 ETR is connected to COMP2 output (*) * @arg TIM_TIM5_ETR_COMP3 TIM5 ETR is connected to COMP3 output (*) * @arg TIM_TIM5_ETR_COMP4 TIM5 ETR is connected to COMP4 output (*) * @arg TIM_TIM5_ETR_COMP5 TIM5 ETR is connected to COMP5 output (*) * @arg TIM_TIM5_ETR_COMP6 TIM5 ETR is connected to COMP6 output (*) * @arg TIM_TIM5_ETR_COMP7 TIM5 ETR is connected to COMP7 output (*) * @arg TIM_TIM5_ETR_TIM2_ETR TIM5 ETR is connected to TIM2 ETR pin (*) * @arg TIM_TIM5_ETR_TIM3_ETR TIM5 ETR is connected to TIM3 ETR pin (*) * * For TIM8, the parameter can take one of the following values: * @arg TIM_TIM8_ETR_GPIO TIM8 ETR is connected to GPIO * @arg TIM_TIM8_ETR_COMP1 TIM8 ETR is connected to COMP1 output * @arg TIM_TIM8_ETR_COMP2 TIM8 ETR is connected to COMP2 output * @arg TIM_TIM8_ETR_COMP3 TIM8 ETR is connected to COMP3 output * @arg TIM_TIM8_ETR_COMP4 TIM8 ETR is connected to COMP4 output * @arg TIM_TIM8_ETR_COMP5 TIM8 ETR is connected to COMP5 output (*) * @arg TIM_TIM8_ETR_COMP6 TIM8 ETR is connected to COMP6 output (*) * @arg TIM_TIM8_ETR_COMP7 TIM8 ETR is connected to COMP7 output (*) * @arg TIM_TIM8_ETR_ADC2_AWD1 TIM8 ETR is connected to ADC2 AWD1 * @arg TIM_TIM8_ETR_ADC2_AWD2 TIM8 ETR is connected to ADC2 AWD2 * @arg TIM_TIM8_ETR_ADC2_AWD3 TIM8 ETR is connected to ADC2 AWD3 * @arg TIM_TIM8_ETR_ADC3_AWD1 TIM8 ETR is connected to ADC3 AWD1 (*) * @arg TIM_TIM8_ETR_ADC3_AWD2 TIM8 ETR is connected to ADC3 AWD2 (*) * @arg TIM_TIM8_ETR_ADC3_AWD3 TIM8 ETR is connected to ADC3 AWD3 (*) * * For TIM20, the parameter can take one of the following values: (**) * @arg TIM_TIM20_ETR_GPIO TIM20 ETR is connected to GPIO * @arg TIM_TIM20_ETR_COMP1 TIM20 ETR is connected to COMP1 output (*) * @arg TIM_TIM20_ETR_COMP2 TIM20 ETR is connected to COMP2 output (*) * @arg TIM_TIM20_ETR_COMP3 TIM20 ETR is connected to COMP3 output (*) * @arg TIM_TIM20_ETR_COMP4 TIM20 ETR is connected to COMP4 output (*) * @arg TIM_TIM20_ETR_COMP5 TIM20 ETR is connected to COMP5 output (*) * @arg TIM_TIM20_ETR_COMP6 TIM20 ETR is connected to COMP6 output (*) * @arg TIM_TIM20_ETR_COMP7 TIM20 ETR is connected to COMP7 output (*) * @arg TIM_TIM20_ETR_ADC3_AWD1 TIM20 ETR is connected to ADC3 AWD1 (*) * @arg TIM_TIM20_ETR_ADC3_AWD2 TIM20 ETR is connected to ADC3 AWD2 (*) * @arg TIM_TIM20_ETR_ADC3_AWD3 TIM20 ETR is connected to ADC3 AWD3 (*) * @arg TIM_TIM20_ETR_ADC5_AWD1 TIM20 ETR is connected to ADC5 AWD1 (*) * @arg TIM_TIM20_ETR_ADC5_AWD2 TIM20 ETR is connected to ADC5 AWD2 (*) * @arg TIM_TIM20_ETR_ADC5_AWD3 TIM20 ETR is connected to ADC5 AWD3 (*) * * (*) Value not defined in all devices. \n * (**) Register not available in all devices. * * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) { /* Check parameters */ assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); assert_param(IS_TIM_REMAP(Remap)); __HAL_LOCK(htim); MODIFY_REG(htim->Instance->AF1, TIM1_AF1_ETRSEL_Msk, Remap); __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Select the timer input source * @param htim TIM handle. * @param Channel specifies the TIM Channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TI1 input channel * @arg TIM_CHANNEL_2: TI2 input channel * @arg TIM_CHANNEL_3: TI3 input channel * @arg TIM_CHANNEL_4: TI4 input channel * @param TISelection specifies the timer input source * For TIM1 this parameter can be one of the following values: * @arg TIM_TIM1_TI1_GPIO: TIM1 TI1 is connected to GPIO * @arg TIM_TIM1_TI1_COMP1: TIM1 TI1 is connected to COMP1 output * @arg TIM_TIM1_TI1_COMP2: TIM1 TI1 is connected to COMP2 output * @arg TIM_TIM1_TI1_COMP3: TIM1 TI1 is connected to COMP3 output * @arg TIM_TIM1_TI1_COMP4: TIM1 TI1 is connected to COMP4 output * * For TIM2 this parameter can be one of the following values: * @arg TIM_TIM2_TI1_GPIO: TIM2 TI1 is connected to GPIO * @arg TIM_TIM2_TI1_COMP1: TIM2 TI1 is connected to COMP1 output * @arg TIM_TIM2_TI1_COMP2: TIM2 TI1 is connected to COMP2 output * @arg TIM_TIM2_TI1_COMP3: TIM2 TI1 is connected to COMP3 output * @arg TIM_TIM2_TI1_COMP4: TIM2 TI1 is connected to COMP4 output * @arg TIM_TIM2_TI1_COMP5: TIM2 TI1 is connected to COMP5 output (*) * * @arg TIM_TIM2_TI2_GPIO: TIM1 TI2 is connected to GPIO * @arg TIM_TIM2_TI2_COMP1: TIM2 TI2 is connected to COMP1 output * @arg TIM_TIM2_TI2_COMP2: TIM2 TI2 is connected to COMP2 output * @arg TIM_TIM2_TI2_COMP3: TIM2 TI2 is connected to COMP3 output * @arg TIM_TIM2_TI2_COMP4: TIM2 TI2 is connected to COMP4 output * @arg TIM_TIM2_TI2_COMP6: TIM2 TI2 is connected to COMP6 output (*) * * @arg TIM_TIM2_TI3_GPIO: TIM2 TI3 is connected to GPIO * @arg TIM_TIM2_TI3_COMP4: TIM2 TI3 is connected to COMP4 output * * @arg TIM_TIM2_TI4_GPIO: TIM2 TI4 is connected to GPIO * @arg TIM_TIM2_TI4_COMP1: TIM2 TI4 is connected to COMP1 output * @arg TIM_TIM2_TI4_COMP2: TIM2 TI4 is connected to COMP2 output * * For TIM3 this parameter can be one of the following values: * @arg TIM_TIM3_TI1_GPIO: TIM3 TI1 is connected to GPIO * @arg TIM_TIM3_TI1_COMP1: TIM3 TI1 is connected to COMP1 output * @arg TIM_TIM3_TI1_COMP2: TIM3 TI1 is connected to COMP2 output * @arg TIM_TIM3_TI1_COMP3: TIM3 TI1 is connected to COMP3 output * @arg TIM_TIM3_TI1_COMP4: TIM3 TI1 is connected to COMP4 output * @arg TIM_TIM3_TI1_COMP5: TIM3 TI1 is connected to COMP5 output (*) * @arg TIM_TIM3_TI1_COMP6: TIM3 TI1 is connected to COMP6 output (*) * @arg TIM_TIM3_TI1_COMP7: TIM3 TI1 is connected to COMP7 output (*) * * @arg TIM_TIM3_TI2_GPIO: TIM3 TI2 is connected to GPIO * @arg TIM_TIM3_TI2_COMP1: TIM3 TI2 is connected to COMP1 output * @arg TIM_TIM3_TI2_COMP2: TIM3 TI2 is connected to COMP2 output * @arg TIM_TIM3_TI2_COMP3: TIM3 TI2 is connected to COMP3 output * @arg TIM_TIM3_TI2_COMP4: TIM3 TI2 is connected to COMP4 output * @arg TIM_TIM3_TI2_COMP5: TIM3 TI2 is connected to COMP5 output (*) * @arg TIM_TIM3_TI2_COMP6: TIM3 TI2 is connected to COMP6 output (*) * @arg TIM_TIM3_TI2_COMP7: TIM3 TI2 is connected to COMP7 output (*) * * @arg TIM_TIM3_TI3_GPIO: TIM3 TI3 is connected to GPIO * @arg TIM_TIM3_TI3_COMP3: TIM3 TI3 is connected to COMP3 output * For TIM4 this parameter can be one of the following values: * @arg TIM_TIM4_TI1_GPIO: TIM4 TI1 is connected to GPIO * @arg TIM_TIM4_TI1_COMP1: TIM4 TI1 is connected to COMP1 output * @arg TIM_TIM4_TI1_COMP2: TIM4 TI1 is connected to COMP2 output * @arg TIM_TIM4_TI1_COMP3: TIM4 TI1 is connected to COMP3 output * @arg TIM_TIM4_TI1_COMP4: TIM4 TI1 is connected to COMP4 output * @arg TIM_TIM4_TI1_COMP5: TIM4 TI1 is connected to COMP5 output (*) * @arg TIM_TIM4_TI1_COMP6: TIM4 TI1 is connected to COMP6 output (*) * @arg TIM_TIM4_TI1_COMP7: TIM4 TI1 is connected to COMP7 output (*) * * @arg TIM_TIM4_TI2_GPIO: TIM4 TI2 is connected to GPIO * @arg TIM_TIM4_TI2_COMP1: TIM4 TI2 is connected to COMP1 output * @arg TIM_TIM4_TI2_COMP2: TIM4 TI2 is connected to COMP2 output * @arg TIM_TIM4_TI2_COMP3: TIM4 TI2 is connected to COMP3 output * @arg TIM_TIM4_TI2_COMP4: TIM4 TI2 is connected to COMP4 output * @arg TIM_TIM4_TI2_COMP5: TIM4 TI2 is connected to COMP5 output (*) * @arg TIM_TIM4_TI2_COMP6: TIM4 TI2 is connected to COMP6 output (*) * @arg TIM_TIM4_TI2_COMP7: TIM4 TI2 is connected to COMP7 output (*) * * @arg TIM_TIM4_TI3_GPIO: TIM4 TI3 is connected to GPIO * @arg TIM_TIM4_TI3_COMP5: TIM4 TI3 is connected to COMP5 output (*) * * @arg TIM_TIM4_TI4_GPIO: TIM4 TI4 is connected to GPIO * @arg TIM_TIM4_TI4_COMP6: TIM4 TI4 is connected to COMP6 output (*) * * For TIM5 this parameter can be one of the following values: (**) * @arg TIM_TIM5_TI1_GPIO: TIM5 TI1 is connected to GPIO * @arg TIM_TIM5_TI1_LSI: TIM5 TI1 is connected to LSI clock (*) * @arg TIM_TIM5_TI1_LSE: TIM5 TI1 is connected to LSE clock (*) * @arg TIM_TIM5_TI1_RTC_WK: TIM5 TI1 is connected to RTC Wakeup (*) * @arg TIM_TIM5_TI1_COMP1: TIM5 TI1 is connected to COMP1 output (*) * @arg TIM_TIM5_TI1_COMP2: TIM5 TI1 is connected to COMP2 output (*) * @arg TIM_TIM5_TI1_COMP3: TIM5 TI1 is connected to COMP3 output (*) * @arg TIM_TIM5_TI1_COMP4: TIM5 TI1 is connected to COMP4 output (*) * @arg TIM_TIM5_TI1_COMP5: TIM5 TI1 is connected to COMP5 output (*) * @arg TIM_TIM5_TI1_COMP6: TIM5 TI1 is connected to COMP6 output (*) * @arg TIM_TIM5_TI1_COMP7: TIM5 TI1 is connected to COMP7 output (*) * * @arg TIM_TIM5_TI2_GPIO: TIM5 TI2 is connected to GPIO * @arg TIM_TIM5_TI2_COMP1: TIM5 TI2 is connected to COMP1 output * @arg TIM_TIM5_TI2_COMP2: TIM5 TI2 is connected to COMP2 output * @arg TIM_TIM5_TI2_COMP3: TIM5 TI2 is connected to COMP3 output * @arg TIM_TIM5_TI2_COMP4: TIM5 TI2 is connected to COMP4 output * @arg TIM_TIM5_TI2_COMP5: TIM5 TI2 is connected to COMP5 output (*) * @arg TIM_TIM5_TI2_COMP6: TIM5 TI2 is connected to COMP6 output (*) * @arg TIM_TIM5_TI2_COMP7: TIM5 TI2 is connected to COMP7 output (*) * * For TIM8 this parameter can be one of the following values: * @arg TIM_TIM8_TI1_GPIO: TIM8 TI1 is connected to GPIO * @arg TIM_TIM8_TI1_COMP1: TIM8 TI1 is connected to COMP1 output * @arg TIM_TIM8_TI1_COMP2: TIM8 TI1 is connected to COMP2 output * @arg TIM_TIM8_TI1_COMP3: TIM8 TI1 is connected to COMP3 output * @arg TIM_TIM8_TI1_COMP4: TIM8 TI1 is connected to COMP4 output * * For TIM15 this parameter can be one of the following values: * @arg TIM_TIM15_TI1_GPIO: TIM15 TI1 is connected to GPIO * @arg TIM_TIM15_TI1_LSE: TIM15 TI1 is connected to LSE clock * @arg TIM_TIM15_TI1_COMP1: TIM15 TI1 is connected to COMP1 output * @arg TIM_TIM15_TI1_COMP2: TIM15 TI1 is connected to COMP2 output * @arg TIM_TIM15_TI1_COMP5: TIM15 TI1 is connected to COMP5 output (*) * @arg TIM_TIM15_TI1_COMP7: TIM15 TI1 is connected to COMP7 output (*) * * @arg TIM_TIM15_TI2_GPIO: TIM15 TI2 is connected to GPIO * @arg TIM_TIM15_TI2_COMP2: TIM15 TI2 is connected to COMP2 output * @arg TIM_TIM15_TI2_COMP3: TIM15 TI2 is connected to COMP3 output * @arg TIM_TIM15_TI2_COMP6: TIM15 TI2 is connected to COMP6 output (*) * @arg TIM_TIM15_TI2_COMP7: TIM15 TI2 is connected to COMP7 output (*) * * For TIM16 this parameter can be one of the following values: * @arg TIM_TIM16_TI1_GPIO: TIM16 TI1 is connected to GPIO * @arg TIM_TIM16_TI1_COMP6: TIM16 TI1 is connected to COMP6 output (*) * @arg TIM_TIM16_TI1_MCO: TIM15 TI1 is connected to MCO output * @arg TIM_TIM16_TI1_HSE_32: TIM15 TI1 is connected to HSE div 32 * @arg TIM_TIM16_TI1_RTC_WK: TIM15 TI1 is connected to RTC wakeup * @arg TIM_TIM16_TI1_LSE: TIM15 TI1 is connected to LSE clock * @arg TIM_TIM16_TI1_LSI: TIM15 TI1 is connected to LSI clock * * For TIM17 this parameter can be one of the following values: * @arg TIM_TIM17_TI1_GPIO: TIM17 TI1 is connected to GPIO * @arg TIM_TIM17_TI1_COMP5: TIM17 TI1 is connected to COMP5 output (*) * @arg TIM_TIM17_TI1_MCO: TIM17 TI1 is connected to MCO output * @arg TIM_TIM17_TI1_HSE_32: TIM17 TI1 is connected to HSE div 32 * @arg TIM_TIM17_TI1_RTC_WK: TIM17 TI1 is connected to RTC wakeup * @arg TIM_TIM17_TI1_LSE: TIM17 TI1 is connected to LSE clock * @arg TIM_TIM17_TI1_LSI: TIM17 TI1 is connected to LSI clock * For TIM20 this parameter can be one of the following values: (**) * @arg TIM_TIM20_TI1_GPIO: TIM20 TI1 is connected to GPIO * @arg TIM_TIM20_TI1_COMP1: TIM20 TI1 is connected to COMP1 output (*) * @arg TIM_TIM20_TI1_COMP2: TIM20 TI1 is connected to COMP2 output (*) * @arg TIM_TIM20_TI1_COMP3: TIM20 TI1 is connected to COMP3 output (*) * @arg TIM_TIM20_TI1_COMP4: TIM20 TI1 is connected to COMP4 output (*) * * (*) Value not defined in all devices. \n * (**) Register not available in all devices. * * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_TISelection(TIM_HandleTypeDef *htim, uint32_t TISelection, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_TIM_TISEL_TIX_INSTANCE(htim->Instance, Channel)); assert_param(IS_TIM_TISEL(TISelection)); __HAL_LOCK(htim); switch (Channel) { case TIM_CHANNEL_1: MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI1SEL, TISelection); /* If required, set OR bit to request HSE/32 clock */ if (IS_TIM_HSE32_INSTANCE(htim->Instance)) { SET_BIT(htim->Instance->OR, TIM_OR_HSE32EN); } else { CLEAR_BIT(htim->Instance->OR, TIM_OR_HSE32EN); } break; case TIM_CHANNEL_2: MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI2SEL, TISelection); break; case TIM_CHANNEL_3: MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI3SEL, TISelection); break; case TIM_CHANNEL_4: MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI4SEL, TISelection); break; default: status = HAL_ERROR; break; } __HAL_UNLOCK(htim); return status; } /** * @brief Group channel 5 and channel 1, 2 or 3 * @param htim TIM handle. * @param Channels specifies the reference signal(s) the OC5REF is combined with. * This parameter can be any combination of the following values: * TIM_GROUPCH5_NONE: No effect of OC5REF on OC1REFC, OC2REFC and OC3REFC * TIM_GROUPCH5_OC1REFC: OC1REFC is the logical AND of OC1REFC and OC5REF * TIM_GROUPCH5_OC2REFC: OC2REFC is the logical AND of OC2REFC and OC5REF * TIM_GROUPCH5_OC3REFC: OC3REFC is the logical AND of OC3REFC and OC5REF * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_GroupChannel5(TIM_HandleTypeDef *htim, uint32_t Channels) { /* Check parameters */ assert_param(IS_TIM_COMBINED3PHASEPWM_INSTANCE(htim->Instance)); assert_param(IS_TIM_GROUPCH5(Channels)); /* Process Locked */ __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; /* Clear GC5Cx bit fields */ htim->Instance->CCR5 &= ~(TIM_CCR5_GC5C3 | TIM_CCR5_GC5C2 | TIM_CCR5_GC5C1); /* Set GC5Cx bit fields */ htim->Instance->CCR5 |= Channels; /* Change the htim state */ htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Disarm the designated break input (when it operates in bidirectional mode). * @param htim TIM handle. * @param BreakInput Break input to disarm * This parameter can be one of the following values: * @arg TIM_BREAKINPUT_BRK: Timer break input * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input * @note The break input can be disarmed only when it is configured in * bidirectional mode and when when MOE is reset. * @note Purpose is to be able to have the input voltage back to high-state, * whatever the time constant on the output . * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpbdtr; /* Check the parameters */ assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance)); assert_param(IS_TIM_BREAKINPUT(BreakInput)); switch (BreakInput) { case TIM_BREAKINPUT_BRK: { /* Check initial conditions */ tmpbdtr = READ_REG(htim->Instance->BDTR); if ((READ_BIT(tmpbdtr, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) && (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) { /* Break input BRK is disarmed */ SET_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM); } break; } case TIM_BREAKINPUT_BRK2: { /* Check initial conditions */ tmpbdtr = READ_REG(htim->Instance->BDTR); if ((READ_BIT(tmpbdtr, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) && (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) { /* Break input BRK is disarmed */ SET_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM); } break; } default: status = HAL_ERROR; break; } return status; } /** * @brief Arm the designated break input (when it operates in bidirectional mode). * @param htim TIM handle. * @param BreakInput Break input to arm * This parameter can be one of the following values: * @arg TIM_BREAKINPUT_BRK: Timer break input * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input * @note Arming is possible at anytime, even if fault is present. * @note Break input is automatically armed as soon as MOE bit is set. * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput) { HAL_StatusTypeDef status = HAL_OK; uint32_t tickstart; /* Check the parameters */ assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance)); assert_param(IS_TIM_BREAKINPUT(BreakInput)); switch (BreakInput) { case TIM_BREAKINPUT_BRK: { /* Check initial conditions */ if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) { /* Break input BRK is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) { if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) { /* New check to avoid false timeout detection in case of preemption */ if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) { return HAL_TIMEOUT; } } } } break; } case TIM_BREAKINPUT_BRK2: { /* Check initial conditions */ if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) { /* Break input BRK2 is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ /* Init tickstart for timeout management */ tickstart = HAL_GetTick(); while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) { if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) { /* New check to avoid false timeout detection in case of preemption */ if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) { return HAL_TIMEOUT; } } } } break; } default: status = HAL_ERROR; break; } return status; } /** * @brief Enable dithering * @param htim TIM handle * @note Main usage is PWM mode * @note This function must be called when timer is stopped or disabled (CEN =0) * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers * - ARR and CCRx values are limited to 0xFFEF in dithering mode for 16b timers * (corresponds to 4094 for the integer part and 15 for the dithered part). * @note Macros @ref __HAL_TIM_CALC_PERIOD_DITHER() __HAL_TIM_CALC_DELAY_DITHER() __HAL_TIM_CALC_PULSE_DITHER() * can be used to calculate period (ARR) and delay (CCRx) value. * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DitheringEnable(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); return HAL_OK; } /** * @brief Disable dithering * @param htim TIM handle * @note This function must be called when timer is stopped or disabled (CEN =0) * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers * - ARR and CCRx values are limited to 0xFFEF in dithering mode * (corresponds to 4094 for the integer part and 15 for the dithered part). * @note Disabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DitheringDisable(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); return HAL_OK; } /** * @brief Initializes the pulse on compare pulse width and pulse prescaler * @param htim TIM Output Compare handle * @param PulseWidthPrescaler Pulse width prescaler * This parameter can be a number between Min_Data = 0x0 and Max_Data = 0x7 * @param PulseWidth Pulse width * This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_OC_ConfigPulseOnCompare(TIM_HandleTypeDef *htim, uint32_t PulseWidthPrescaler, uint32_t PulseWidth) { uint32_t tmpecr; /* Check the parameters */ assert_param(IS_TIM_PULSEONCOMPARE_INSTANCE(htim->Instance)); assert_param(IS_TIM_PULSEONCOMPARE_WIDTH(PulseWidth)); assert_param(IS_TIM_PULSEONCOMPARE_WIDTHPRESCALER(PulseWidthPrescaler)); /* Process Locked */ __HAL_LOCK(htim); /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Get the TIMx ECR register value */ tmpecr = htim->Instance->ECR; /* Reset the Pulse width prescaler and the Pulse width */ tmpecr &= ~(TIM_ECR_PWPRSC | TIM_ECR_PW); /* Set the Pulse width prescaler and Pulse width*/ tmpecr |= PulseWidthPrescaler << TIM_ECR_PWPRSC_Pos; tmpecr |= PulseWidth << TIM_ECR_PW_Pos; /* Write to TIMx ECR */ htim->Instance->ECR = tmpecr; /* Change the TIM state */ htim->State = HAL_TIM_STATE_READY; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configure preload source of Slave Mode Selection bitfield (SMS in SMCR register) * @param htim TIM handle * @param Source Source of slave mode selection preload * This parameter can be one of the following values: * @arg TIM_SMS_PRELOAD_SOURCE_UPDATE: Timer update event is used as source of Slave Mode Selection preload * @arg TIM_SMS_PRELOAD_SOURCE_INDEX: Timer index event is used as source of Slave Mode Selection preload * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigSlaveModePreload(TIM_HandleTypeDef *htim, uint32_t Source) { /* Check the parameters */ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); assert_param(IS_TIM_SLAVE_PRELOAD_SOURCE(Source)); MODIFY_REG(htim->Instance->SMCR, TIM_SMCR_SMSPS, Source); return HAL_OK; } /** * @brief Enable preload of Slave Mode Selection bitfield (SMS in SMCR register) * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_EnableSlaveModePreload(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); return HAL_OK; } /** * @brief Disable preload of Slave Mode Selection bitfield (SMS in SMCR register) * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisableSlaveModePreload(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); return HAL_OK; } /** * @brief Enable deadtime preload * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_EnableDeadTimePreload(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); return HAL_OK; } /** * @brief Disable deadtime preload * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisableDeadTimePreload(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); return HAL_OK; } /** * @brief Configure deadtime * @param htim TIM handle * @param Deadtime Deadtime value * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigDeadTime(TIM_HandleTypeDef *htim, uint32_t Deadtime) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_DEADTIME(Deadtime)); MODIFY_REG(htim->Instance->BDTR, TIM_BDTR_DTG, Deadtime); return HAL_OK; } /** * @brief Configure asymmetrical deadtime * @param htim TIM handle * @param FallingDeadtime Falling edge deadtime value * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigAsymmetricalDeadTime(TIM_HandleTypeDef *htim, uint32_t FallingDeadtime) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_DEADTIME(FallingDeadtime)); MODIFY_REG(htim->Instance->DTR2, TIM_DTR2_DTGF, FallingDeadtime); return HAL_OK; } /** * @brief Enable asymmetrical deadtime * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_EnableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); return HAL_OK; } /** * @brief Disable asymmetrical deadtime * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); return HAL_OK; } /** * @brief Configures the encoder index. * @note warning in case of encoder mode clock plus direction * @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X1 or @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X2 * Direction must be set to @ref TIM_ENCODERINDEX_DIRECTION_UP_DOWN * @param htim TIM handle. * @param sEncoderIndexConfig Encoder index configuration * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_ConfigEncoderIndex(TIM_HandleTypeDef *htim, TIMEx_EncoderIndexConfigTypeDef *sEncoderIndexConfig) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); assert_param(IS_TIM_ENCODERINDEX_POLARITY(sEncoderIndexConfig->Polarity)); assert_param(IS_TIM_ENCODERINDEX_PRESCALER(sEncoderIndexConfig->Prescaler)); assert_param(IS_TIM_ENCODERINDEX_FILTER(sEncoderIndexConfig->Filter)); assert_param(IS_FUNCTIONAL_STATE(sEncoderIndexConfig->FirstIndexEnable)); assert_param(IS_TIM_ENCODERINDEX_POSITION(sEncoderIndexConfig->Position)); assert_param(IS_TIM_ENCODERINDEX_DIRECTION(sEncoderIndexConfig->Direction)); /* Process Locked */ __HAL_LOCK(htim); /* Configures the TIMx External Trigger (ETR) which is used as Index input */ TIM_ETR_SetConfig(htim->Instance, sEncoderIndexConfig->Prescaler, sEncoderIndexConfig->Polarity, sEncoderIndexConfig->Filter); /* Configures the encoder index */ MODIFY_REG(htim->Instance->ECR, TIM_ECR_IDIR_Msk | TIM_ECR_FIDX_Msk | TIM_ECR_IPOS_Msk, (sEncoderIndexConfig->Direction | ((sEncoderIndexConfig->FirstIndexEnable == ENABLE) ? (0x1U << TIM_ECR_FIDX_Pos) : 0U) | sEncoderIndexConfig->Position | TIM_ECR_IE)); __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Enable encoder index * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_EnableEncoderIndex(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->ECR, TIM_ECR_IE); return HAL_OK; } /** * @brief Disable encoder index * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisableEncoderIndex(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->ECR, TIM_ECR_IE); return HAL_OK; } /** * @brief Enable encoder first index * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_EnableEncoderFirstIndex(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); SET_BIT(htim->Instance->ECR, TIM_ECR_FIDX); return HAL_OK; } /** * @brief Disable encoder first index * @param htim TIM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_DisableEncoderFirstIndex(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); CLEAR_BIT(htim->Instance->ECR, TIM_ECR_FIDX); return HAL_OK; } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group6 Extended Callbacks functions * @brief Extended Callbacks functions * @verbatim ============================================================================== ##### Extended Callbacks functions ##### ============================================================================== [..] This section provides Extended TIM callback functions: (+) Timer Commutation callback (+) Timer Break callback @endverbatim * @{ */ /** * @brief Hall commutation changed callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_CommutCallback could be implemented in the user file */ } /** * @brief Hall commutation changed half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_CommutHalfCpltCallback could be implemented in the user file */ } /** * @brief Hall Break detection callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_BreakCallback could be implemented in the user file */ } /** * @brief Hall Break2 detection callback in non blocking mode * @param htim: TIM handle * @retval None */ __weak void HAL_TIMEx_Break2Callback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_TIMEx_Break2Callback could be implemented in the user file */ } /** * @brief Encoder index callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_EncoderIndexCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_EncoderIndexCallback could be implemented in the user file */ } /** * @brief Direction change callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_DirectionChangeCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_DirectionChangeCallback could be implemented in the user file */ } /** * @brief Index error callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_IndexErrorCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_IndexErrorCallback could be implemented in the user file */ } /** * @brief Transition error callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIMEx_TransitionErrorCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIMEx_TransitionErrorCallback could be implemented in the user file */ } /** * @} */ /** @defgroup TIMEx_Exported_Functions_Group7 Extended Peripheral State functions * @brief Extended Peripheral State functions * @verbatim ============================================================================== ##### Extended Peripheral State functions ##### ============================================================================== [..] This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim * @{ */ /** * @brief Return the TIM Hall Sensor interface handle state. * @param htim TIM Hall Sensor handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return actual state of the TIM complementary channel. * @param htim TIM handle * @param ChannelN TIM Complementary channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 * @arg TIM_CHANNEL_2: TIM Channel 2 * @arg TIM_CHANNEL_3: TIM Channel 3 * @arg TIM_CHANNEL_4: TIM Channel 4 * @retval TIM Complementary channel state */ HAL_TIM_ChannelStateTypeDef HAL_TIMEx_GetChannelNState(TIM_HandleTypeDef *htim, uint32_t ChannelN) { HAL_TIM_ChannelStateTypeDef channel_state; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, ChannelN)); channel_state = TIM_CHANNEL_N_STATE_GET(htim, ChannelN); return channel_state; } /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup TIMEx_Private_Functions TIM Extended Private Functions * @{ */ /** * @brief TIM DMA Commutation callback. * @param hdma pointer to DMA handle. * @retval None */ void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Change the htim state */ htim->State = HAL_TIM_STATE_READY; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationCallback(htim); #else HAL_TIMEx_CommutCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief TIM DMA Commutation half complete callback. * @param hdma pointer to DMA handle. * @retval None */ void TIMEx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Change the htim state */ htim->State = HAL_TIM_STATE_READY; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationHalfCpltCallback(htim); #else HAL_TIMEx_CommutHalfCpltCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief TIM DMA Delay Pulse complete callback (complementary channel). * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); } } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA error callback (complementary channel) * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->ErrorCallback(htim); #else HAL_TIM_ErrorCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief Enables or disables the TIM Capture Compare Channel xN. * @param TIMx to select the TIM peripheral * @param Channel specifies the TIM Channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 * @arg TIM_CHANNEL_2: TIM Channel 2 * @arg TIM_CHANNEL_3: TIM Channel 3 * @arg TIM_CHANNEL_4: TIM Channel 4 * @param ChannelNState specifies the TIM Channel CCxNE bit new state. * This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable. * @retval None */ static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState) { uint32_t tmp; tmp = TIM_CCER_CC1NE << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ /* Reset the CCxNE Bit */ TIMx->CCER &= ~tmp; /* Set or reset the CCxNE Bit */ TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ } /** * @} */ #endif /* HAL_TIM_MODULE_ENABLED */ /** * @} */ /** * @} */
137,754
C
36.210967
119
0.628635
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_hal_cortex.c
/** ****************************************************************************** * @file stm32g4xx_hal_cortex.c * @author MCD Application Team * @brief CORTEX HAL module driver. * This file provides firmware functions to manage the following * functionalities of the CORTEX: * + Initialization and Configuration 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 ##### ============================================================================== [..] *** How to configure Interrupts using CORTEX HAL driver *** =========================================================== [..] This section provides functions allowing to configure the NVIC interrupts (IRQ). The Cortex-M4 exceptions are managed by CMSIS functions. (#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping() function. (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority(). (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ(). -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ pre-emption is no more possible. The pending IRQ priority will be managed only by the sub priority. -@- IRQ priority order (sorted by highest to lowest priority): (+@) Lowest pre-emption priority (+@) Lowest sub priority (+@) Lowest hardware priority (IRQ number) [..] *** How to configure SysTick using CORTEX HAL driver *** ======================================================== [..] Setup SysTick Timer for time base. (+) The HAL_SYSTICK_Config() function calls the SysTick_Config() function which is a CMSIS function that: (++) Configures the SysTick Reload register with value passed as function parameter. (++) Configures the SysTick IRQ priority to the lowest value (0x0F). (++) Resets the SysTick Counter register. (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). (++) Enables the SysTick Interrupt. (++) Starts the SysTick Counter. (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined inside the stm32g4xx_hal_cortex.h file. (+) You can change the SysTick IRQ priority by calling the HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. (+) To adjust the SysTick time base, use the following formula: Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function (++) Reload Value should not exceed 0xFFFFFF @endverbatim ****************************************************************************** The table below gives the allowed values of the pre-emption priority and subpriority according to the Priority Grouping configuration performed by HAL_NVIC_SetPriorityGrouping() function. ========================================================================================================================== NVIC_PriorityGroup | NVIC_IRQChannelPreemptionPriority | NVIC_IRQChannelSubPriority | Description ========================================================================================================================== NVIC_PRIORITYGROUP_0 | 0 | 0-15 | 0 bit for pre-emption priority | | | 4 bits for subpriority -------------------------------------------------------------------------------------------------------------------------- NVIC_PRIORITYGROUP_1 | 0-1 | 0-7 | 1 bit for pre-emption priority | | | 3 bits for subpriority -------------------------------------------------------------------------------------------------------------------------- NVIC_PRIORITYGROUP_2 | 0-3 | 0-3 | 2 bits for pre-emption priority | | | 2 bits for subpriority -------------------------------------------------------------------------------------------------------------------------- NVIC_PRIORITYGROUP_3 | 0-7 | 0-1 | 3 bits for pre-emption priority | | | 1 bit for subpriority -------------------------------------------------------------------------------------------------------------------------- NVIC_PRIORITYGROUP_4 | 0-15 | 0 | 4 bits for pre-emption priority | | | 0 bit for subpriority ========================================================================================================================== */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup CORTEX * @{ */ #ifdef HAL_CORTEX_MODULE_ENABLED /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 * @brief Initialization and Configuration functions * @verbatim ============================================================================== ##### Initialization and Configuration functions ##### ============================================================================== [..] This section provides the CORTEX HAL driver functions allowing to configure Interrupts SysTick functionalities @endverbatim * @{ */ /** * @brief Set the priority grouping field (pre-emption priority and subpriority) * using the required unlock sequence. * @param PriorityGroup: The priority grouping bits length. * This parameter can be one of the following values: * @arg NVIC_PRIORITYGROUP_0: 0 bit for pre-emption priority, * 4 bits for subpriority * @arg NVIC_PRIORITYGROUP_1: 1 bit for pre-emption priority, * 3 bits for subpriority * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority, * 2 bits for subpriority * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority, * 1 bit for subpriority * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority, * 0 bit for subpriority * @note When the NVIC_PriorityGroup_0 is selected, IRQ pre-emption is no more possible. * The pending IRQ priority will be managed only by the subpriority. * @retval None */ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); /* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */ NVIC_SetPriorityGrouping(PriorityGroup); } /** * @brief Set the priority of an interrupt. * @param IRQn: External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @param PreemptPriority: The pre-emption priority for the IRQn channel. * This parameter can be a value between 0 and 15 * A lower priority value indicates a higher priority * @param SubPriority: the subpriority level for the IRQ channel. * This parameter can be a value between 0 and 15 * A lower priority value indicates a higher priority. * @retval None */ void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t prioritygroup; /* Check the parameters */ assert_param(IS_NVIC_SUB_PRIORITY(SubPriority)); assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); prioritygroup = NVIC_GetPriorityGrouping(); NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority)); } /** * @brief Enable a device specific interrupt in the NVIC interrupt controller. * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() * function should be called before. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval None */ void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Enable interrupt */ NVIC_EnableIRQ(IRQn); } /** * @brief Disable a device specific interrupt in the NVIC interrupt controller. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval None */ void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Disable interrupt */ NVIC_DisableIRQ(IRQn); } /** * @brief Initiate a system reset request to reset the MCU. * @retval None */ void HAL_NVIC_SystemReset(void) { /* System Reset */ NVIC_SystemReset(); } /** * @brief Initialize the System Timer with interrupt enabled and start the System Tick Timer (SysTick): * Counter is in free running mode to generate periodic interrupts. * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts. * @retval status: - 0 Function succeeded. * - 1 Function failed. */ uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) { return SysTick_Config(TicksNumb); } /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 * @brief Cortex control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to control the CORTEX (NVIC, SYSTICK, MPU) functionalities. @endverbatim * @{ */ /** * @brief Get the priority grouping field from the NVIC Interrupt Controller. * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field) */ uint32_t HAL_NVIC_GetPriorityGrouping(void) { /* Get the PRIGROUP[10:8] field value */ return NVIC_GetPriorityGrouping(); } /** * @brief Get the priority of an interrupt. * @param IRQn: External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @param PriorityGroup: the priority grouping bits length. * This parameter can be one of the following values: * @arg NVIC_PRIORITYGROUP_0: 0 bit for pre-emption priority, * 4 bits for subpriority * @arg NVIC_PRIORITYGROUP_1: 1 bit for pre-emption priority, * 3 bits for subpriority * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority, * 2 bits for subpriority * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority, * 1 bit for subpriority * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority, * 0 bit for subpriority * @param pPreemptPriority: Pointer on the Preemptive priority value (starting from 0). * @param pSubPriority: Pointer on the Subpriority value (starting from 0). * @retval None */ void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); /* Get priority for Cortex-M system or device specific interrupts */ NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority); } /** * @brief Set Pending bit of an external interrupt. * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval None */ void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Set interrupt pending */ NVIC_SetPendingIRQ(IRQn); } /** * @brief Get Pending Interrupt (read the pending register in the NVIC * and return the pending bit for the specified interrupt). * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Return 1 if pending else 0 */ return NVIC_GetPendingIRQ(IRQn); } /** * @brief Clear the pending bit of an external interrupt. * @param IRQn External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval None */ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Clear pending interrupt */ NVIC_ClearPendingIRQ(IRQn); } /** * @brief Get active interrupt (read the active register in NVIC and return the active bit). * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32g4xxxx.h)) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn) { /* Return 1 if active else 0 */ return NVIC_GetActive(IRQn); } /** * @brief Configure the SysTick clock source. * @param CLKSource: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) { /* Check the parameters */ assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource)); if (CLKSource == SYSTICK_CLKSOURCE_HCLK) { SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; } else { SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; } } /** * @brief Handle SYSTICK interrupt request. * @retval None */ void HAL_SYSTICK_IRQHandler(void) { HAL_SYSTICK_Callback(); } /** * @brief SYSTICK callback. * @retval None */ __weak void HAL_SYSTICK_Callback(void) { /* NOTE : This function should not be modified, when the callback is needed, the HAL_SYSTICK_Callback could be implemented in the user file */ } #if (__MPU_PRESENT == 1) /** * @brief Enable the MPU. * @param MPU_Control: Specifies the control mode of the MPU during hard fault, * NMI, FAULTMASK and privileged accessto the default memory * This parameter can be one of the following values: * @arg MPU_HFNMI_PRIVDEF_NONE * @arg MPU_HARDFAULT_NMI * @arg MPU_PRIVILEGED_DEFAULT * @arg MPU_HFNMI_PRIVDEF * @retval None */ void HAL_MPU_Enable(uint32_t MPU_Control) { /* Enable the MPU */ MPU->CTRL = (MPU_Control | MPU_CTRL_ENABLE_Msk); /* Ensure MPU setting take effects */ __DSB(); __ISB(); } /** * @brief Disable the MPU. * @retval None */ void HAL_MPU_Disable(void) { /* Make sure outstanding transfers are done */ __DMB(); /* Disable the MPU and clear the control register*/ MPU->CTRL = 0; } /** * @brief Initialize and configure the Region and the memory to be protected. * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains * the initialization and configuration information. * @retval None */ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; if ((MPU_Init->Enable) != 0U) { /* Check the parameters */ assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00; MPU->RASR = 0x00; } } #endif /* __MPU_PRESENT */ /** * @} */ /** * @} */ #endif /* HAL_CORTEX_MODULE_ENABLED */ /** * @} */ /** * @} */
20,537
C
38.648649
139
0.560793
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_tim.c
/** ****************************************************************************** * @file stm32g4xx_hal_tim.c * @author MCD Application Team * @brief TIM HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Timer (TIM) peripheral: * + TIM Time Base Initialization * + TIM Time Base Start * + TIM Time Base Start Interruption * + TIM Time Base Start DMA * + TIM Output Compare/PWM Initialization * + TIM Output Compare/PWM Channel Configuration * + TIM Output Compare/PWM Start * + TIM Output Compare/PWM Start Interruption * + TIM Output Compare/PWM Start DMA * + TIM Input Capture Initialization * + TIM Input Capture Channel Configuration * + TIM Input Capture Start * + TIM Input Capture Start Interruption * + TIM Input Capture Start DMA * + TIM One Pulse Initialization * + TIM One Pulse Channel Configuration * + TIM One Pulse Start * + TIM Encoder Interface Initialization * + TIM Encoder Interface Start * + TIM Encoder Interface Start Interruption * + TIM Encoder Interface Start DMA * + Commutation Event configuration with Interruption and DMA * + TIM OCRef clear configuration * + TIM External Clock configuration ****************************************************************************** * @attention * * Copyright (c) 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 ============================================================================== ##### TIMER Generic features ##### ============================================================================== [..] The Timer features include: (#) 16-bit up, down, up/down auto-reload counter. (#) 16-bit programmable prescaler allowing dividing (also on the fly) the counter clock frequency either by any factor between 1 and 65536. (#) Up to 4 independent channels for: (++) Input Capture (++) Output Compare (++) PWM generation (Edge and Center-aligned Mode) (++) One-pulse mode output (#) Synchronization circuit to control the timer with external signals and to interconnect several timers together. (#) Supports incremental encoder for positioning purposes ##### How to use this driver ##### ============================================================================== [..] (#) Initialize the TIM low level resources by implementing the following functions depending on the selected feature: (++) Time Base : HAL_TIM_Base_MspInit() (++) Input Capture : HAL_TIM_IC_MspInit() (++) Output Compare : HAL_TIM_OC_MspInit() (++) PWM generation : HAL_TIM_PWM_MspInit() (++) One-pulse mode output : HAL_TIM_OnePulse_MspInit() (++) Encoder mode output : HAL_TIM_Encoder_MspInit() (#) Initialize the TIM low level resources : (##) Enable the TIM interface clock using __HAL_RCC_TIMx_CLK_ENABLE(); (##) TIM pins configuration (+++) Enable the clock for the TIM GPIOs using the following function: __HAL_RCC_GPIOx_CLK_ENABLE(); (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); (#) The external Clock can be configured, if needed (the default clock is the internal clock from the APBx), using the following function: HAL_TIM_ConfigClockSource, the clock configuration should be done before any start function. (#) Configure the TIM in the desired functioning mode using one of the Initialization function of this driver: (++) HAL_TIM_Base_Init: to use the Timer to generate a simple time base (++) HAL_TIM_OC_Init, HAL_TIM_OC_ConfigChannel and optionally HAL_TIMEx_OC_ConfigPulseOnCompare: to use the Timer to generate an Output Compare signal. (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a PWM signal. (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an external signal. (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer in One Pulse Mode. (++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface. (#) Activate the TIM peripheral using one of the start functions depending from the feature used: (++) Time Base : HAL_TIM_Base_Start(), HAL_TIM_Base_Start_DMA(), HAL_TIM_Base_Start_IT() (++) Input Capture : HAL_TIM_IC_Start(), HAL_TIM_IC_Start_DMA(), HAL_TIM_IC_Start_IT() (++) Output Compare : HAL_TIM_OC_Start(), HAL_TIM_OC_Start_DMA(), HAL_TIM_OC_Start_IT() (++) PWM generation : HAL_TIM_PWM_Start(), HAL_TIM_PWM_Start_DMA(), HAL_TIM_PWM_Start_IT() (++) One-pulse mode output : HAL_TIM_OnePulse_Start(), HAL_TIM_OnePulse_Start_IT() (++) Encoder mode output : HAL_TIM_Encoder_Start(), HAL_TIM_Encoder_Start_DMA(), HAL_TIM_Encoder_Start_IT(). (#) The DMA Burst is managed with the two following functions: HAL_TIM_DMABurst_WriteStart() HAL_TIM_DMABurst_ReadStart() *** Callback registration *** ============================================= [..] The compilation define USE_HAL_TIM_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. [..] Use Function HAL_TIM_RegisterCallback() to register a callback. HAL_TIM_RegisterCallback() takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. [..] Use function HAL_TIM_UnRegisterCallback() to reset a callback to the default weak function. HAL_TIM_UnRegisterCallback takes as parameters the HAL peripheral handle, and the Callback ID. [..] These functions allow to register/unregister following callbacks: (+) Base_MspInitCallback : TIM Base Msp Init Callback. (+) Base_MspDeInitCallback : TIM Base Msp DeInit Callback. (+) IC_MspInitCallback : TIM IC Msp Init Callback. (+) IC_MspDeInitCallback : TIM IC Msp DeInit Callback. (+) OC_MspInitCallback : TIM OC Msp Init Callback. (+) OC_MspDeInitCallback : TIM OC Msp DeInit Callback. (+) PWM_MspInitCallback : TIM PWM Msp Init Callback. (+) PWM_MspDeInitCallback : TIM PWM Msp DeInit Callback. (+) OnePulse_MspInitCallback : TIM One Pulse Msp Init Callback. (+) OnePulse_MspDeInitCallback : TIM One Pulse Msp DeInit Callback. (+) Encoder_MspInitCallback : TIM Encoder Msp Init Callback. (+) Encoder_MspDeInitCallback : TIM Encoder Msp DeInit Callback. (+) HallSensor_MspInitCallback : TIM Hall Sensor Msp Init Callback. (+) HallSensor_MspDeInitCallback : TIM Hall Sensor Msp DeInit Callback. (+) PeriodElapsedCallback : TIM Period Elapsed Callback. (+) PeriodElapsedHalfCpltCallback : TIM Period Elapsed half complete Callback. (+) TriggerCallback : TIM Trigger Callback. (+) TriggerHalfCpltCallback : TIM Trigger half complete Callback. (+) IC_CaptureCallback : TIM Input Capture Callback. (+) IC_CaptureHalfCpltCallback : TIM Input Capture half complete Callback. (+) OC_DelayElapsedCallback : TIM Output Compare Delay Elapsed Callback. (+) PWM_PulseFinishedCallback : TIM PWM Pulse Finished Callback. (+) PWM_PulseFinishedHalfCpltCallback : TIM PWM Pulse Finished half complete Callback. (+) ErrorCallback : TIM Error Callback. (+) CommutationCallback : TIM Commutation Callback. (+) CommutationHalfCpltCallback : TIM Commutation half complete Callback. (+) BreakCallback : TIM Break Callback. (+) Break2Callback : TIM Break2 Callback. (+) EncoderIndexCallback : TIM Encoder Index Callback. (+) DirectionChangeCallback : TIM Direction Change Callback (+) IndexErrorCallback : TIM Index Error Callback. (+) TransitionErrorCallback : TIM Transition Error Callback [..] By default, after the Init and when the state is HAL_TIM_STATE_RESET all interrupt callbacks are set to the corresponding weak functions: examples HAL_TIM_TriggerCallback(), HAL_TIM_ErrorCallback(). [..] Exception done for MspInit and MspDeInit functions that are reset to the legacy weak functionalities in the Init / DeInit only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init / DeInit keep and use the user MspInit / MspDeInit callbacks(registered beforehand) [..] Callbacks can be registered / unregistered in HAL_TIM_STATE_READY state only. Exception done MspInit / MspDeInit that can be registered / unregistered in HAL_TIM_STATE_READY or HAL_TIM_STATE_RESET state, thus registered(user) MspInit / DeInit callbacks can be used during the Init / DeInit. In that case first register the MspInit/MspDeInit user callbacks using HAL_TIM_RegisterCallback() before calling DeInit or Init function. [..] When The compilation define USE_HAL_TIM_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration feature is not available and all callbacks are set to the corresponding weak functions. @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup TIM TIM * @brief TIM HAL module driver * @{ */ #ifdef HAL_TIM_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @addtogroup TIM_Private_Constants * @{ */ #define TIMx_AF2_OCRSEL TIM1_AF2_OCRSEL /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @addtogroup TIM_Private_Functions * @{ */ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint32_t InputTriggerSource); static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma); static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma); static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma); static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup TIM_Exported_Functions TIM Exported Functions * @{ */ /** @defgroup TIM_Exported_Functions_Group1 TIM Time Base functions * @brief Time Base functions * @verbatim ============================================================================== ##### Time Base functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM base. (+) De-initialize the TIM base. (+) Start the Time Base. (+) Stop the Time Base. (+) Start the Time Base and enable interrupt. (+) Stop the Time Base and disable interrupt. (+) Start the Time Base and enable DMA transfer. (+) Stop the Time Base and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM Time base Unit according to the specified * parameters in the TIM_HandleTypeDef and initialize the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_Base_DeInit() before HAL_TIM_Base_Init() * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim) { /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->Base_MspInitCallback == NULL) { htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->Base_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC */ HAL_TIM_Base_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Set the Time Base configuration */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM Base peripheral * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->Base_MspDeInitCallback == NULL) { htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; } /* DeInit the low level hardware */ htim->Base_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ HAL_TIM_Base_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Change the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM Base MSP. * @param htim TIM Base handle * @retval None */ __weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_Base_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM Base MSP. * @param htim TIM Base handle * @retval None */ __weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_Base_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM Base generation. * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); /* Check the TIM state */ if (htim->State != HAL_TIM_STATE_READY) { return HAL_ERROR; } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Base generation. * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM state */ htim->State = HAL_TIM_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Base generation in interrupt mode. * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); /* Check the TIM state */ if (htim->State != HAL_TIM_STATE_READY) { return HAL_ERROR; } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Enable the TIM Update interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Base generation in interrupt mode. * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); /* Disable the TIM Update interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM state */ htim->State = HAL_TIM_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Base generation in DMA mode. * @param htim TIM Base handle * @param pData The source Buffer address. * @param Length The length of data to be transferred from memory to peripheral. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); /* Set the TIM state */ if (htim->State == HAL_TIM_STATE_BUSY) { return HAL_BUSY; } else if (htim->State == HAL_TIM_STATE_READY) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { htim->State = HAL_TIM_STATE_BUSY; } } else { return HAL_ERROR; } /* Set the DMA Period elapsed callbacks */ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Update DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Base generation in DMA mode. * @param htim TIM Base handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); /* Disable the TIM Update DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_UPDATE); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM state */ htim->State = HAL_TIM_STATE_READY; /* Return function status */ return HAL_OK; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group2 TIM Output Compare functions * @brief TIM Output Compare functions * @verbatim ============================================================================== ##### TIM Output Compare functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM Output Compare. (+) De-initialize the TIM Output Compare. (+) Start the TIM Output Compare. (+) Stop the TIM Output Compare. (+) Start the TIM Output Compare and enable interrupt. (+) Stop the TIM Output Compare and disable interrupt. (+) Start the TIM Output Compare and enable DMA transfer. (+) Stop the TIM Output Compare and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM Output Compare according to the specified * parameters in the TIM_HandleTypeDef and initializes the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_OC_DeInit() before HAL_TIM_OC_Init() * @param htim TIM Output Compare handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim) { /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->OC_MspInitCallback == NULL) { htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->OC_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIM_OC_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Init the base time for the Output Compare */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM peripheral * @param htim TIM Output Compare handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->OC_MspDeInitCallback == NULL) { htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; } /* DeInit the low level hardware */ htim->OC_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ HAL_TIM_OC_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Change the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM Output Compare MSP. * @param htim TIM Output Compare handle * @retval None */ __weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_OC_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM Output Compare MSP. * @param htim TIM Output Compare handle * @retval None */ __weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_OC_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM Output Compare signal generation. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Output Compare signal generation. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Disable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Output Compare signal generation in interrupt mode. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); switch (Channel) { case TIM_CHANNEL_1: { /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Enable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Enable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM Output Compare signal generation in interrupt mode. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @brief Starts the TIM Output Compare signal generation in DMA mode. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param pData The source Buffer address. * @param Length The length of data to be transferred from memory to TIM peripheral * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Set the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) { return HAL_BUSY; } else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); break; } case TIM_CHANNEL_2: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); break; } case TIM_CHANNEL_3: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); break; } case TIM_CHANNEL_4: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM Output Compare signal generation in DMA mode. * @param htim TIM Output Compare handle * @param Channel TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Output compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group3 TIM PWM functions * @brief TIM PWM functions * @verbatim ============================================================================== ##### TIM PWM functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM PWM. (+) De-initialize the TIM PWM. (+) Start the TIM PWM. (+) Stop the TIM PWM. (+) Start the TIM PWM and enable interrupt. (+) Stop the TIM PWM and disable interrupt. (+) Start the TIM PWM and enable DMA transfer. (+) Stop the TIM PWM and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM PWM Time Base according to the specified * parameters in the TIM_HandleTypeDef and initializes the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_PWM_DeInit() before HAL_TIM_PWM_Init() * @param htim TIM PWM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim) { /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->PWM_MspInitCallback == NULL) { htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->PWM_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIM_PWM_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Init the base time for the PWM */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM peripheral * @param htim TIM PWM handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->PWM_MspDeInitCallback == NULL) { htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; } /* DeInit the low level hardware */ htim->PWM_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ HAL_TIM_PWM_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Change the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM PWM MSP. * @param htim TIM PWM handle * @retval None */ __weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PWM_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM PWM MSP. * @param htim TIM PWM handle * @retval None */ __weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PWM_MspDeInit could be implemented in the user file */ } /** * @brief Starts the PWM signal generation. * @param htim TIM handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the PWM signal generation. * @param htim TIM PWM handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Disable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the PWM signal generation in interrupt mode. * @param htim TIM PWM handle * @param Channel TIM Channel to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); switch (Channel) { case TIM_CHANNEL_1: { /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Enable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Enable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the PWM signal generation in interrupt mode. * @param htim TIM PWM handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @brief Starts the TIM PWM signal generation in DMA mode. * @param htim TIM PWM handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param pData The source Buffer address. * @param Length The length of data to be transferred from memory to TIM peripheral * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Set the TIM channel state */ if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) { return HAL_BUSY; } else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); break; } case TIM_CHANNEL_2: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); break; } case TIM_CHANNEL_3: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Output Capture/Compare 3 request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); break; } case TIM_CHANNEL_4: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM PWM signal generation in DMA mode. * @param htim TIM PWM handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group4 TIM Input Capture functions * @brief TIM Input Capture functions * @verbatim ============================================================================== ##### TIM Input Capture functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM Input Capture. (+) De-initialize the TIM Input Capture. (+) Start the TIM Input Capture. (+) Stop the TIM Input Capture. (+) Start the TIM Input Capture and enable interrupt. (+) Stop the TIM Input Capture and disable interrupt. (+) Start the TIM Input Capture and enable DMA transfer. (+) Stop the TIM Input Capture and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM Input Capture Time base according to the specified * parameters in the TIM_HandleTypeDef and initializes the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_IC_DeInit() before HAL_TIM_IC_Init() * @param htim TIM Input Capture handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim) { /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->IC_MspInitCallback == NULL) { htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->IC_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIM_IC_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Init the base time for the input capture */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM peripheral * @param htim TIM Input Capture handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->IC_MspDeInitCallback == NULL) { htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; } /* DeInit the low level hardware */ htim->IC_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ HAL_TIM_IC_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Change the TIM channels state */ TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM Input Capture MSP. * @param htim TIM Input Capture handle * @retval None */ __weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_IC_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM Input Capture MSP. * @param htim TIM handle * @retval None */ __weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_IC_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM Input Capture measurement. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Input Capture measurement. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Disable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Input Capture measurement in interrupt mode. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Check the TIM channel state */ if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); switch (Channel) { case TIM_CHANNEL_1: { /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Enable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Enable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Enable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } } /* Return function status */ return status; } /** * @brief Stops the TIM Input Capture measurement in interrupt mode. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @brief Starts the TIM Input Capture measurement in DMA mode. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param pData The destination Buffer address. * @param Length The length of data to be transferred from TIM peripheral to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); /* Set the TIM channel state */ if ((channel_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; } else if ((channel_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((pData == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } /* Enable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); break; } case TIM_CHANNEL_2: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); break; } case TIM_CHANNEL_3: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); break; } case TIM_CHANNEL_4: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); break; } default: status = HAL_ERROR; break; } /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) { tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) { __HAL_TIM_ENABLE(htim); } } else { __HAL_TIM_ENABLE(htim); } /* Return function status */ return status; } /** * @brief Stops the TIM Input Capture measurement in DMA mode. * @param htim TIM Input Capture handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); /* Disable the Input Capture channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); switch (Channel) { case TIM_CHANNEL_1: { /* Disable the TIM Capture/Compare 1 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_CHANNEL_2: { /* Disable the TIM Capture/Compare 2 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_CHANNEL_3: { /* Disable the TIM Capture/Compare 3 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_CHANNEL_4: { /* Disable the TIM Capture/Compare 4 DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return status; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group5 TIM One Pulse functions * @brief TIM One Pulse functions * @verbatim ============================================================================== ##### TIM One Pulse functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM One Pulse. (+) De-initialize the TIM One Pulse. (+) Start the TIM One Pulse. (+) Stop the TIM One Pulse. (+) Start the TIM One Pulse and enable interrupt. (+) Stop the TIM One Pulse and disable interrupt. (+) Start the TIM One Pulse and enable DMA transfer. (+) Stop the TIM One Pulse and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM One Pulse Time Base according to the specified * parameters in the TIM_HandleTypeDef and initializes the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_OnePulse_DeInit() before HAL_TIM_OnePulse_Init() * @note When the timer instance is initialized in One Pulse mode, timer * channels 1 and channel 2 are reserved and cannot be used for other * purpose. * @param htim TIM One Pulse handle * @param OnePulseMode Select the One pulse mode. * This parameter can be one of the following values: * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated. * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses will be generated. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode) { /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_OPM_MODE(OnePulseMode)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->OnePulse_MspInitCallback == NULL) { htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->OnePulse_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIM_OnePulse_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Configure the Time base in the One Pulse Mode */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Reset the OPM Bit */ htim->Instance->CR1 &= ~TIM_CR1_OPM; /* Configure the OPM Mode */ htim->Instance->CR1 |= OnePulseMode; /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Initialize the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM One Pulse * @param htim TIM One Pulse handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->OnePulse_MspDeInitCallback == NULL) { htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; } /* DeInit the low level hardware */ htim->OnePulse_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ HAL_TIM_OnePulse_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Set the TIM channel state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM One Pulse MSP. * @param htim TIM One Pulse handle * @retval None */ __weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_OnePulse_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM One Pulse MSP. * @param htim TIM One Pulse handle * @retval None */ __weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_OnePulse_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM One Pulse signal generation. * @note Though OutputChannel parameter is deprecated and ignored by the function * it has been kept to avoid HAL_TIM API compatibility break. * @note The pulse output channel is determined when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel See note above * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Prevent unused argument(s) compilation warning */ UNUSED(OutputChannel); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output whatever the combination, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together No need to enable the counter, it's enabled automatically by hardware (the counter starts in response to a stimulus and generate a pulse */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM One Pulse signal generation. * @note Though OutputChannel parameter is deprecated and ignored by the function * it has been kept to avoid HAL_TIM API compatibility break. * @note The pulse output channel is determined when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel See note above * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { /* Prevent unused argument(s) compilation warning */ UNUSED(OutputChannel); /* Disable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output whatever the combination, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM One Pulse signal generation in interrupt mode. * @note Though OutputChannel parameter is deprecated and ignored by the function * it has been kept to avoid HAL_TIM API compatibility break. * @note The pulse output channel is determined when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel See note above * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Prevent unused argument(s) compilation warning */ UNUSED(OutputChannel); /* Check the TIM channels state */ if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); /* Enable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output whatever the combination, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together No need to enable the counter, it's enabled automatically by hardware (the counter starts in response to a stimulus and generate a pulse */ /* Enable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); /* Enable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM One Pulse signal generation in interrupt mode. * @note Though OutputChannel parameter is deprecated and ignored by the function * it has been kept to avoid HAL_TIM API compatibility break. * @note The pulse output channel is determined when calling * @ref HAL_TIM_OnePulse_ConfigChannel(). * @param htim TIM One Pulse handle * @param OutputChannel See note above * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { /* Prevent unused argument(s) compilation warning */ UNUSED(OutputChannel); /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); /* Disable the TIM Capture/Compare 2 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); /* Disable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output whatever the combination, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Disable the Main Output */ __HAL_TIM_MOE_DISABLE(htim); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Return function status */ return HAL_OK; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group6 TIM Encoder functions * @brief TIM Encoder functions * @verbatim ============================================================================== ##### TIM Encoder functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TIM Encoder. (+) De-initialize the TIM Encoder. (+) Start the TIM Encoder. (+) Stop the TIM Encoder. (+) Start the TIM Encoder and enable interrupt. (+) Stop the TIM Encoder and disable interrupt. (+) Start the TIM Encoder and enable DMA transfer. (+) Stop the TIM Encoder and disable DMA transfer. @endverbatim * @{ */ /** * @brief Initializes the TIM Encoder Interface and initialize the associated handle. * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) * requires a timer reset to avoid unexpected direction * due to DIR bit readonly in center aligned mode. * Ex: call @ref HAL_TIM_Encoder_DeInit() before HAL_TIM_Encoder_Init() * @note Encoder mode and External clock mode 2 are not compatible and must not be selected together * Ex: A call for @ref HAL_TIM_Encoder_Init will erase the settings of @ref HAL_TIM_ConfigClockSource * using TIM_CLOCKSOURCE_ETRMODE2 and vice versa * @note When the timer instance is initialized in Encoder mode, timer * channels 1 and channel 2 are reserved and cannot be used for other * purpose. * @param htim TIM Encoder Interface handle * @param sConfig TIM Encoder Interface configuration structure * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef *sConfig) { uint32_t tmpsmcr; uint32_t tmpccmr1; uint32_t tmpccer; /* Check the TIM handle allocation */ if (htim == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode)); assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection)); assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection)); assert_param(IS_TIM_ENCODERINPUT_POLARITY(sConfig->IC1Polarity)); assert_param(IS_TIM_ENCODERINPUT_POLARITY(sConfig->IC2Polarity)); assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); assert_param(IS_TIM_IC_PRESCALER(sConfig->IC2Prescaler)); assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); assert_param(IS_TIM_IC_FILTER(sConfig->IC2Filter)); if (htim->State == HAL_TIM_STATE_RESET) { /* Allocate lock resource and initialize it */ htim->Lock = HAL_UNLOCKED; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /* Reset interrupt callbacks to legacy weak callbacks */ TIM_ResetCallback(htim); if (htim->Encoder_MspInitCallback == NULL) { htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; } /* Init the low level hardware : GPIO, CLOCK, NVIC */ htim->Encoder_MspInitCallback(htim); #else /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ HAL_TIM_Encoder_MspInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Set the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Reset the SMS and ECE bits */ htim->Instance->SMCR &= ~(TIM_SMCR_SMS | TIM_SMCR_ECE); /* Configure the Time base in the Encoder Mode */ TIM_Base_SetConfig(htim->Instance, &htim->Init); /* Get the TIMx SMCR register value */ tmpsmcr = htim->Instance->SMCR; /* Get the TIMx CCMR1 register value */ tmpccmr1 = htim->Instance->CCMR1; /* Get the TIMx CCER register value */ tmpccer = htim->Instance->CCER; /* Set the encoder Mode */ tmpsmcr |= sConfig->EncoderMode; /* Select the Capture Compare 1 and the Capture Compare 2 as input */ tmpccmr1 &= ~(TIM_CCMR1_CC1S | TIM_CCMR1_CC2S); tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8U)); /* Set the Capture Compare 1 and the Capture Compare 2 prescalers and filters */ tmpccmr1 &= ~(TIM_CCMR1_IC1PSC | TIM_CCMR1_IC2PSC); tmpccmr1 &= ~(TIM_CCMR1_IC1F | TIM_CCMR1_IC2F); tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8U); tmpccmr1 |= (sConfig->IC1Filter << 4U) | (sConfig->IC2Filter << 12U); /* Set the TI1 and the TI2 Polarities */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC2P); tmpccer &= ~(TIM_CCER_CC1NP | TIM_CCER_CC2NP); tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4U); /* Write to TIMx SMCR */ htim->Instance->SMCR = tmpsmcr; /* Write to TIMx CCMR1 */ htim->Instance->CCMR1 = tmpccmr1; /* Write to TIMx CCER */ htim->Instance->CCER = tmpccer; /* Initialize the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); /* Initialize the TIM state*/ htim->State = HAL_TIM_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the TIM Encoder interface * @param htim TIM Encoder Interface handle * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); htim->State = HAL_TIM_STATE_BUSY; /* Disable the TIM Peripheral Clock */ __HAL_TIM_DISABLE(htim); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) if (htim->Encoder_MspDeInitCallback == NULL) { htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; } /* DeInit the low level hardware */ htim->Encoder_MspDeInitCallback(htim); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ HAL_TIM_Encoder_MspDeInit(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; /* Set the TIM channels state */ TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); /* Change TIM state */ htim->State = HAL_TIM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Initializes the TIM Encoder Interface MSP. * @param htim TIM Encoder Interface handle * @retval None */ __weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_Encoder_MspInit could be implemented in the user file */ } /** * @brief DeInitializes TIM Encoder Interface MSP. * @param htim TIM Encoder Interface handle * @retval None */ __weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_Encoder_MspDeInit could be implemented in the user file */ } /** * @brief Starts the TIM Encoder Interface. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Set the TIM channel(s) state */ if (Channel == TIM_CHANNEL_1) { if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); } } else if (Channel == TIM_CHANNEL_2) { if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } /* Enable the encoder interface channels */ switch (Channel) { case TIM_CHANNEL_1: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); break; } case TIM_CHANNEL_2: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); break; } default : { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); break; } } /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Encoder Interface. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channels 1 and 2 (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ switch (Channel) { case TIM_CHANNEL_1: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); break; } case TIM_CHANNEL_2: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); break; } default : { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); break; } } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel(s) state */ if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Encoder Interface in interrupt mode. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Set the TIM channel(s) state */ if (Channel == TIM_CHANNEL_1) { if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); } } else if (Channel == TIM_CHANNEL_2) { if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } /* Enable the encoder interface channels */ /* Enable the capture compare Interrupts 1 and/or 2 */ switch (Channel) { case TIM_CHANNEL_1: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); break; } case TIM_CHANNEL_2: { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } default : { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); break; } } /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Encoder Interface in interrupt mode. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channels 1 and 2 (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ if (Channel == TIM_CHANNEL_1) { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); /* Disable the capture compare Interrupts 1 */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); } else if (Channel == TIM_CHANNEL_2) { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); /* Disable the capture compare Interrupts 2 */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); } else { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); /* Disable the capture compare Interrupts 1 and 2 */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel(s) state */ if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return HAL_OK; } /** * @brief Starts the TIM Encoder Interface in DMA mode. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @param pData1 The destination Buffer address for IC1. * @param pData2 The destination Buffer address for IC2. * @param Length The length of data to be transferred from TIM peripheral to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length) { HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Set the TIM channel(s) state */ if (Channel == TIM_CHANNEL_1) { if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((pData1 == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } } else if (Channel == TIM_CHANNEL_2) { if ((channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; } else if ((channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((pData2 == NULL) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } } else { if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { return HAL_ERROR; } } switch (Channel) { case TIM_CHANNEL_1: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Input Capture DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); break; } case TIM_CHANNEL_2: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Input Capture DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); break; } default: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length) != HAL_OK) { /* Return error status */ return HAL_ERROR; } /* Enable the TIM Input Capture DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); /* Enable the TIM Input Capture DMA request */ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); break; } } /* Return function status */ return HAL_OK; } /** * @brief Stops the TIM Encoder Interface in DMA mode. * @param htim TIM Encoder Interface handle * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); /* Disable the Input Capture channels 1 and 2 (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ if (Channel == TIM_CHANNEL_1) { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); /* Disable the capture compare DMA Request 1 */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); } else if (Channel == TIM_CHANNEL_2) { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); /* Disable the capture compare DMA Request 2 */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); } else { TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); /* Disable the capture compare DMA Request 1 and 2 */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); } /* Disable the Peripheral */ __HAL_TIM_DISABLE(htim); /* Set the TIM channel(s) state */ if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) { TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } /* Return function status */ return HAL_OK; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group7 TIM IRQ handler management * @brief TIM IRQ handler management * @verbatim ============================================================================== ##### IRQ handler management ##### ============================================================================== [..] This section provides Timer IRQ handler function. @endverbatim * @{ */ /** * @brief This function handles TIM interrupts requests. * @param htim TIM handle * @retval None */ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { /* Capture compare 1 event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET) { { __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; /* Input capture event */ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U) { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureCallback(htim); #else HAL_TIM_IC_CaptureCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Output compare event */ else { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->OC_DelayElapsedCallback(htim); htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_OC_DelayElapsedCallback(htim); HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } } } /* Capture compare 2 event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; /* Input capture event */ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureCallback(htim); #else HAL_TIM_IC_CaptureCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Output compare event */ else { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->OC_DelayElapsedCallback(htim); htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_OC_DelayElapsedCallback(htim); HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } } /* Capture compare 3 event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureCallback(htim); #else HAL_TIM_IC_CaptureCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Output compare event */ else { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->OC_DelayElapsedCallback(htim); htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_OC_DelayElapsedCallback(htim); HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } } /* Capture compare 4 event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureCallback(htim); #else HAL_TIM_IC_CaptureCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /* Output compare event */ else { #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->OC_DelayElapsedCallback(htim); htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_OC_DelayElapsedCallback(htim); HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } } /* TIM Update event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedCallback(htim); #else HAL_TIM_PeriodElapsedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Break input event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->BreakCallback(htim); #else HAL_TIMEx_BreakCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Break2 input event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK2) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET) { __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK2); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->Break2Callback(htim); #else HAL_TIMEx_Break2Callback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Trigger detection event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerCallback(htim); #else HAL_TIM_TriggerCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM commutation event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationCallback(htim); #else HAL_TIMEx_CommutCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Encoder index event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_IDX) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_IDX) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_IDX); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->EncoderIndexCallback(htim); #else HAL_TIMEx_EncoderIndexCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Direction change event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_DIR) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_DIR) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_DIR); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->DirectionChangeCallback(htim); #else HAL_TIMEx_DirectionChangeCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Index error event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_IERR) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_IERR) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_IERR); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IndexErrorCallback(htim); #else HAL_TIMEx_IndexErrorCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } /* TIM Transition error event */ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TERR) != RESET) { if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TERR) != RESET) { __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_TERR); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TransitionErrorCallback(htim); #else HAL_TIMEx_TransitionErrorCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } } } /** * @} */ /** @defgroup TIM_Exported_Functions_Group8 TIM Peripheral Control functions * @brief TIM Peripheral Control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode. (+) Configure External Clock source. (+) Configure Complementary channels, break features and dead time. (+) Configure Master and the Slave synchronization. (+) Configure the DMA Burst Mode. @endverbatim * @{ */ /** * @brief Initializes the TIM Output Compare Channels according to the specified * parameters in the TIM_OC_InitTypeDef. * @param htim TIM Output Compare handle * @param sConfig TIM Output Compare configuration structure * @param Channel TIM Channels to configure * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef *sConfig, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CHANNELS(Channel)); assert_param(IS_TIM_OC_CHANNEL_MODE(sConfig->OCMode, Channel)); assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); /* Process Locked */ __HAL_LOCK(htim); switch (Channel) { case TIM_CHANNEL_1: { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); /* Configure the TIM Channel 1 in Output Compare */ TIM_OC1_SetConfig(htim->Instance, sConfig); break; } case TIM_CHANNEL_2: { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); /* Configure the TIM Channel 2 in Output Compare */ TIM_OC2_SetConfig(htim->Instance, sConfig); break; } case TIM_CHANNEL_3: { /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); /* Configure the TIM Channel 3 in Output Compare */ TIM_OC3_SetConfig(htim->Instance, sConfig); break; } case TIM_CHANNEL_4: { /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); /* Configure the TIM Channel 4 in Output Compare */ TIM_OC4_SetConfig(htim->Instance, sConfig); break; } case TIM_CHANNEL_5: { /* Check the parameters */ assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); /* Configure the TIM Channel 5 in Output Compare */ TIM_OC5_SetConfig(htim->Instance, sConfig); break; } case TIM_CHANNEL_6: { /* Check the parameters */ assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); /* Configure the TIM Channel 6 in Output Compare */ TIM_OC6_SetConfig(htim->Instance, sConfig); break; } default: status = HAL_ERROR; break; } __HAL_UNLOCK(htim); return status; } /** * @brief Initializes the TIM Input Capture Channels according to the specified * parameters in the TIM_IC_InitTypeDef. * @param htim TIM IC handle * @param sConfig TIM Input Capture configuration structure * @param Channel TIM Channel to configure * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef *sConfig, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); assert_param(IS_TIM_IC_POLARITY(sConfig->ICPolarity)); assert_param(IS_TIM_IC_SELECTION(sConfig->ICSelection)); assert_param(IS_TIM_IC_PRESCALER(sConfig->ICPrescaler)); assert_param(IS_TIM_IC_FILTER(sConfig->ICFilter)); /* Process Locked */ __HAL_LOCK(htim); if (Channel == TIM_CHANNEL_1) { /* TI1 Configuration */ TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC1PSC Bits */ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC; /* Set the IC1PSC value */ htim->Instance->CCMR1 |= sConfig->ICPrescaler; } else if (Channel == TIM_CHANNEL_2) { /* TI2 Configuration */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC2PSC Bits */ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC; /* Set the IC2PSC value */ htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8U); } else if (Channel == TIM_CHANNEL_3) { /* TI3 Configuration */ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); TIM_TI3_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC3PSC Bits */ htim->Instance->CCMR2 &= ~TIM_CCMR2_IC3PSC; /* Set the IC3PSC value */ htim->Instance->CCMR2 |= sConfig->ICPrescaler; } else if (Channel == TIM_CHANNEL_4) { /* TI4 Configuration */ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); TIM_TI4_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC4PSC Bits */ htim->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC; /* Set the IC4PSC value */ htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8U); } else { status = HAL_ERROR; } __HAL_UNLOCK(htim); return status; } /** * @brief Initializes the TIM PWM channels according to the specified * parameters in the TIM_OC_InitTypeDef. * @param htim TIM PWM handle * @param sConfig TIM PWM configuration structure * @param Channel TIM Channels to be configured * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef *sConfig, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_CHANNELS(Channel)); assert_param(IS_TIM_PWM_MODE(sConfig->OCMode)); assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); assert_param(IS_TIM_FAST_STATE(sConfig->OCFastMode)); /* Process Locked */ __HAL_LOCK(htim); switch (Channel) { case TIM_CHANNEL_1: { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); /* Configure the Channel 1 in PWM mode */ TIM_OC1_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel1 */ htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE; /* Configure the Output Fast mode */ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1FE; htim->Instance->CCMR1 |= sConfig->OCFastMode; break; } case TIM_CHANNEL_2: { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); /* Configure the Channel 2 in PWM mode */ TIM_OC2_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel2 */ htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE; /* Configure the Output Fast mode */ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2FE; htim->Instance->CCMR1 |= sConfig->OCFastMode << 8U; break; } case TIM_CHANNEL_3: { /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); /* Configure the Channel 3 in PWM mode */ TIM_OC3_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel3 */ htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE; /* Configure the Output Fast mode */ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3FE; htim->Instance->CCMR2 |= sConfig->OCFastMode; break; } case TIM_CHANNEL_4: { /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); /* Configure the Channel 4 in PWM mode */ TIM_OC4_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel4 */ htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE; /* Configure the Output Fast mode */ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4FE; htim->Instance->CCMR2 |= sConfig->OCFastMode << 8U; break; } case TIM_CHANNEL_5: { /* Check the parameters */ assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); /* Configure the Channel 5 in PWM mode */ TIM_OC5_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel5*/ htim->Instance->CCMR3 |= TIM_CCMR3_OC5PE; /* Configure the Output Fast mode */ htim->Instance->CCMR3 &= ~TIM_CCMR3_OC5FE; htim->Instance->CCMR3 |= sConfig->OCFastMode; break; } case TIM_CHANNEL_6: { /* Check the parameters */ assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); /* Configure the Channel 6 in PWM mode */ TIM_OC6_SetConfig(htim->Instance, sConfig); /* Set the Preload enable bit for channel6 */ htim->Instance->CCMR3 |= TIM_CCMR3_OC6PE; /* Configure the Output Fast mode */ htim->Instance->CCMR3 &= ~TIM_CCMR3_OC6FE; htim->Instance->CCMR3 |= sConfig->OCFastMode << 8U; break; } default: status = HAL_ERROR; break; } __HAL_UNLOCK(htim); return status; } /** * @brief Initializes the TIM One Pulse Channels according to the specified * parameters in the TIM_OnePulse_InitTypeDef. * @param htim TIM One Pulse handle * @param sConfig TIM One Pulse configuration structure * @param OutputChannel TIM output channel to configure * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @param InputChannel TIM input Channel to configure * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @note To output a waveform with a minimum delay user can enable the fast * mode by calling the @ref __HAL_TIM_ENABLE_OCxFAST macro. Then CCx * output is forced in response to the edge detection on TIx input, * without taking in account the comparison. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef *sConfig, uint32_t OutputChannel, uint32_t InputChannel) { HAL_StatusTypeDef status = HAL_OK; TIM_OC_InitTypeDef temp1; /* Check the parameters */ assert_param(IS_TIM_OPM_CHANNELS(OutputChannel)); assert_param(IS_TIM_OPM_CHANNELS(InputChannel)); if (OutputChannel != InputChannel) { /* Process Locked */ __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; /* Extract the Output compare configuration from sConfig structure */ temp1.OCMode = sConfig->OCMode; temp1.Pulse = sConfig->Pulse; temp1.OCPolarity = sConfig->OCPolarity; temp1.OCNPolarity = sConfig->OCNPolarity; temp1.OCIdleState = sConfig->OCIdleState; temp1.OCNIdleState = sConfig->OCNIdleState; switch (OutputChannel) { case TIM_CHANNEL_1: { assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); TIM_OC1_SetConfig(htim->Instance, &temp1); break; } case TIM_CHANNEL_2: { assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); TIM_OC2_SetConfig(htim->Instance, &temp1); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { switch (InputChannel) { case TIM_CHANNEL_1: { assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC1PSC Bits */ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC; /* Select the Trigger source */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= TIM_TS_TI1FP1; /* Select the Slave Mode */ htim->Instance->SMCR &= ~TIM_SMCR_SMS; htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; break; } case TIM_CHANNEL_2: { assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter); /* Reset the IC2PSC Bits */ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC; /* Select the Trigger source */ htim->Instance->SMCR &= ~TIM_SMCR_TS; htim->Instance->SMCR |= TIM_TS_TI2FP2; /* Select the Slave Mode */ htim->Instance->SMCR &= ~TIM_SMCR_SMS; htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; break; } default: status = HAL_ERROR; break; } } htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return status; } else { return HAL_ERROR; } } /** * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral * @param htim TIM handle * @param BurstBaseAddress TIM Base address from where the DMA will start the Data write * This parameter can be one of the following values: * @arg TIM_DMABASE_CR1 * @arg TIM_DMABASE_CR2 * @arg TIM_DMABASE_SMCR * @arg TIM_DMABASE_DIER * @arg TIM_DMABASE_SR * @arg TIM_DMABASE_EGR * @arg TIM_DMABASE_CCMR1 * @arg TIM_DMABASE_CCMR2 * @arg TIM_DMABASE_CCER * @arg TIM_DMABASE_CNT * @arg TIM_DMABASE_PSC * @arg TIM_DMABASE_ARR * @arg TIM_DMABASE_RCR * @arg TIM_DMABASE_CCR1 * @arg TIM_DMABASE_CCR2 * @arg TIM_DMABASE_CCR3 * @arg TIM_DMABASE_CCR4 * @arg TIM_DMABASE_BDTR * @arg TIM_DMABASE_CCMR3 * @arg TIM_DMABASE_CCR5 * @arg TIM_DMABASE_CCR6 * @arg TIM_DMABASE_DTR2 * @arg TIM_DMABASE_ECR * @arg TIM_DMABASE_TISEL * @arg TIM_DMABASE_AF1 * @arg TIM_DMABASE_AF2 * @arg TIM_DMABASE_OR * @param BurstRequestSrc TIM DMA Request sources * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: TIM update Interrupt source * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source * @arg TIM_DMA_COM: TIM Commutation DMA source * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source * @param BurstBuffer The Buffer address. * @param BurstLength DMA Burst length. This parameter can be one value * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_26TRANSFER. * @note This function should be used only when BurstLength is equal to DMA data transfer length. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) { HAL_StatusTypeDef status; status = HAL_TIM_DMABurst_MultiWriteStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, ((BurstLength) >> 8U) + 1U); return status; } /** * @brief Configure the DMA Burst to transfer multiple Data from the memory to the TIM peripheral * @param htim TIM handle * @param BurstBaseAddress TIM Base address from where the DMA will start the Data write * This parameter can be one of the following values: * @arg TIM_DMABASE_CR1 * @arg TIM_DMABASE_CR2 * @arg TIM_DMABASE_SMCR * @arg TIM_DMABASE_DIER * @arg TIM_DMABASE_SR * @arg TIM_DMABASE_EGR * @arg TIM_DMABASE_CCMR1 * @arg TIM_DMABASE_CCMR2 * @arg TIM_DMABASE_CCER * @arg TIM_DMABASE_CNT * @arg TIM_DMABASE_PSC * @arg TIM_DMABASE_ARR * @arg TIM_DMABASE_RCR * @arg TIM_DMABASE_CCR1 * @arg TIM_DMABASE_CCR2 * @arg TIM_DMABASE_CCR3 * @arg TIM_DMABASE_CCR4 * @arg TIM_DMABASE_BDTR * @arg TIM_DMABASE_CCMR3 * @arg TIM_DMABASE_CCR5 * @arg TIM_DMABASE_CCR6 * @arg TIM_DMABASE_DTR2 * @arg TIM_DMABASE_ECR * @arg TIM_DMABASE_TISEL * @arg TIM_DMABASE_AF1 * @arg TIM_DMABASE_AF2 * @arg TIM_DMABASE_OR * @param BurstRequestSrc TIM DMA Request sources * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: TIM update Interrupt source * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source * @arg TIM_DMA_COM: TIM Commutation DMA source * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source * @param BurstBuffer The Buffer address. * @param BurstLength DMA Burst length. This parameter can be one value * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_26TRANSFER. * @param DataLength Data length. This parameter can be one value * between 1 and 0xFFFF. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength, uint32_t DataLength) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); assert_param(IS_TIM_DMA_LENGTH(BurstLength)); assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) { return HAL_BUSY; } else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) { if ((BurstBuffer == NULL) && (BurstLength > 0U)) { return HAL_ERROR; } else { htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; } } else { /* nothing to do */ } switch (BurstRequestSrc) { case TIM_DMA_UPDATE: { /* Set the DMA Period elapsed callbacks */ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC1: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC2: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC3: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC4: { /* Set the DMA compare callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_COM: { /* Set the DMA commutation callbacks */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_TRIGGER: { /* Set the DMA trigger callbacks */ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Configure the DMA Burst Mode */ htim->Instance->DCR = (BurstBaseAddress | BurstLength); /* Enable the TIM DMA Request */ __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); } /* Return function status */ return status; } /** * @brief Stops the TIM DMA Burst mode * @param htim TIM handle * @param BurstRequestSrc TIM DMA Request sources to disable * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); /* Abort the DMA transfer (at least disable the DMA channel) */ switch (BurstRequestSrc) { case TIM_DMA_UPDATE: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); break; } case TIM_DMA_CC1: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_DMA_CC2: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_DMA_CC3: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_DMA_CC4: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } case TIM_DMA_COM: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); break; } case TIM_DMA_TRIGGER: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the TIM Update DMA request */ __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; } /* Return function status */ return status; } /** * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory * @param htim TIM handle * @param BurstBaseAddress TIM Base address from where the DMA will start the Data read * This parameter can be one of the following values: * @arg TIM_DMABASE_CR1 * @arg TIM_DMABASE_CR2 * @arg TIM_DMABASE_SMCR * @arg TIM_DMABASE_DIER * @arg TIM_DMABASE_SR * @arg TIM_DMABASE_EGR * @arg TIM_DMABASE_CCMR1 * @arg TIM_DMABASE_CCMR2 * @arg TIM_DMABASE_CCER * @arg TIM_DMABASE_CNT * @arg TIM_DMABASE_PSC * @arg TIM_DMABASE_ARR * @arg TIM_DMABASE_RCR * @arg TIM_DMABASE_CCR1 * @arg TIM_DMABASE_CCR2 * @arg TIM_DMABASE_CCR3 * @arg TIM_DMABASE_CCR4 * @arg TIM_DMABASE_BDTR * @arg TIM_DMABASE_CCMR3 * @arg TIM_DMABASE_CCR5 * @arg TIM_DMABASE_CCR6 * @arg TIM_DMABASE_DTR2 * @arg TIM_DMABASE_ECR * @arg TIM_DMABASE_TISEL * @arg TIM_DMABASE_AF1 * @arg TIM_DMABASE_AF2 * @arg TIM_DMABASE_OR * @param BurstRequestSrc TIM DMA Request sources * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: TIM update Interrupt source * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source * @arg TIM_DMA_COM: TIM Commutation DMA source * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source * @param BurstBuffer The Buffer address. * @param BurstLength DMA Burst length. This parameter can be one value * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_26TRANSFER. * @note This function should be used only when BurstLength is equal to DMA data transfer length. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) { HAL_StatusTypeDef status; status = HAL_TIM_DMABurst_MultiReadStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, ((BurstLength) >> 8U) + 1U); return status; } /** * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory * @param htim TIM handle * @param BurstBaseAddress TIM Base address from where the DMA will start the Data read * This parameter can be one of the following values: * @arg TIM_DMABASE_CR1 * @arg TIM_DMABASE_CR2 * @arg TIM_DMABASE_SMCR * @arg TIM_DMABASE_DIER * @arg TIM_DMABASE_SR * @arg TIM_DMABASE_EGR * @arg TIM_DMABASE_CCMR1 * @arg TIM_DMABASE_CCMR2 * @arg TIM_DMABASE_CCER * @arg TIM_DMABASE_CNT * @arg TIM_DMABASE_PSC * @arg TIM_DMABASE_ARR * @arg TIM_DMABASE_RCR * @arg TIM_DMABASE_CCR1 * @arg TIM_DMABASE_CCR2 * @arg TIM_DMABASE_CCR3 * @arg TIM_DMABASE_CCR4 * @arg TIM_DMABASE_BDTR * @arg TIM_DMABASE_CCMR3 * @arg TIM_DMABASE_CCR5 * @arg TIM_DMABASE_CCR6 * @arg TIM_DMABASE_DTR2 * @arg TIM_DMABASE_ECR * @arg TIM_DMABASE_TISEL * @arg TIM_DMABASE_AF1 * @arg TIM_DMABASE_AF2 * @arg TIM_DMABASE_OR * @param BurstRequestSrc TIM DMA Request sources * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: TIM update Interrupt source * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source * @arg TIM_DMA_COM: TIM Commutation DMA source * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source * @param BurstBuffer The Buffer address. * @param BurstLength DMA Burst length. This parameter can be one value * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_26TRANSFER. * @param DataLength Data length. This parameter can be one value * between 1 and 0xFFFF. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_MultiReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength, uint32_t DataLength) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); assert_param(IS_TIM_DMA_LENGTH(BurstLength)); assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) { return HAL_BUSY; } else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) { if ((BurstBuffer == NULL) && (BurstLength > 0U)) { return HAL_ERROR; } else { htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; } } else { /* nothing to do */ } switch (BurstRequestSrc) { case TIM_DMA_UPDATE: { /* Set the DMA Period elapsed callbacks */ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC1: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC2: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC3: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_CC4: { /* Set the DMA capture callbacks */ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_COM: { /* Set the DMA commutation callbacks */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } case TIM_DMA_TRIGGER: { /* Set the DMA trigger callbacks */ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; /* Set the DMA error callback */ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, DataLength) != HAL_OK) { /* Return error status */ return HAL_ERROR; } break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Configure the DMA Burst Mode */ htim->Instance->DCR = (BurstBaseAddress | BurstLength); /* Enable the TIM DMA Request */ __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); } /* Return function status */ return status; } /** * @brief Stop the DMA burst reading * @param htim TIM handle * @param BurstRequestSrc TIM DMA Request sources to disable. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); /* Abort the DMA transfer (at least disable the DMA channel) */ switch (BurstRequestSrc) { case TIM_DMA_UPDATE: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); break; } case TIM_DMA_CC1: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); break; } case TIM_DMA_CC2: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); break; } case TIM_DMA_CC3: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); break; } case TIM_DMA_CC4: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); break; } case TIM_DMA_COM: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); break; } case TIM_DMA_TRIGGER: { (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { /* Disable the TIM Update DMA request */ __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); /* Change the DMA burst operation state */ htim->DMABurstState = HAL_DMA_BURST_STATE_READY; } /* Return function status */ return status; } /** * @brief Generate a software event * @param htim TIM handle * @param EventSource specifies the event source. * This parameter can be one of the following values: * @arg TIM_EVENTSOURCE_UPDATE: Timer update Event source * @arg TIM_EVENTSOURCE_CC1: Timer Capture Compare 1 Event source * @arg TIM_EVENTSOURCE_CC2: Timer Capture Compare 2 Event source * @arg TIM_EVENTSOURCE_CC3: Timer Capture Compare 3 Event source * @arg TIM_EVENTSOURCE_CC4: Timer Capture Compare 4 Event source * @arg TIM_EVENTSOURCE_COM: Timer COM event source * @arg TIM_EVENTSOURCE_TRIGGER: Timer Trigger Event source * @arg TIM_EVENTSOURCE_BREAK: Timer Break event source * @arg TIM_EVENTSOURCE_BREAK2: Timer Break2 event source * @note Basic timers can only generate an update event. * @note TIM_EVENTSOURCE_COM is relevant only with advanced timer instances. * @note TIM_EVENTSOURCE_BREAK and TIM_EVENTSOURCE_BREAK2 are relevant * only for timer instances supporting break input(s). * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource) { /* Check the parameters */ assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_EVENT_SOURCE(EventSource)); /* Process Locked */ __HAL_LOCK(htim); /* Change the TIM state */ htim->State = HAL_TIM_STATE_BUSY; /* Set the event sources */ htim->Instance->EGR = EventSource; /* Change the TIM state */ htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); /* Return function status */ return HAL_OK; } /** * @brief Configures the OCRef clear feature * @param htim TIM handle * @param sClearInputConfig pointer to a TIM_ClearInputConfigTypeDef structure that * contains the OCREF clear feature and parameters for the TIM peripheral. * @param Channel specifies the TIM Channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 * @arg TIM_CHANNEL_2: TIM Channel 2 * @arg TIM_CHANNEL_3: TIM Channel 3 * @arg TIM_CHANNEL_4: TIM Channel 4 * @arg TIM_CHANNEL_5: TIM Channel 5 * @arg TIM_CHANNEL_6: TIM Channel 6 * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef *sClearInputConfig, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance)); assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); /* Process Locked */ __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; switch (sClearInputConfig->ClearInputSource) { case TIM_CLEARINPUTSOURCE_NONE: { /* Clear the OCREF clear selection bit and the the ETR Bits */ if (IS_TIM_OCCS_INSTANCE(htim->Instance)) { CLEAR_BIT(htim->Instance->SMCR, (TIM_SMCR_OCCS | TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); /* Clear TIMx_AF2_OCRSEL (reset value) */ CLEAR_BIT(htim->Instance->AF2, TIMx_AF2_OCRSEL); } else { CLEAR_BIT(htim->Instance->SMCR, (TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); } break; } case TIM_CLEARINPUTSOURCE_COMP1: case TIM_CLEARINPUTSOURCE_COMP2: case TIM_CLEARINPUTSOURCE_COMP3: case TIM_CLEARINPUTSOURCE_COMP4: #if defined (COMP5) case TIM_CLEARINPUTSOURCE_COMP5: #endif /* COMP5 */ #if defined (COMP6) case TIM_CLEARINPUTSOURCE_COMP6: #endif /* COMP6 */ #if defined (COMP7) case TIM_CLEARINPUTSOURCE_COMP7: #endif /* COMP7 */ { if (IS_TIM_OCCS_INSTANCE(htim->Instance)) { /* Clear the OCREF clear selection bit */ CLEAR_BIT(htim->Instance->SMCR, TIM_SMCR_OCCS); /* Clear TIM1_AF2_OCRSEL (reset value) */ MODIFY_REG(htim->Instance->AF2, TIMx_AF2_OCRSEL, sClearInputConfig->ClearInputSource); } break; } case TIM_CLEARINPUTSOURCE_ETR: { /* Check the parameters */ assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); /* When OCRef clear feature is used with ETR source, ETR prescaler must be off */ if (sClearInputConfig->ClearInputPrescaler != TIM_CLEARINPUTPRESCALER_DIV1) { htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_ERROR; } TIM_ETR_SetConfig(htim->Instance, sClearInputConfig->ClearInputPrescaler, sClearInputConfig->ClearInputPolarity, sClearInputConfig->ClearInputFilter); if (IS_TIM_OCCS_INSTANCE(htim->Instance)) { /* Set the OCREF clear selection bit */ SET_BIT(htim->Instance->SMCR, TIM_SMCR_OCCS); /* Clear TIMx_AF2_OCRSEL (reset value) */ CLEAR_BIT(htim->Instance->AF2, TIMx_AF2_OCRSEL); } break; } default: status = HAL_ERROR; break; } if (status == HAL_OK) { switch (Channel) { case TIM_CHANNEL_1: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 1 */ SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); } else { /* Disable the OCREF clear feature for Channel 1 */ CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); } break; } case TIM_CHANNEL_2: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 2 */ SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); } else { /* Disable the OCREF clear feature for Channel 2 */ CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); } break; } case TIM_CHANNEL_3: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 3 */ SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); } else { /* Disable the OCREF clear feature for Channel 3 */ CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); } break; } case TIM_CHANNEL_4: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 4 */ SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); } else { /* Disable the OCREF clear feature for Channel 4 */ CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); } break; } case TIM_CHANNEL_5: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 5 */ SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); } else { /* Disable the OCREF clear feature for Channel 5 */ CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); } break; } case TIM_CHANNEL_6: { if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) { /* Enable the OCREF clear feature for Channel 6 */ SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); } else { /* Disable the OCREF clear feature for Channel 6 */ CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); } break; } default: break; } } htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return status; } /** * @brief Configures the clock source to be used * @param htim TIM handle * @param sClockSourceConfig pointer to a TIM_ClockConfigTypeDef structure that * contains the clock source information for the TIM peripheral. * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef *sClockSourceConfig) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; /* Process Locked */ __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; /* Check the parameters */ assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource)); /* Reset the SMS, TS, ECE, ETPS and ETRF bits */ tmpsmcr = htim->Instance->SMCR; tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS); tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); htim->Instance->SMCR = tmpsmcr; switch (sClockSourceConfig->ClockSource) { case TIM_CLOCKSOURCE_INTERNAL: { assert_param(IS_TIM_INSTANCE(htim->Instance)); break; } case TIM_CLOCKSOURCE_ETRMODE1: { /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/ assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); /* Check ETR input conditioning related parameters */ assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); /* Configure the ETR Clock source */ TIM_ETR_SetConfig(htim->Instance, sClockSourceConfig->ClockPrescaler, sClockSourceConfig->ClockPolarity, sClockSourceConfig->ClockFilter); /* Select the External clock mode1 and the ETRF trigger */ tmpsmcr = htim->Instance->SMCR; tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1); /* Write to TIMx SMCR */ htim->Instance->SMCR = tmpsmcr; break; } case TIM_CLOCKSOURCE_ETRMODE2: { /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/ assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance)); /* Check ETR input conditioning related parameters */ assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); /* Configure the ETR Clock source */ TIM_ETR_SetConfig(htim->Instance, sClockSourceConfig->ClockPrescaler, sClockSourceConfig->ClockPolarity, sClockSourceConfig->ClockFilter); /* Enable the External clock mode2 */ htim->Instance->SMCR |= TIM_SMCR_ECE; break; } case TIM_CLOCKSOURCE_TI1: { /* Check whether or not the timer instance supports external clock mode 1 */ assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); /* Check TI1 input conditioning related parameters */ assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); TIM_TI1_ConfigInputStage(htim->Instance, sClockSourceConfig->ClockPolarity, sClockSourceConfig->ClockFilter); TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1); break; } case TIM_CLOCKSOURCE_TI2: { /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/ assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); /* Check TI2 input conditioning related parameters */ assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); TIM_TI2_ConfigInputStage(htim->Instance, sClockSourceConfig->ClockPolarity, sClockSourceConfig->ClockFilter); TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2); break; } case TIM_CLOCKSOURCE_TI1ED: { /* Check whether or not the timer instance supports external clock mode 1 */ assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); /* Check TI1 input conditioning related parameters */ assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); TIM_TI1_ConfigInputStage(htim->Instance, sClockSourceConfig->ClockPolarity, sClockSourceConfig->ClockFilter); TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED); break; } case TIM_CLOCKSOURCE_ITR0: case TIM_CLOCKSOURCE_ITR1: case TIM_CLOCKSOURCE_ITR2: case TIM_CLOCKSOURCE_ITR3: #if defined (TIM5) case TIM_CLOCKSOURCE_ITR4: #endif /* TIM5 */ case TIM_CLOCKSOURCE_ITR5: case TIM_CLOCKSOURCE_ITR6: case TIM_CLOCKSOURCE_ITR7: case TIM_CLOCKSOURCE_ITR8: #if defined (TIM20) case TIM_CLOCKSOURCE_ITR9: #endif /* TIM20 */ #if defined (HRTIM1) case TIM_CLOCKSOURCE_ITR10: #endif /* HRTIM1 */ case TIM_CLOCKSOURCE_ITR11: { /* Check whether or not the timer instance supports internal trigger input */ assert_param(IS_TIM_CLOCKSOURCE_INSTANCE((htim->Instance), sClockSourceConfig->ClockSource)); TIM_ITRx_SetConfig(htim->Instance, sClockSourceConfig->ClockSource); break; } default: status = HAL_ERROR; break; } htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return status; } /** * @brief Selects the signal connected to the TI1 input: direct from CH1_input * or a XOR combination between CH1_input, CH2_input & CH3_input * @param htim TIM handle. * @param TI1_Selection Indicate whether or not channel 1 is connected to the * output of a XOR gate. * This parameter can be one of the following values: * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3 * pins are connected to the TI1 input (XOR combination) * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection) { uint32_t tmpcr2; /* Check the parameters */ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); assert_param(IS_TIM_TI1SELECTION(TI1_Selection)); /* Get the TIMx CR2 register value */ tmpcr2 = htim->Instance->CR2; /* Reset the TI1 selection */ tmpcr2 &= ~TIM_CR2_TI1S; /* Set the TI1 selection */ tmpcr2 |= TI1_Selection; /* Write to TIMxCR2 */ htim->Instance->CR2 = tmpcr2; return HAL_OK; } /** * @brief Configures the TIM in Slave mode * @param htim TIM handle. * @param sSlaveConfig pointer to a TIM_SlaveConfigTypeDef structure that * contains the selected trigger (internal trigger input, filtered * timer input or external trigger input) and the Slave mode * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) { /* Check the parameters */ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) { htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_ERROR; } /* Disable Trigger Interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_TRIGGER); /* Disable Trigger DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configures the TIM in Slave mode in interrupt mode * @param htim TIM handle. * @param sSlaveConfig pointer to a TIM_SlaveConfigTypeDef structure that * contains the selected trigger (internal trigger input, filtered * timer input or external trigger input) and the Slave mode * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) { /* Check the parameters */ assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) { htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_ERROR; } /* Enable Trigger Interrupt */ __HAL_TIM_ENABLE_IT(htim, TIM_IT_TRIGGER); /* Disable Trigger DMA request */ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Read the captured value from Capture Compare unit * @param htim TIM handle. * @param Channel TIM Channels to be enabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @retval Captured value */ uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel) { uint32_t tmpreg = 0U; switch (Channel) { case TIM_CHANNEL_1: { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); /* Return the capture 1 value */ tmpreg = htim->Instance->CCR1; break; } case TIM_CHANNEL_2: { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); /* Return the capture 2 value */ tmpreg = htim->Instance->CCR2; break; } case TIM_CHANNEL_3: { /* Check the parameters */ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); /* Return the capture 3 value */ tmpreg = htim->Instance->CCR3; break; } case TIM_CHANNEL_4: { /* Check the parameters */ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); /* Return the capture 4 value */ tmpreg = htim->Instance->CCR4; break; } default: break; } return tmpreg; } /** * @} */ /** @defgroup TIM_Exported_Functions_Group9 TIM Callbacks functions * @brief TIM Callbacks functions * @verbatim ============================================================================== ##### TIM Callbacks functions ##### ============================================================================== [..] This section provides TIM callback functions: (+) TIM Period elapsed callback (+) TIM Output Compare callback (+) TIM Input capture callback (+) TIM Trigger callback (+) TIM Error callback (+) TIM Index callback (+) TIM Direction change callback (+) TIM Index error callback (+) TIM Transition error callback @endverbatim * @{ */ /** * @brief Period elapsed callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PeriodElapsedCallback could be implemented in the user file */ } /** * @brief Period elapsed half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_PeriodElapsedHalfCpltCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PeriodElapsedHalfCpltCallback could be implemented in the user file */ } /** * @brief Output Compare callback in non-blocking mode * @param htim TIM OC handle * @retval None */ __weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_OC_DelayElapsedCallback could be implemented in the user file */ } /** * @brief Input Capture callback in non-blocking mode * @param htim TIM IC handle * @retval None */ __weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_IC_CaptureCallback could be implemented in the user file */ } /** * @brief Input Capture half complete callback in non-blocking mode * @param htim TIM IC handle * @retval None */ __weak void HAL_TIM_IC_CaptureHalfCpltCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_IC_CaptureHalfCpltCallback could be implemented in the user file */ } /** * @brief PWM Pulse finished callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PWM_PulseFinishedCallback could be implemented in the user file */ } /** * @brief PWM Pulse finished half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_PWM_PulseFinishedHalfCpltCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_PWM_PulseFinishedHalfCpltCallback could be implemented in the user file */ } /** * @brief Hall Trigger detection callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_TriggerCallback could be implemented in the user file */ } /** * @brief Hall Trigger detection half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_TriggerHalfCpltCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_TriggerHalfCpltCallback could be implemented in the user file */ } /** * @brief Timer error callback in non-blocking mode * @param htim TIM handle * @retval None */ __weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim) { /* Prevent unused argument(s) compilation warning */ UNUSED(htim); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TIM_ErrorCallback could be implemented in the user file */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /** * @brief Register a User TIM callback to be used instead of the weak predefined callback * @param htim tim handle * @param CallbackID ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID * @param pCallback pointer to the callback function * @retval status */ HAL_StatusTypeDef HAL_TIM_RegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID, pTIM_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { return HAL_ERROR; } /* Process locked */ __HAL_LOCK(htim); if (htim->State == HAL_TIM_STATE_READY) { switch (CallbackID) { case HAL_TIM_BASE_MSPINIT_CB_ID : htim->Base_MspInitCallback = pCallback; break; case HAL_TIM_BASE_MSPDEINIT_CB_ID : htim->Base_MspDeInitCallback = pCallback; break; case HAL_TIM_IC_MSPINIT_CB_ID : htim->IC_MspInitCallback = pCallback; break; case HAL_TIM_IC_MSPDEINIT_CB_ID : htim->IC_MspDeInitCallback = pCallback; break; case HAL_TIM_OC_MSPINIT_CB_ID : htim->OC_MspInitCallback = pCallback; break; case HAL_TIM_OC_MSPDEINIT_CB_ID : htim->OC_MspDeInitCallback = pCallback; break; case HAL_TIM_PWM_MSPINIT_CB_ID : htim->PWM_MspInitCallback = pCallback; break; case HAL_TIM_PWM_MSPDEINIT_CB_ID : htim->PWM_MspDeInitCallback = pCallback; break; case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : htim->OnePulse_MspInitCallback = pCallback; break; case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : htim->OnePulse_MspDeInitCallback = pCallback; break; case HAL_TIM_ENCODER_MSPINIT_CB_ID : htim->Encoder_MspInitCallback = pCallback; break; case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : htim->Encoder_MspDeInitCallback = pCallback; break; case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : htim->HallSensor_MspInitCallback = pCallback; break; case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : htim->HallSensor_MspDeInitCallback = pCallback; break; case HAL_TIM_PERIOD_ELAPSED_CB_ID : htim->PeriodElapsedCallback = pCallback; break; case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : htim->PeriodElapsedHalfCpltCallback = pCallback; break; case HAL_TIM_TRIGGER_CB_ID : htim->TriggerCallback = pCallback; break; case HAL_TIM_TRIGGER_HALF_CB_ID : htim->TriggerHalfCpltCallback = pCallback; break; case HAL_TIM_IC_CAPTURE_CB_ID : htim->IC_CaptureCallback = pCallback; break; case HAL_TIM_IC_CAPTURE_HALF_CB_ID : htim->IC_CaptureHalfCpltCallback = pCallback; break; case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : htim->OC_DelayElapsedCallback = pCallback; break; case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : htim->PWM_PulseFinishedCallback = pCallback; break; case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : htim->PWM_PulseFinishedHalfCpltCallback = pCallback; break; case HAL_TIM_ERROR_CB_ID : htim->ErrorCallback = pCallback; break; case HAL_TIM_COMMUTATION_CB_ID : htim->CommutationCallback = pCallback; break; case HAL_TIM_COMMUTATION_HALF_CB_ID : htim->CommutationHalfCpltCallback = pCallback; break; case HAL_TIM_BREAK_CB_ID : htim->BreakCallback = pCallback; break; case HAL_TIM_BREAK2_CB_ID : htim->Break2Callback = pCallback; break; case HAL_TIM_ENCODER_INDEX_CB_ID : htim->EncoderIndexCallback = pCallback; break; case HAL_TIM_DIRECTION_CHANGE_CB_ID : htim->DirectionChangeCallback = pCallback; break; case HAL_TIM_INDEX_ERROR_CB_ID : htim->IndexErrorCallback = pCallback; break; case HAL_TIM_TRANSITION_ERROR_CB_ID : htim->TransitionErrorCallback = pCallback; break; default : /* Return error status */ status = HAL_ERROR; break; } } else if (htim->State == HAL_TIM_STATE_RESET) { switch (CallbackID) { case HAL_TIM_BASE_MSPINIT_CB_ID : htim->Base_MspInitCallback = pCallback; break; case HAL_TIM_BASE_MSPDEINIT_CB_ID : htim->Base_MspDeInitCallback = pCallback; break; case HAL_TIM_IC_MSPINIT_CB_ID : htim->IC_MspInitCallback = pCallback; break; case HAL_TIM_IC_MSPDEINIT_CB_ID : htim->IC_MspDeInitCallback = pCallback; break; case HAL_TIM_OC_MSPINIT_CB_ID : htim->OC_MspInitCallback = pCallback; break; case HAL_TIM_OC_MSPDEINIT_CB_ID : htim->OC_MspDeInitCallback = pCallback; break; case HAL_TIM_PWM_MSPINIT_CB_ID : htim->PWM_MspInitCallback = pCallback; break; case HAL_TIM_PWM_MSPDEINIT_CB_ID : htim->PWM_MspDeInitCallback = pCallback; break; case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : htim->OnePulse_MspInitCallback = pCallback; break; case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : htim->OnePulse_MspDeInitCallback = pCallback; break; case HAL_TIM_ENCODER_MSPINIT_CB_ID : htim->Encoder_MspInitCallback = pCallback; break; case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : htim->Encoder_MspDeInitCallback = pCallback; break; case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : htim->HallSensor_MspInitCallback = pCallback; break; case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : htim->HallSensor_MspDeInitCallback = pCallback; break; default : /* Return error status */ status = HAL_ERROR; break; } } else { /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(htim); return status; } /** * @brief Unregister a TIM callback * TIM callback is redirected to the weak predefined callback * @param htim tim handle * @param CallbackID ID of the callback to be unregistered * This parameter can be one of the following values: * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID * @retval status */ HAL_StatusTypeDef HAL_TIM_UnRegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(htim); if (htim->State == HAL_TIM_STATE_READY) { switch (CallbackID) { case HAL_TIM_BASE_MSPINIT_CB_ID : /* Legacy weak Base MspInit Callback */ htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; break; case HAL_TIM_BASE_MSPDEINIT_CB_ID : /* Legacy weak Base Msp DeInit Callback */ htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; break; case HAL_TIM_IC_MSPINIT_CB_ID : /* Legacy weak IC Msp Init Callback */ htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; break; case HAL_TIM_IC_MSPDEINIT_CB_ID : /* Legacy weak IC Msp DeInit Callback */ htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; break; case HAL_TIM_OC_MSPINIT_CB_ID : /* Legacy weak OC Msp Init Callback */ htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; break; case HAL_TIM_OC_MSPDEINIT_CB_ID : /* Legacy weak OC Msp DeInit Callback */ htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; break; case HAL_TIM_PWM_MSPINIT_CB_ID : /* Legacy weak PWM Msp Init Callback */ htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; break; case HAL_TIM_PWM_MSPDEINIT_CB_ID : /* Legacy weak PWM Msp DeInit Callback */ htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; break; case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : /* Legacy weak One Pulse Msp Init Callback */ htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; break; case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : /* Legacy weak One Pulse Msp DeInit Callback */ htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; break; case HAL_TIM_ENCODER_MSPINIT_CB_ID : /* Legacy weak Encoder Msp Init Callback */ htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; break; case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : /* Legacy weak Encoder Msp DeInit Callback */ htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; break; case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : /* Legacy weak Hall Sensor Msp Init Callback */ htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; break; case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : /* Legacy weak Hall Sensor Msp DeInit Callback */ htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; break; case HAL_TIM_PERIOD_ELAPSED_CB_ID : /* Legacy weak Period Elapsed Callback */ htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; break; case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : /* Legacy weak Period Elapsed half complete Callback */ htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; break; case HAL_TIM_TRIGGER_CB_ID : /* Legacy weak Trigger Callback */ htim->TriggerCallback = HAL_TIM_TriggerCallback; break; case HAL_TIM_TRIGGER_HALF_CB_ID : /* Legacy weak Trigger half complete Callback */ htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; break; case HAL_TIM_IC_CAPTURE_CB_ID : /* Legacy weak IC Capture Callback */ htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; break; case HAL_TIM_IC_CAPTURE_HALF_CB_ID : /* Legacy weak IC Capture half complete Callback */ htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; break; case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : /* Legacy weak OC Delay Elapsed Callback */ htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; break; case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : /* Legacy weak PWM Pulse Finished Callback */ htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; break; case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : /* Legacy weak PWM Pulse Finished half complete Callback */ htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; break; case HAL_TIM_ERROR_CB_ID : /* Legacy weak Error Callback */ htim->ErrorCallback = HAL_TIM_ErrorCallback; break; case HAL_TIM_COMMUTATION_CB_ID : /* Legacy weak Commutation Callback */ htim->CommutationCallback = HAL_TIMEx_CommutCallback; break; case HAL_TIM_COMMUTATION_HALF_CB_ID : /* Legacy weak Commutation half complete Callback */ htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; break; case HAL_TIM_BREAK_CB_ID : /* Legacy weak Break Callback */ htim->BreakCallback = HAL_TIMEx_BreakCallback; break; case HAL_TIM_BREAK2_CB_ID : /* Legacy weak Break2 Callback */ htim->Break2Callback = HAL_TIMEx_Break2Callback; break; case HAL_TIM_ENCODER_INDEX_CB_ID : /* Legacy weak Encoder Index Callback */ htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; break; case HAL_TIM_DIRECTION_CHANGE_CB_ID : /* Legacy weak Direction Change Callback */ htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; break; case HAL_TIM_INDEX_ERROR_CB_ID : /* Legacy weak Index Error Callback */ htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; break; case HAL_TIM_TRANSITION_ERROR_CB_ID : /* Legacy weak Transition Error Callback */ htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; break; default : /* Return error status */ status = HAL_ERROR; break; } } else if (htim->State == HAL_TIM_STATE_RESET) { switch (CallbackID) { case HAL_TIM_BASE_MSPINIT_CB_ID : /* Legacy weak Base MspInit Callback */ htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; break; case HAL_TIM_BASE_MSPDEINIT_CB_ID : /* Legacy weak Base Msp DeInit Callback */ htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; break; case HAL_TIM_IC_MSPINIT_CB_ID : /* Legacy weak IC Msp Init Callback */ htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; break; case HAL_TIM_IC_MSPDEINIT_CB_ID : /* Legacy weak IC Msp DeInit Callback */ htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; break; case HAL_TIM_OC_MSPINIT_CB_ID : /* Legacy weak OC Msp Init Callback */ htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; break; case HAL_TIM_OC_MSPDEINIT_CB_ID : /* Legacy weak OC Msp DeInit Callback */ htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; break; case HAL_TIM_PWM_MSPINIT_CB_ID : /* Legacy weak PWM Msp Init Callback */ htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; break; case HAL_TIM_PWM_MSPDEINIT_CB_ID : /* Legacy weak PWM Msp DeInit Callback */ htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; break; case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : /* Legacy weak One Pulse Msp Init Callback */ htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; break; case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : /* Legacy weak One Pulse Msp DeInit Callback */ htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; break; case HAL_TIM_ENCODER_MSPINIT_CB_ID : /* Legacy weak Encoder Msp Init Callback */ htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; break; case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : /* Legacy weak Encoder Msp DeInit Callback */ htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; break; case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : /* Legacy weak Hall Sensor Msp Init Callback */ htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; break; case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : /* Legacy weak Hall Sensor Msp DeInit Callback */ htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; break; default : /* Return error status */ status = HAL_ERROR; break; } } else { /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(htim); return status; } #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup TIM_Exported_Functions_Group10 TIM Peripheral State functions * @brief TIM Peripheral State functions * @verbatim ============================================================================== ##### Peripheral State functions ##### ============================================================================== [..] This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim * @{ */ /** * @brief Return the TIM Base handle state. * @param htim TIM Base handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM OC handle state. * @param htim TIM Output Compare handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM PWM handle state. * @param htim TIM handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM Input Capture handle state. * @param htim TIM IC handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM One Pulse Mode handle state. * @param htim TIM OPM handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM Encoder Mode handle state. * @param htim TIM Encoder Interface handle * @retval HAL state */ HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim) { return htim->State; } /** * @brief Return the TIM Encoder Mode handle state. * @param htim TIM handle * @retval Active channel */ HAL_TIM_ActiveChannel HAL_TIM_GetActiveChannel(TIM_HandleTypeDef *htim) { return htim->Channel; } /** * @brief Return actual state of the TIM channel. * @param htim TIM handle * @param Channel TIM Channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 * @arg TIM_CHANNEL_2: TIM Channel 2 * @arg TIM_CHANNEL_3: TIM Channel 3 * @arg TIM_CHANNEL_4: TIM Channel 4 * @arg TIM_CHANNEL_5: TIM Channel 5 * @arg TIM_CHANNEL_6: TIM Channel 6 * @retval TIM Channel state */ HAL_TIM_ChannelStateTypeDef HAL_TIM_GetChannelState(TIM_HandleTypeDef *htim, uint32_t Channel) { HAL_TIM_ChannelStateTypeDef channel_state; /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); return channel_state; } /** * @brief Return actual state of a DMA burst operation. * @param htim TIM handle * @retval DMA burst state */ HAL_TIM_DMABurstStateTypeDef HAL_TIM_DMABurstState(TIM_HandleTypeDef *htim) { /* Check the parameters */ assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); return htim->DMABurstState; } /** * @} */ /** * @} */ /** @defgroup TIM_Private_Functions TIM Private Functions * @{ */ /** * @brief TIM DMA error callback * @param hdma pointer to DMA handle. * @retval None */ void TIM_DMAError(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); } else { htim->State = HAL_TIM_STATE_READY; } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->ErrorCallback(htim); #else HAL_TIM_ErrorCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA Delay Pulse complete callback. * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); } } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PWM_PulseFinishedCallback(htim); #else HAL_TIM_PWM_PulseFinishedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA Delay Pulse half complete callback. * @param hdma pointer to DMA handle. * @retval None */ void TIM_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PWM_PulseFinishedHalfCpltCallback(htim); #else HAL_TIM_PWM_PulseFinishedHalfCpltCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA Capture complete callback. * @param hdma pointer to DMA handle. * @retval None */ void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; if (hdma->Init.Mode == DMA_NORMAL) { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); } } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureCallback(htim); #else HAL_TIM_IC_CaptureCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA Capture half complete callback. * @param hdma pointer to DMA handle. * @retval None */ void TIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (hdma == htim->hdma[TIM_DMA_ID_CC1]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) { htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; } else { /* nothing to do */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->IC_CaptureHalfCpltCallback(htim); #else HAL_TIM_IC_CaptureHalfCpltCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; } /** * @brief TIM DMA Period Elapse complete callback. * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (htim->hdma[TIM_DMA_ID_UPDATE]->Init.Mode == DMA_NORMAL) { htim->State = HAL_TIM_STATE_READY; } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedCallback(htim); #else HAL_TIM_PeriodElapsedCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief TIM DMA Period Elapse half complete callback. * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedHalfCpltCallback(htim); #else HAL_TIM_PeriodElapsedHalfCpltCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief TIM DMA Trigger callback. * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; if (htim->hdma[TIM_DMA_ID_TRIGGER]->Init.Mode == DMA_NORMAL) { htim->State = HAL_TIM_STATE_READY; } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerCallback(htim); #else HAL_TIM_TriggerCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief TIM DMA Trigger half complete callback. * @param hdma pointer to DMA handle. * @retval None */ static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma) { TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerHalfCpltCallback(htim); #else HAL_TIM_TriggerHalfCpltCallback(htim); #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ } /** * @brief Time Base configuration * @param TIMx TIM peripheral * @param Structure TIM Base configuration structure * @retval None */ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) { uint32_t tmpcr1; tmpcr1 = TIMx->CR1; /* Set TIM Time Base Unit parameters ---------------------------------------*/ if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) { /* Select the Counter Mode */ tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS); tmpcr1 |= Structure->CounterMode; } if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) { /* Set the clock division */ tmpcr1 &= ~TIM_CR1_CKD; tmpcr1 |= (uint32_t)Structure->ClockDivision; } /* Set the auto-reload preload */ MODIFY_REG(tmpcr1, TIM_CR1_ARPE, Structure->AutoReloadPreload); TIMx->CR1 = tmpcr1; /* Set the Autoreload value */ TIMx->ARR = (uint32_t)Structure->Period ; /* Set the Prescaler value */ TIMx->PSC = Structure->Prescaler; if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) { /* Set the Repetition Counter value */ TIMx->RCR = Structure->RepetitionCounter; } /* Generate an update event to reload the Prescaler and the repetition counter (only for advanced timer) value immediately */ TIMx->EGR = TIM_EGR_UG; } /** * @brief Timer Output Compare 1 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= ~TIM_CCER_CC1E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR1 register value */ tmpccmrx = TIMx->CCMR1; /* Reset the Output Compare Mode Bits */ tmpccmrx &= ~TIM_CCMR1_OC1M; tmpccmrx &= ~TIM_CCMR1_CC1S; /* Select the Output Compare Mode */ tmpccmrx |= OC_Config->OCMode; /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC1P; /* Set the Output Compare Polarity */ tmpccer |= OC_Config->OCPolarity; if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1)) { /* Check parameters */ assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC1NP; /* Set the Output N Polarity */ tmpccer |= OC_Config->OCNPolarity; /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC1NE; } if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Check parameters */ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); /* Reset the Output Compare and Output Compare N IDLE State */ tmpcr2 &= ~TIM_CR2_OIS1; tmpcr2 &= ~TIM_CR2_OIS1N; /* Set the Output Idle state */ tmpcr2 |= OC_Config->OCIdleState; /* Set the Output N Idle state */ tmpcr2 |= OC_Config->OCNIdleState; } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR1 */ TIMx->CCMR1 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR1 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Timer Output Compare 2 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR1 register value */ tmpccmrx = TIMx->CCMR1; /* Reset the Output Compare mode and Capture/Compare selection Bits */ tmpccmrx &= ~TIM_CCMR1_OC2M; tmpccmrx &= ~TIM_CCMR1_CC2S; /* Select the Output Compare Mode */ tmpccmrx |= (OC_Config->OCMode << 8U); /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC2P; /* Set the Output Compare Polarity */ tmpccer |= (OC_Config->OCPolarity << 4U); if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) { assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC2NP; /* Set the Output N Polarity */ tmpccer |= (OC_Config->OCNPolarity << 4U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC2NE; } if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Check parameters */ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); /* Reset the Output Compare and Output Compare N IDLE State */ tmpcr2 &= ~TIM_CR2_OIS2; tmpcr2 &= ~TIM_CR2_OIS2N; /* Set the Output Idle state */ tmpcr2 |= (OC_Config->OCIdleState << 2U); /* Set the Output N Idle state */ tmpcr2 |= (OC_Config->OCNIdleState << 2U); } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR1 */ TIMx->CCMR1 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR2 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Timer Output Compare 3 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the Channel 3: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC3E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR2 register value */ tmpccmrx = TIMx->CCMR2; /* Reset the Output Compare mode and Capture/Compare selection Bits */ tmpccmrx &= ~TIM_CCMR2_OC3M; tmpccmrx &= ~TIM_CCMR2_CC3S; /* Select the Output Compare Mode */ tmpccmrx |= OC_Config->OCMode; /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC3P; /* Set the Output Compare Polarity */ tmpccer |= (OC_Config->OCPolarity << 8U); if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) { assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC3NP; /* Set the Output N Polarity */ tmpccer |= (OC_Config->OCNPolarity << 8U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC3NE; } if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Check parameters */ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); /* Reset the Output Compare and Output Compare N IDLE State */ tmpcr2 &= ~TIM_CR2_OIS3; tmpcr2 &= ~TIM_CR2_OIS3N; /* Set the Output Idle state */ tmpcr2 |= (OC_Config->OCIdleState << 4U); /* Set the Output N Idle state */ tmpcr2 |= (OC_Config->OCNIdleState << 4U); } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR2 */ TIMx->CCMR2 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR3 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Timer Output Compare 4 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= ~TIM_CCER_CC4E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR2 register value */ tmpccmrx = TIMx->CCMR2; /* Reset the Output Compare mode and Capture/Compare selection Bits */ tmpccmrx &= ~TIM_CCMR2_OC4M; tmpccmrx &= ~TIM_CCMR2_CC4S; /* Select the Output Compare Mode */ tmpccmrx |= (OC_Config->OCMode << 8U); /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC4P; /* Set the Output Compare Polarity */ tmpccer |= (OC_Config->OCPolarity << 12U); if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_4)) { assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC4NP; /* Set the Output N Polarity */ tmpccer |= (OC_Config->OCNPolarity << 12U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC4NE; } if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Check parameters */ assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); /* Reset the Output Compare IDLE State */ tmpcr2 &= ~TIM_CR2_OIS4; /* Reset the Output Compare N IDLE State */ tmpcr2 &= ~TIM_CR2_OIS4N; /* Set the Output Idle state */ tmpcr2 |= (OC_Config->OCIdleState << 6U); /* Set the Output N Idle state */ tmpcr2 |= (OC_Config->OCNIdleState << 6U); } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR2 */ TIMx->CCMR2 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR4 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Timer Output Compare 5 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the output: Reset the CCxE Bit */ TIMx->CCER &= ~TIM_CCER_CC5E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR1 register value */ tmpccmrx = TIMx->CCMR3; /* Reset the Output Compare Mode Bits */ tmpccmrx &= ~(TIM_CCMR3_OC5M); /* Select the Output Compare Mode */ tmpccmrx |= OC_Config->OCMode; /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC5P; /* Set the Output Compare Polarity */ tmpccer |= (OC_Config->OCPolarity << 16U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Reset the Output Compare IDLE State */ tmpcr2 &= ~TIM_CR2_OIS5; /* Set the Output Idle state */ tmpcr2 |= (OC_Config->OCIdleState << 8U); } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR3 */ TIMx->CCMR3 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR5 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Timer Output Compare 6 configuration * @param TIMx to select the TIM peripheral * @param OC_Config The output configuration structure * @retval None */ static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { uint32_t tmpccmrx; uint32_t tmpccer; uint32_t tmpcr2; /* Disable the output: Reset the CCxE Bit */ TIMx->CCER &= ~TIM_CCER_CC6E; /* Get the TIMx CCER register value */ tmpccer = TIMx->CCER; /* Get the TIMx CR2 register value */ tmpcr2 = TIMx->CR2; /* Get the TIMx CCMR1 register value */ tmpccmrx = TIMx->CCMR3; /* Reset the Output Compare Mode Bits */ tmpccmrx &= ~(TIM_CCMR3_OC6M); /* Select the Output Compare Mode */ tmpccmrx |= (OC_Config->OCMode << 8U); /* Reset the Output Polarity level */ tmpccer &= (uint32_t)~TIM_CCER_CC6P; /* Set the Output Compare Polarity */ tmpccer |= (OC_Config->OCPolarity << 20U); if (IS_TIM_BREAK_INSTANCE(TIMx)) { /* Reset the Output Compare IDLE State */ tmpcr2 &= ~TIM_CR2_OIS6; /* Set the Output Idle state */ tmpcr2 |= (OC_Config->OCIdleState << 10U); } /* Write to TIMx CR2 */ TIMx->CR2 = tmpcr2; /* Write to TIMx CCMR3 */ TIMx->CCMR3 = tmpccmrx; /* Set the Capture Compare Register value */ TIMx->CCR6 = OC_Config->Pulse; /* Write to TIMx CCER */ TIMx->CCER = tmpccer; } /** * @brief Slave Timer configuration function * @param htim TIM handle * @param sSlaveConfig Slave timer configuration * @retval None */ static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) { HAL_StatusTypeDef status = HAL_OK; uint32_t tmpsmcr; uint32_t tmpccmr1; uint32_t tmpccer; /* Get the TIMx SMCR register value */ tmpsmcr = htim->Instance->SMCR; /* Reset the Trigger Selection Bits */ tmpsmcr &= ~TIM_SMCR_TS; /* Set the Input Trigger source */ tmpsmcr |= sSlaveConfig->InputTrigger; /* Reset the slave mode Bits */ tmpsmcr &= ~TIM_SMCR_SMS; /* Set the slave mode */ tmpsmcr |= sSlaveConfig->SlaveMode; /* Write to TIMx SMCR */ htim->Instance->SMCR = tmpsmcr; /* Configure the trigger prescaler, filter, and polarity */ switch (sSlaveConfig->InputTrigger) { case TIM_TS_ETRF: { /* Check the parameters */ assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler)); assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); /* Configure the ETR Trigger source */ TIM_ETR_SetConfig(htim->Instance, sSlaveConfig->TriggerPrescaler, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter); break; } case TIM_TS_TI1F_ED: { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); if ((sSlaveConfig->SlaveMode == TIM_SLAVEMODE_GATED) || \ (sSlaveConfig->SlaveMode == TIM_SLAVEMODE_COMBINED_GATEDRESET)) { return HAL_ERROR; } /* Disable the Channel 1: Reset the CC1E Bit */ tmpccer = htim->Instance->CCER; htim->Instance->CCER &= ~TIM_CCER_CC1E; tmpccmr1 = htim->Instance->CCMR1; /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4U); /* Write to TIMx CCMR1 and CCER registers */ htim->Instance->CCMR1 = tmpccmr1; htim->Instance->CCER = tmpccer; break; } case TIM_TS_TI1FP1: { /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); /* Configure TI1 Filter and Polarity */ TIM_TI1_ConfigInputStage(htim->Instance, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter); break; } case TIM_TS_TI2FP2: { /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); /* Configure TI2 Filter and Polarity */ TIM_TI2_ConfigInputStage(htim->Instance, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter); break; } case TIM_TS_ITR0: case TIM_TS_ITR1: case TIM_TS_ITR2: case TIM_TS_ITR3: #if defined (TIM5) case TIM_TS_ITR4: #endif /* TIM5 */ case TIM_TS_ITR5: case TIM_TS_ITR6: case TIM_TS_ITR7: case TIM_TS_ITR8: #if defined (TIM20) case TIM_TS_ITR9: #endif /* TIM20 */ #if defined (HRTIM1) case TIM_TS_ITR10: #endif /* HRTIM1 */ case TIM_TS_ITR11: { /* Check the parameter */ assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE((htim->Instance), sSlaveConfig->InputTrigger)); break; } default: status = HAL_ERROR; break; } return status; } /** * @brief Configure the TI1 as Input. * @param TIMx to select the TIM peripheral. * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 1 is selected to be connected to IC1. * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 1 is selected to be connected to IC2. * @arg TIM_ICSELECTION_TRC: TIM Input 1 is selected to be connected to TRC. * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI2FP1 * (on channel2 path) is used as the input signal. Therefore CCMR1 must be * protected against un-initialized filter and polarity values. */ void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { uint32_t tmpccmr1; uint32_t tmpccer; /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= ~TIM_CCER_CC1E; tmpccmr1 = TIMx->CCMR1; tmpccer = TIMx->CCER; /* Select the Input */ if (IS_TIM_CC2_INSTANCE(TIMx) != RESET) { tmpccmr1 &= ~TIM_CCMR1_CC1S; tmpccmr1 |= TIM_ICSelection; } else { tmpccmr1 |= TIM_CCMR1_CC1S_0; } /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; tmpccmr1 |= ((TIM_ICFilter << 4U) & TIM_CCMR1_IC1F); /* Select the Polarity and set the CC1E Bit */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); tmpccer |= (TIM_ICPolarity & (TIM_CCER_CC1P | TIM_CCER_CC1NP)); /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1; TIMx->CCER = tmpccer; } /** * @brief Configure the Polarity and Filter for TI1. * @param TIMx to select the TIM peripheral. * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) { uint32_t tmpccmr1; uint32_t tmpccer; /* Disable the Channel 1: Reset the CC1E Bit */ tmpccer = TIMx->CCER; TIMx->CCER &= ~TIM_CCER_CC1E; tmpccmr1 = TIMx->CCMR1; /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; tmpccmr1 |= (TIM_ICFilter << 4U); /* Select the Polarity and set the CC1E Bit */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); tmpccer |= TIM_ICPolarity; /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1; TIMx->CCER = tmpccer; } /** * @brief Configure the TI2 as Input. * @param TIMx to select the TIM peripheral * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 2 is selected to be connected to IC2. * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 2 is selected to be connected to IC1. * @arg TIM_ICSELECTION_TRC: TIM Input 2 is selected to be connected to TRC. * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI1FP2 * (on channel1 path) is used as the input signal. Therefore CCMR1 must be * protected against un-initialized filter and polarity values. */ static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { uint32_t tmpccmr1; uint32_t tmpccer; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; tmpccmr1 = TIMx->CCMR1; tmpccer = TIMx->CCER; /* Select the Input */ tmpccmr1 &= ~TIM_CCMR1_CC2S; tmpccmr1 |= (TIM_ICSelection << 8U); /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC2F; tmpccmr1 |= ((TIM_ICFilter << 12U) & TIM_CCMR1_IC2F); /* Select the Polarity and set the CC2E Bit */ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= ((TIM_ICPolarity << 4U) & (TIM_CCER_CC2P | TIM_CCER_CC2NP)); /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1 ; TIMx->CCER = tmpccer; } /** * @brief Configure the Polarity and Filter for TI2. * @param TIMx to select the TIM peripheral. * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) { uint32_t tmpccmr1; uint32_t tmpccer; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; tmpccmr1 = TIMx->CCMR1; tmpccer = TIMx->CCER; /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC2F; tmpccmr1 |= (TIM_ICFilter << 12U); /* Select the Polarity and set the CC2E Bit */ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); tmpccer |= (TIM_ICPolarity << 4U); /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1 ; TIMx->CCER = tmpccer; } /** * @brief Configure the TI3 as Input. * @param TIMx to select the TIM peripheral * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 3 is selected to be connected to IC3. * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 3 is selected to be connected to IC4. * @arg TIM_ICSELECTION_TRC: TIM Input 3 is selected to be connected to TRC. * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI3FP4 * (on channel1 path) is used as the input signal. Therefore CCMR2 must be * protected against un-initialized filter and polarity values. */ static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { uint32_t tmpccmr2; uint32_t tmpccer; /* Disable the Channel 3: Reset the CC3E Bit */ TIMx->CCER &= ~TIM_CCER_CC3E; tmpccmr2 = TIMx->CCMR2; tmpccer = TIMx->CCER; /* Select the Input */ tmpccmr2 &= ~TIM_CCMR2_CC3S; tmpccmr2 |= TIM_ICSelection; /* Set the filter */ tmpccmr2 &= ~TIM_CCMR2_IC3F; tmpccmr2 |= ((TIM_ICFilter << 4U) & TIM_CCMR2_IC3F); /* Select the Polarity and set the CC3E Bit */ tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP); tmpccer |= ((TIM_ICPolarity << 8U) & (TIM_CCER_CC3P | TIM_CCER_CC3NP)); /* Write to TIMx CCMR2 and CCER registers */ TIMx->CCMR2 = tmpccmr2; TIMx->CCER = tmpccer; } /** * @brief Configure the TI4 as Input. * @param TIMx to select the TIM peripheral * @param TIM_ICPolarity The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 4 is selected to be connected to IC4. * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 4 is selected to be connected to IC3. * @arg TIM_ICSELECTION_TRC: TIM Input 4 is selected to be connected to TRC. * @param TIM_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI4FP3 * (on channel1 path) is used as the input signal. Therefore CCMR2 must be * protected against un-initialized filter and polarity values. * @retval None */ static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { uint32_t tmpccmr2; uint32_t tmpccer; /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= ~TIM_CCER_CC4E; tmpccmr2 = TIMx->CCMR2; tmpccer = TIMx->CCER; /* Select the Input */ tmpccmr2 &= ~TIM_CCMR2_CC4S; tmpccmr2 |= (TIM_ICSelection << 8U); /* Set the filter */ tmpccmr2 &= ~TIM_CCMR2_IC4F; tmpccmr2 |= ((TIM_ICFilter << 12U) & TIM_CCMR2_IC4F); /* Select the Polarity and set the CC4E Bit */ tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP); tmpccer |= ((TIM_ICPolarity << 12U) & (TIM_CCER_CC4P | TIM_CCER_CC4NP)); /* Write to TIMx CCMR2 and CCER registers */ TIMx->CCMR2 = tmpccmr2; TIMx->CCER = tmpccer ; } /** * @brief Selects the Input Trigger source * @param TIMx to select the TIM peripheral * @param InputTriggerSource The Input Trigger source. * This parameter can be one of the following values: * @arg TIM_TS_ITR0: Internal Trigger 0 * @arg TIM_TS_ITR1: Internal Trigger 1 * @arg TIM_TS_ITR2: Internal Trigger 2 * @arg TIM_TS_ITR3: Internal Trigger 3 * @arg TIM_TS_TI1F_ED: TI1 Edge Detector * @arg TIM_TS_TI1FP1: Filtered Timer Input 1 * @arg TIM_TS_TI2FP2: Filtered Timer Input 2 * @arg TIM_TS_ETRF: External Trigger input * @arg TIM_TS_ITR4: Internal Trigger 4 (*) * @arg TIM_TS_ITR5: Internal Trigger 5 * @arg TIM_TS_ITR6: Internal Trigger 6 * @arg TIM_TS_ITR7: Internal Trigger 7 * @arg TIM_TS_ITR8: Internal Trigger 8 * @arg TIM_TS_ITR9: Internal Trigger 9 (*) * @arg TIM_TS_ITR10: Internal Trigger 10 * @arg TIM_TS_ITR11: Internal Trigger 11 * * (*) Value not defined in all devices. * * @retval None */ static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint32_t InputTriggerSource) { uint32_t tmpsmcr; /* Get the TIMx SMCR register value */ tmpsmcr = TIMx->SMCR; /* Reset the TS Bits */ tmpsmcr &= ~TIM_SMCR_TS; /* Set the Input Trigger source and the slave mode*/ tmpsmcr |= (InputTriggerSource | TIM_SLAVEMODE_EXTERNAL1); /* Write to TIMx SMCR */ TIMx->SMCR = tmpsmcr; } /** * @brief Configures the TIMx External Trigger (ETR). * @param TIMx to select the TIM peripheral * @param TIM_ExtTRGPrescaler The external Trigger Prescaler. * This parameter can be one of the following values: * @arg TIM_ETRPRESCALER_DIV1: ETRP Prescaler OFF. * @arg TIM_ETRPRESCALER_DIV2: ETRP frequency divided by 2. * @arg TIM_ETRPRESCALER_DIV4: ETRP frequency divided by 4. * @arg TIM_ETRPRESCALER_DIV8: ETRP frequency divided by 8. * @param TIM_ExtTRGPolarity The external Trigger Polarity. * This parameter can be one of the following values: * @arg TIM_ETRPOLARITY_INVERTED: active low or falling edge active. * @arg TIM_ETRPOLARITY_NONINVERTED: active high or rising edge active. * @param ExtTRGFilter External Trigger Filter. * This parameter must be a value between 0x00 and 0x0F * @retval None */ void TIM_ETR_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ExtTRGPrescaler, uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) { uint32_t tmpsmcr; tmpsmcr = TIMx->SMCR; /* Reset the ETR Bits */ tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); /* Set the Prescaler, the Filter value and the Polarity */ tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8U))); /* Write to TIMx SMCR */ TIMx->SMCR = tmpsmcr; } /** * @brief Enables or disables the TIM Capture Compare Channel x. * @param TIMx to select the TIM peripheral * @param Channel specifies the TIM Channel * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 * @arg TIM_CHANNEL_2: TIM Channel 2 * @arg TIM_CHANNEL_3: TIM Channel 3 * @arg TIM_CHANNEL_4: TIM Channel 4 * @arg TIM_CHANNEL_5: TIM Channel 5 selected * @arg TIM_CHANNEL_6: TIM Channel 6 selected * @param ChannelState specifies the TIM Channel CCxE bit new state. * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_DISABLE. * @retval None */ void TIM_CCxChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelState) { uint32_t tmp; /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); assert_param(IS_TIM_CHANNELS(Channel)); tmp = TIM_CCER_CC1E << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ /* Reset the CCxE Bit */ TIMx->CCER &= ~tmp; /* Set or reset the CCxE Bit */ TIMx->CCER |= (uint32_t)(ChannelState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ } #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) /** * @brief Reset interrupt callbacks to the legacy weak callbacks. * @param htim pointer to a TIM_HandleTypeDef structure that contains * the configuration information for TIM module. * @retval None */ void TIM_ResetCallback(TIM_HandleTypeDef *htim) { /* Reset the TIM callback to the legacy weak callbacks */ htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; htim->TriggerCallback = HAL_TIM_TriggerCallback; htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; htim->ErrorCallback = HAL_TIM_ErrorCallback; htim->CommutationCallback = HAL_TIMEx_CommutCallback; htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; htim->BreakCallback = HAL_TIMEx_BreakCallback; htim->Break2Callback = HAL_TIMEx_Break2Callback; htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; } #endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ /** * @} */ #endif /* HAL_TIM_MODULE_ENABLED */ /** * @} */ /** * @} */
259,599
C
31.013812
119
0.627472
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_hal.c
/** ****************************************************************************** * @file stm32g4xx_hal.c * @author MCD Application Team * @brief HAL module driver. * This is the common part of the HAL initialization ****************************************************************************** * @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 common HAL driver contains a set of generic and common APIs that can be used by the PPP peripheral drivers and the user to start using the HAL. [..] The HAL contains two APIs' categories: (+) Common HAL APIs (+) Services HAL APIs @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup HAL HAL * @brief HAL module driver * @{ */ #ifdef HAL_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** * @brief STM32G4xx HAL Driver version number V1.2.2 */ #define __STM32G4xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32G4xx_HAL_VERSION_SUB1 (0x02U) /*!< [23:16] sub1 version */ #define __STM32G4xx_HAL_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ #define __STM32G4xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32G4xx_HAL_VERSION ((__STM32G4xx_HAL_VERSION_MAIN << 24U)\ |(__STM32G4xx_HAL_VERSION_SUB1 << 16U)\ |(__STM32G4xx_HAL_VERSION_SUB2 << 8U )\ |(__STM32G4xx_HAL_VERSION_RC)) #if defined(VREFBUF) #define VREFBUF_TIMEOUT_VALUE 10U /* 10 ms */ #endif /* VREFBUF */ /* ------------ SYSCFG registers bit address in the alias region ------------ */ #define SYSCFG_OFFSET (SYSCFG_BASE - PERIPH_BASE) /* --- MEMRMP Register ---*/ /* Alias word address of FB_MODE bit */ #define MEMRMP_OFFSET SYSCFG_OFFSET #define FB_MODE_BitNumber ((uint8_t)0x8) #define FB_MODE_BB (PERIPH_BB_BASE + (MEMRMP_OFFSET * 32) + (FB_MODE_BitNumber * 4)) /* --- GPC Register ---*/ /* Alias word address of CCMER bit */ #define SCSR_OFFSET (SYSCFG_OFFSET + 0x18) #define CCMER_BitNumber ((uint8_t)0x0) #define SCSR_CCMER_BB (PERIPH_BB_BASE + (SCSR_OFFSET * 32) + (CCMER_BitNumber * 4)) /* Private macro -------------------------------------------------------------*/ /* Exported variables ---------------------------------------------------------*/ /** @defgroup HAL_Exported_Variables HAL Exported Variables * @{ */ __IO uint32_t uwTick; uint32_t uwTickPrio = (1UL << __NVIC_PRIO_BITS); /* Invalid PRIO */ uint32_t uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup HAL_Exported_Functions HAL Exported Functions * @{ */ /** @defgroup HAL_Exported_Functions_Group1 Initialization and de-initialization Functions * @brief HAL Initialization and de-initialization functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Initialize the Flash interface the NVIC allocation and initial time base clock configuration. (+) De-Initialize common part of the HAL. (+) Configure the time base source to have 1ms time base with a dedicated Tick interrupt priority. (++) SysTick timer is used by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis. (++) Time base configuration function (HAL_InitTick ()) is called automatically at the beginning of the program after reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). (++) Source of time base is configured to generate interrupts at regular time intervals. Care must be taken if HAL_Delay() is called from a peripheral ISR process, the Tick interrupt line must have higher priority (numerically lower) than the peripheral interrupt. Otherwise the caller ISR process will be blocked. (++) functions affecting time base configurations are declared as __weak to make override possible in case of other implementations in user file. @endverbatim * @{ */ /** * @brief This function is used to configure the Flash prefetch, the Instruction and Data caches, * the time base source, NVIC and any required global low level hardware * by calling the HAL_MspInit() callback function to be optionally defined in user file * stm32g4xx_hal_msp.c. * * @note HAL_Init() function is called at the beginning of program after reset and before * the clock configuration. * * @note In the default implementation the System Timer (Systick) is used as source of time base. * The Systick configuration is based on HSI clock, as HSI is the clock * used after a system Reset and the NVIC configuration is set to Priority group 4. * Once done, time base tick starts incrementing: the tick variable counter is incremented * each 1ms in the SysTick_Handler() interrupt handler. * * @retval HAL status */ HAL_StatusTypeDef HAL_Init(void) { HAL_StatusTypeDef status = HAL_OK; /* Configure Flash prefetch, Instruction cache, Data cache */ /* Default configuration at reset is: */ /* - Prefetch disabled */ /* - Instruction cache enabled */ /* - Data cache enabled */ #if (INSTRUCTION_CACHE_ENABLE == 0U) __HAL_FLASH_INSTRUCTION_CACHE_DISABLE(); #endif /* INSTRUCTION_CACHE_ENABLE */ #if (DATA_CACHE_ENABLE == 0U) __HAL_FLASH_DATA_CACHE_DISABLE(); #endif /* DATA_CACHE_ENABLE */ #if (PREFETCH_ENABLE != 0U) __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); #endif /* PREFETCH_ENABLE */ /* Set Interrupt Group Priority */ HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* Use SysTick as time base source and configure 1ms tick (default clock after Reset is HSI) */ if (HAL_InitTick(TICK_INT_PRIORITY) != HAL_OK) { status = HAL_ERROR; } else { /* Init the low level hardware */ HAL_MspInit(); } /* Return function status */ return status; } /** * @brief This function de-initializes common part of the HAL and stops the source of time base. * @note This function is optional. * @retval HAL status */ HAL_StatusTypeDef HAL_DeInit(void) { /* Reset of all peripherals */ __HAL_RCC_APB1_FORCE_RESET(); __HAL_RCC_APB1_RELEASE_RESET(); __HAL_RCC_APB2_FORCE_RESET(); __HAL_RCC_APB2_RELEASE_RESET(); __HAL_RCC_AHB1_FORCE_RESET(); __HAL_RCC_AHB1_RELEASE_RESET(); __HAL_RCC_AHB2_FORCE_RESET(); __HAL_RCC_AHB2_RELEASE_RESET(); __HAL_RCC_AHB3_FORCE_RESET(); __HAL_RCC_AHB3_RELEASE_RESET(); /* De-Init the low level hardware */ HAL_MspDeInit(); /* Return function status */ return HAL_OK; } /** * @brief Initialize the MSP. * @retval None */ __weak void HAL_MspInit(void) { /* NOTE : This function should not be modified, when the callback is needed, the HAL_MspInit could be implemented in the user file */ } /** * @brief DeInitializes the MSP. * @retval None */ __weak void HAL_MspDeInit(void) { /* NOTE : This function should not be modified, when the callback is needed, the HAL_MspDeInit could be implemented in the user file */ } /** * @brief This function configures the source of the time base: * The time source is configured to have 1ms time base with a dedicated * Tick interrupt priority. * @note This function is called automatically at the beginning of program after * reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig(). * @note In the default implementation, SysTick timer is the source of time base. * It is used to generate interrupts at regular time intervals. * Care must be taken if HAL_Delay() is called from a peripheral ISR process, * The SysTick interrupt must have higher priority (numerically lower) * than the peripheral interrupt. Otherwise the caller ISR process will be blocked. * The function is declared as __weak to be overwritten in case of other * implementation in user file. * @param TickPriority: Tick interrupt priority. * @retval HAL status */ __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { HAL_StatusTypeDef status = HAL_OK; if (uwTickFreq != 0U) { /* Configure the SysTick to have interrupt in 1ms time basis*/ if (HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) == 0U) { /* Configure the SysTick IRQ priority */ if (TickPriority < (1UL << __NVIC_PRIO_BITS)) { HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, 0U); uwTickPrio = TickPriority; } else { status = HAL_ERROR; } } else { status = HAL_ERROR; } } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @} */ /** @defgroup HAL_Exported_Functions_Group2 HAL Control functions * @brief HAL Control functions * @verbatim =============================================================================== ##### HAL Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Provide a tick value in millisecond (+) Provide a blocking delay in millisecond (+) Suspend the time base source interrupt (+) Resume the time base source interrupt (+) Get the HAL API driver version (+) Get the device identifier (+) Get the device revision identifier @endverbatim * @{ */ /** * @brief This function is called to increment a global variable "uwTick" * used as application time base. * @note In the default implementation, this variable is incremented each 1ms * in SysTick ISR. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval None */ __weak void HAL_IncTick(void) { uwTick += uwTickFreq; } /** * @brief Provides a tick value in millisecond. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval tick value */ __weak uint32_t HAL_GetTick(void) { return uwTick; } /** * @brief This function returns a tick priority. * @retval tick priority */ uint32_t HAL_GetTickPrio(void) { return uwTickPrio; } /** * @brief Set new tick Freq. * @retval status */ HAL_StatusTypeDef HAL_SetTickFreq(uint32_t Freq) { HAL_StatusTypeDef status = HAL_OK; uint32_t prevTickFreq; assert_param(IS_TICKFREQ(Freq)); if (uwTickFreq != Freq) { /* Back up uwTickFreq frequency */ prevTickFreq = uwTickFreq; /* Update uwTickFreq global variable used by HAL_InitTick() */ uwTickFreq = Freq; /* Apply the new tick Freq */ status = HAL_InitTick(uwTickPrio); if (status != HAL_OK) { /* Restore previous tick frequency */ uwTickFreq = prevTickFreq; } } return status; } /** * @brief Returns tick frequency. * @retval tick period in Hz */ uint32_t HAL_GetTickFreq(void) { return uwTickFreq; } /** * @brief This function provides minimum delay (in milliseconds) based * on variable incremented. * @note In the default implementation , SysTick timer is the source of time base. * It is used to generate interrupts at regular time intervals where uwTick * is incremented. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @param Delay specifies the delay time length, in milliseconds. * @retval None */ __weak void HAL_Delay(uint32_t Delay) { uint32_t tickstart = HAL_GetTick(); uint32_t wait = Delay; /* Add a freq to guarantee minimum wait */ if (wait < HAL_MAX_DELAY) { wait += (uint32_t)(uwTickFreq); } while ((HAL_GetTick() - tickstart) < wait) { } } /** * @brief Suspends Tick increment. * @note In the default implementation , SysTick timer is the source of time base. It is * used to generate interrupts at regular time intervals. Once HAL_SuspendTick() * is called, the SysTick interrupt will be disabled and so Tick increment * is suspended. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval None */ __weak void HAL_SuspendTick(void) { /* Disable SysTick Interrupt */ CLEAR_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); } /** * @brief Resume Tick increment. * @note In the default implementation , SysTick timer is the source of time base. It is * used to generate interrupts at regular time intervals. Once HAL_ResumeTick() * is called, the SysTick interrupt will be enabled and so Tick increment * is resumed. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval None */ __weak void HAL_ResumeTick(void) { /* Enable SysTick Interrupt */ SET_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); } /** * @brief Returns the HAL revision. * @retval version : 0xXYZR (8bits for each decimal, R for RC) */ uint32_t HAL_GetHalVersion(void) { return __STM32G4xx_HAL_VERSION; } /** * @brief Returns the device revision identifier. * @retval Device revision identifier */ uint32_t HAL_GetREVID(void) { return ((DBGMCU->IDCODE & DBGMCU_IDCODE_REV_ID) >> 16U); } /** * @brief Returns the device identifier. * @retval Device identifier */ uint32_t HAL_GetDEVID(void) { return (DBGMCU->IDCODE & DBGMCU_IDCODE_DEV_ID); } /** * @} */ /** @defgroup HAL_Exported_Functions_Group3 HAL Debug functions * @brief HAL Debug functions * @verbatim =============================================================================== ##### HAL Debug functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Enable/Disable Debug module during SLEEP mode (+) Enable/Disable Debug module during STOP0/STOP1/STOP2 modes (+) Enable/Disable Debug module during STANDBY mode @endverbatim * @{ */ /** * @brief Enable the Debug Module during SLEEP mode. * @retval None */ void HAL_DBGMCU_EnableDBGSleepMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP); } /** * @brief Disable the Debug Module during SLEEP mode. * @retval None */ void HAL_DBGMCU_DisableDBGSleepMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP); } /** * @brief Enable the Debug Module during STOP0/STOP1/STOP2 modes. * @retval None */ void HAL_DBGMCU_EnableDBGStopMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); } /** * @brief Disable the Debug Module during STOP0/STOP1/STOP2 modes. * @retval None */ void HAL_DBGMCU_DisableDBGStopMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); } /** * @brief Enable the Debug Module during STANDBY mode. * @retval None */ void HAL_DBGMCU_EnableDBGStandbyMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); } /** * @brief Disable the Debug Module during STANDBY mode. * @retval None */ void HAL_DBGMCU_DisableDBGStandbyMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); } /** * @} */ /** @defgroup HAL_Exported_Functions_Group4 HAL SYSCFG configuration functions * @brief HAL SYSCFG configuration functions * @verbatim =============================================================================== ##### HAL SYSCFG configuration functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Start a hardware CCMSRAM erase operation (+) Enable/Disable the Internal FLASH Bank Swapping (+) Configure the Voltage reference buffer (+) Enable/Disable the Voltage reference buffer (+) Enable/Disable the I/O analog switch voltage booster @endverbatim * @{ */ /** * @brief Start a hardware CCMSRAM erase operation. * @note As long as CCMSRAM is not erased the CCMER bit will be set. * This bit is automatically reset at the end of the CCMSRAM erase operation. * @retval None */ void HAL_SYSCFG_CCMSRAMErase(void) { /* unlock the write protection of the CCMER bit */ SYSCFG->SKR = 0xCA; SYSCFG->SKR = 0x53; /* Starts a hardware CCMSRAM erase operation*/ SET_BIT(SYSCFG->SCSR, SYSCFG_SCSR_CCMER); } /** * @brief Enable the Internal FLASH Bank Swapping. * * @note This function can be used only for STM32G4xx devices. * * @note Flash Bank2 mapped at 0x08000000 (and aliased @0x00000000) * and Flash Bank1 mapped at 0x08040000 (and aliased at 0x00040000) * * @retval None */ void HAL_SYSCFG_EnableMemorySwappingBank(void) { SET_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE); } /** * @brief Disable the Internal FLASH Bank Swapping. * * @note This function can be used only for STM32G4xx devices. * * @note The default state : Flash Bank1 mapped at 0x08000000 (and aliased @0x0000 0000) * and Flash Bank2 mapped at 0x08040000 (and aliased at 0x00040000) * * @retval None */ void HAL_SYSCFG_DisableMemorySwappingBank(void) { CLEAR_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE); } #if defined(VREFBUF) /** * @brief Configure the internal voltage reference buffer voltage scale. * @param VoltageScaling: specifies the output voltage to achieve * This parameter can be one of the following values: * @arg SYSCFG_VREFBUF_VOLTAGE_SCALE0: VREFBUF_OUT around 2.048 V. * This requires VDDA equal to or higher than 2.4 V. * @arg SYSCFG_VREFBUF_VOLTAGE_SCALE1: VREFBUF_OUT around 2.5 V. * This requires VDDA equal to or higher than 2.8 V. * @arg SYSCFG_VREFBUF_VOLTAGE_SCALE2: VREFBUF_OUT around 2.9 V. * This requires VDDA equal to or higher than 3.15 V. * @retval None */ void HAL_SYSCFG_VREFBUF_VoltageScalingConfig(uint32_t VoltageScaling) { /* Check the parameters */ assert_param(IS_SYSCFG_VREFBUF_VOLTAGE_SCALE(VoltageScaling)); MODIFY_REG(VREFBUF->CSR, VREFBUF_CSR_VRS, VoltageScaling); } /** * @brief Configure the internal voltage reference buffer high impedance mode. * @param Mode: specifies the high impedance mode * This parameter can be one of the following values: * @arg SYSCFG_VREFBUF_HIGH_IMPEDANCE_DISABLE: VREF+ pin is internally connect to VREFINT output. * @arg SYSCFG_VREFBUF_HIGH_IMPEDANCE_ENABLE: VREF+ pin is high impedance. * @retval None */ void HAL_SYSCFG_VREFBUF_HighImpedanceConfig(uint32_t Mode) { /* Check the parameters */ assert_param(IS_SYSCFG_VREFBUF_HIGH_IMPEDANCE(Mode)); MODIFY_REG(VREFBUF->CSR, VREFBUF_CSR_HIZ, Mode); } /** * @brief Tune the Internal Voltage Reference buffer (VREFBUF). * @param TrimmingValue specifies trimming code for VREFBUF calibration * This parameter can be a number between Min_Data = 0x00 and Max_Data = 0x3F * @retval None */ void HAL_SYSCFG_VREFBUF_TrimmingConfig(uint32_t TrimmingValue) { /* Check the parameters */ assert_param(IS_SYSCFG_VREFBUF_TRIMMING(TrimmingValue)); MODIFY_REG(VREFBUF->CCR, VREFBUF_CCR_TRIM, TrimmingValue); } /** * @brief Enable the Internal Voltage Reference buffer (VREFBUF). * @retval HAL_OK/HAL_TIMEOUT */ HAL_StatusTypeDef HAL_SYSCFG_EnableVREFBUF(void) { uint32_t tickstart; SET_BIT(VREFBUF->CSR, VREFBUF_CSR_ENVR); /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait for VRR bit */ while (READ_BIT(VREFBUF->CSR, VREFBUF_CSR_VRR) == 0x00U) { if ((HAL_GetTick() - tickstart) > VREFBUF_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } return HAL_OK; } /** * @brief Disable the Internal Voltage Reference buffer (VREFBUF). * * @retval None */ void HAL_SYSCFG_DisableVREFBUF(void) { CLEAR_BIT(VREFBUF->CSR, VREFBUF_CSR_ENVR); } #endif /* VREFBUF */ /** * @brief Enable the I/O analog switch voltage booster * * @retval None */ void HAL_SYSCFG_EnableIOSwitchBooster(void) { SET_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_BOOSTEN); } /** * @brief Disable the I/O analog switch voltage booster * * @retval None */ void HAL_SYSCFG_DisableIOSwitchBooster(void) { CLEAR_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_BOOSTEN); } /** * @brief Enable the I/O analog switch voltage by VDD * * @retval None */ void HAL_SYSCFG_EnableIOSwitchVDD(void) { SET_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_ANASWVDD); } /** * @brief Disable the I/O analog switch voltage by VDD * * @retval None */ void HAL_SYSCFG_DisableIOSwitchVDD(void) { CLEAR_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_ANASWVDD); } /** @brief CCMSRAM page write protection enable * @param Page: This parameter is a long 32bit value and can be a value of @ref SYSCFG_CCMSRAMWRP * @note write protection can only be disabled by a system reset * @retval None */ void HAL_SYSCFG_CCMSRAM_WriteProtectionEnable(uint32_t Page) { assert_param(IS_SYSCFG_CCMSRAMWRP_PAGE(Page)); SET_BIT(SYSCFG->SWPR, (uint32_t)(Page)); } /** * @} */ /** * @} */ #endif /* HAL_MODULE_ENABLED */ /** * @} */ /** * @} */
23,218
C
29.037516
109
0.606641
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_crc.c
/** ****************************************************************************** * @file stm32g4xx_hal_crc.c * @author MCD Application Team * @brief CRC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Cyclic Redundancy Check (CRC) peripheral: * + Initialization and de-initialization functions * + Peripheral Control functions * + Peripheral State functions * ****************************************************************************** * @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 CRC AHB clock using __HAL_RCC_CRC_CLK_ENABLE(); (+) Initialize CRC calculator (++) specify generating polynomial (peripheral default or non-default one) (++) specify initialization value (peripheral default or non-default one) (++) specify input data format (++) specify input or output data inversion mode if any (+) Use HAL_CRC_Accumulate() function to compute the CRC value of the input data buffer starting with the previously computed CRC as initialization value (+) Use HAL_CRC_Calculate() function to compute the CRC value of the input data buffer starting with the defined initialization value (default or non-default) to initiate CRC calculation @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup CRC CRC * @brief CRC HAL module driver. * @{ */ #ifdef HAL_CRC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup CRC_Private_Functions CRC Private Functions * @{ */ static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength); static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRC_Exported_Functions CRC Exported Functions * @{ */ /** @defgroup CRC_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 CRC according to the specified parameters in the CRC_InitTypeDef and create the associated handle (+) DeInitialize the CRC peripheral (+) Initialize the CRC MSP (MCU Specific Package) (+) DeInitialize the CRC MSP @endverbatim * @{ */ /** * @brief Initialize the CRC according to the specified * parameters in the CRC_InitTypeDef and create the associated handle. * @param hcrc CRC handle * @retval HAL status */ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc) { /* Check the CRC handle allocation */ if (hcrc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); if (hcrc->State == HAL_CRC_STATE_RESET) { /* Allocate lock resource and initialize it */ hcrc->Lock = HAL_UNLOCKED; /* Init the low level hardware */ HAL_CRC_MspInit(hcrc); } hcrc->State = HAL_CRC_STATE_BUSY; /* check whether or not non-default generating polynomial has been * picked up by user */ assert_param(IS_DEFAULT_POLYNOMIAL(hcrc->Init.DefaultPolynomialUse)); if (hcrc->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_ENABLE) { /* initialize peripheral with default generating polynomial */ WRITE_REG(hcrc->Instance->POL, DEFAULT_CRC32_POLY); MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, CRC_POLYLENGTH_32B); } else { /* initialize CRC peripheral with generating polynomial defined by user */ if (HAL_CRCEx_Polynomial_Set(hcrc, hcrc->Init.GeneratingPolynomial, hcrc->Init.CRCLength) != HAL_OK) { return HAL_ERROR; } } /* check whether or not non-default CRC initial value has been * picked up by user */ assert_param(IS_DEFAULT_INIT_VALUE(hcrc->Init.DefaultInitValueUse)); if (hcrc->Init.DefaultInitValueUse == DEFAULT_INIT_VALUE_ENABLE) { WRITE_REG(hcrc->Instance->INIT, DEFAULT_CRC_INITVALUE); } else { WRITE_REG(hcrc->Instance->INIT, hcrc->Init.InitValue); } /* set input data inversion mode */ assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(hcrc->Init.InputDataInversionMode)); MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, hcrc->Init.InputDataInversionMode); /* set output data inversion mode */ assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(hcrc->Init.OutputDataInversionMode)); MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, hcrc->Init.OutputDataInversionMode); /* makes sure the input data format (bytes, halfwords or words stream) * is properly specified by user */ assert_param(IS_CRC_INPUTDATA_FORMAT(hcrc->InputDataFormat)); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief DeInitialize the CRC peripheral. * @param hcrc CRC handle * @retval HAL status */ HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) { /* Check the CRC handle allocation */ if (hcrc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); /* Check the CRC peripheral state */ if (hcrc->State == HAL_CRC_STATE_BUSY) { return HAL_BUSY; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* Reset CRC calculation unit */ __HAL_CRC_DR_RESET(hcrc); /* Reset IDR register content */ CLEAR_BIT(hcrc->Instance->IDR, CRC_IDR_IDR); /* DeInit the low level hardware */ HAL_CRC_MspDeInit(hcrc); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_RESET; /* Process unlocked */ __HAL_UNLOCK(hcrc); /* Return function status */ return HAL_OK; } /** * @brief Initializes the CRC MSP. * @param hcrc CRC handle * @retval None */ __weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hcrc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_CRC_MspInit can be implemented in the user file */ } /** * @brief DeInitialize the CRC MSP. * @param hcrc CRC handle * @retval None */ __weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hcrc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_CRC_MspDeInit can be implemented in the user file */ } /** * @} */ /** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions * @brief management functions. * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer using combination of the previous CRC value and the new one. [..] or (+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer independently of the previous CRC value. @endverbatim * @{ */ /** * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer * starting with the previously computed CRC as initialization value. * @param hcrc CRC handle * @param pBuffer pointer to the input data buffer, exact input data format is * provided by hcrc->InputDataFormat. * @param BufferLength input data buffer length (number of bytes if pBuffer * type is * uint8_t, number of half-words if pBuffer type is * uint16_t, * number of words if pBuffer type is * uint32_t). * @note By default, the API expects a uint32_t pointer as input buffer parameter. * Input buffer pointers with other types simply need to be cast in uint32_t * and the API will internally adjust its input data processing based on the * handle field hcrc->InputDataFormat. * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { uint32_t index; /* CRC input data buffer index */ uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DR register) */ /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; switch (hcrc->InputDataFormat) { case CRC_INPUTDATA_FORMAT_WORDS: /* Enter Data to the CRC calculator */ for (index = 0U; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } temp = hcrc->Instance->DR; break; case CRC_INPUTDATA_FORMAT_BYTES: temp = CRC_Handle_8(hcrc, (uint8_t *)pBuffer, BufferLength); break; case CRC_INPUTDATA_FORMAT_HALFWORDS: temp = CRC_Handle_16(hcrc, (uint16_t *)(void *)pBuffer, BufferLength); /* Derogation MisraC2012 R.11.5 */ break; default: break; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return the CRC computed value */ return temp; } /** * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer * starting with hcrc->Instance->INIT as initialization value. * @param hcrc CRC handle * @param pBuffer pointer to the input data buffer, exact input data format is * provided by hcrc->InputDataFormat. * @param BufferLength input data buffer length (number of bytes if pBuffer * type is * uint8_t, number of half-words if pBuffer type is * uint16_t, * number of words if pBuffer type is * uint32_t). * @note By default, the API expects a uint32_t pointer as input buffer parameter. * Input buffer pointers with other types simply need to be cast in uint32_t * and the API will internally adjust its input data processing based on the * handle field hcrc->InputDataFormat. * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { uint32_t index; /* CRC input data buffer index */ uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DR register) */ /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* Reset CRC Calculation Unit (hcrc->Instance->INIT is * written in hcrc->Instance->DR) */ __HAL_CRC_DR_RESET(hcrc); switch (hcrc->InputDataFormat) { case CRC_INPUTDATA_FORMAT_WORDS: /* Enter 32-bit input data to the CRC calculator */ for (index = 0U; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } temp = hcrc->Instance->DR; break; case CRC_INPUTDATA_FORMAT_BYTES: /* Specific 8-bit input data handling */ temp = CRC_Handle_8(hcrc, (uint8_t *)pBuffer, BufferLength); break; case CRC_INPUTDATA_FORMAT_HALFWORDS: /* Specific 16-bit input data handling */ temp = CRC_Handle_16(hcrc, (uint16_t *)(void *)pBuffer, BufferLength); /* Derogation MisraC2012 R.11.5 */ break; default: break; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return the CRC computed value */ return temp; } /** * @} */ /** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions * @brief Peripheral State functions. * @verbatim =============================================================================== ##### Peripheral State functions ##### =============================================================================== [..] This subsection permits to get in run-time the status of the peripheral. @endverbatim * @{ */ /** * @brief Return the CRC handle state. * @param hcrc CRC handle * @retval HAL state */ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc) { /* Return CRC handle state */ return hcrc->State; } /** * @} */ /** * @} */ /** @addtogroup CRC_Private_Functions * @{ */ /** * @brief Enter 8-bit input data to the CRC calculator. * Specific data handling to optimize processing time. * @param hcrc CRC handle * @param pBuffer pointer to the input data buffer * @param BufferLength input data buffer length * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength) { uint32_t i; /* input data buffer index */ uint16_t data; __IO uint16_t *pReg; /* Processing time optimization: 4 bytes are entered in a row with a single word write, * last bytes must be carefully fed to the CRC calculator to ensure a correct type * handling by the peripheral */ for (i = 0U; i < (BufferLength / 4U); i++) { hcrc->Instance->DR = ((uint32_t)pBuffer[4U * i] << 24U) | \ ((uint32_t)pBuffer[(4U * i) + 1U] << 16U) | \ ((uint32_t)pBuffer[(4U * i) + 2U] << 8U) | \ (uint32_t)pBuffer[(4U * i) + 3U]; } /* last bytes specific handling */ if ((BufferLength % 4U) != 0U) { if ((BufferLength % 4U) == 1U) { *(__IO uint8_t *)(__IO void *)(&hcrc->Instance->DR) = pBuffer[4U * i]; /* Derogation MisraC2012 R.11.5 */ } if ((BufferLength % 4U) == 2U) { data = ((uint16_t)(pBuffer[4U * i]) << 8U) | (uint16_t)pBuffer[(4U * i) + 1U]; pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */ *pReg = data; } if ((BufferLength % 4U) == 3U) { data = ((uint16_t)(pBuffer[4U * i]) << 8U) | (uint16_t)pBuffer[(4U * i) + 1U]; pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */ *pReg = data; *(__IO uint8_t *)(__IO void *)(&hcrc->Instance->DR) = pBuffer[(4U * i) + 2U]; /* Derogation MisraC2012 R.11.5 */ } } /* Return the CRC computed value */ return hcrc->Instance->DR; } /** * @brief Enter 16-bit input data to the CRC calculator. * Specific data handling to optimize processing time. * @param hcrc CRC handle * @param pBuffer pointer to the input data buffer * @param BufferLength input data buffer length * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength) { uint32_t i; /* input data buffer index */ __IO uint16_t *pReg; /* Processing time optimization: 2 HalfWords are entered in a row with a single word write, * in case of odd length, last HalfWord must be carefully fed to the CRC calculator to ensure * a correct type handling by the peripheral */ for (i = 0U; i < (BufferLength / 2U); i++) { hcrc->Instance->DR = ((uint32_t)pBuffer[2U * i] << 16U) | (uint32_t)pBuffer[(2U * i) + 1U]; } if ((BufferLength % 2U) != 0U) { pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */ *pReg = pBuffer[2U * i]; } /* Return the CRC computed value */ return hcrc->Instance->DR; } /** * @} */ #endif /* HAL_CRC_MODULE_ENABLED */ /** * @} */ /** * @} */
17,026
C
31.934236
119
0.587337
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_rcc_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_rcc_ex.c * @author MCD Application Team * @brief Extended RCC HAL module driver. * This file provides firmware functions to manage the following * functionalities RCC extended peripheral: * + Extended Peripheral Control functions * + Extended Clock management functions * + Extended Clock Recovery System Control functions * ****************************************************************************** * @attention * * Copyright (c) 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 RCCEx RCCEx * @brief RCC Extended HAL module driver * @{ */ #ifdef HAL_RCC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /** @defgroup RCCEx_Private_Constants RCCEx Private Constants * @{ */ #define PLL_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ #define DIVIDER_P_UPDATE 0U #define DIVIDER_Q_UPDATE 1U #define DIVIDER_R_UPDATE 2U #define __LSCO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE() #define LSCO_GPIO_PORT GPIOA #define LSCO_PIN GPIO_PIN_2 /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup RCCEx_Private_Functions RCCEx Private Functions * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Functions RCCEx Exported Functions * @{ */ /** @defgroup RCCEx_Exported_Functions_Group1 Extended Peripheral Control functions * @brief Extended Peripheral Control functions * @verbatim =============================================================================== ##### Extended Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the RCC Clocks frequencies. [..] (@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select the RTC clock source; in this case the Backup domain will be reset in order to modify the RTC Clock source, as consequence RTC registers (including the backup registers) are set to their reset values. @endverbatim * @{ */ /** * @brief Initialize the RCC extended peripherals clocks according to the specified * parameters in the RCC_PeriphCLKInitTypeDef. * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that * contains a field PeriphClockSelection which can be a combination of the following values: * @arg @ref RCC_PERIPHCLK_RTC RTC peripheral clock * @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock * @arg @ref RCC_PERIPHCLK_USART2 USART2 peripheral clock * @arg @ref RCC_PERIPHCLK_USART3 USART3 peripheral clock * @arg @ref RCC_PERIPHCLK_UART4 UART4 peripheral clock (only for devices with UART4) * @arg @ref RCC_PERIPHCLK_UART5 UART5 peripheral clock (only for devices with UART5) * @arg @ref RCC_PERIPHCLK_LPUART1 LPUART1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C2 I2C2 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C3 I2C3 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C4 I2C4 peripheral clock (only for devices with I2C4) * @arg @ref RCC_PERIPHCLK_LPTIM1 LPTIM1 peripheral clock * @arg @ref RCC_PERIPHCLK_SAI1 SAI1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2S I2S peripheral clock * @arg @ref RCC_PERIPHCLK_FDCAN FDCAN peripheral clock (only for devices with FDCAN) * @arg @ref RCC_PERIPHCLK_RNG RNG peripheral clock * @arg @ref RCC_PERIPHCLK_USB USB peripheral clock (only for devices with USB) * @arg @ref RCC_PERIPHCLK_ADC12 ADC1 and ADC2 peripheral clock * @arg @ref RCC_PERIPHCLK_ADC345 ADC3, ADC4 and ADC5 peripheral clock (only for devices with ADC3, ADC4, ADC5) * @arg @ref RCC_PERIPHCLK_QSPI QuadSPI peripheral clock (only for devices with QuadSPI) * * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select * the RTC clock source: in this case the access to Backup domain is enabled. * * @retval HAL status */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) { uint32_t tmpregister; uint32_t tickstart; HAL_StatusTypeDef ret = HAL_OK; /* Intermediate status */ HAL_StatusTypeDef status = HAL_OK; /* Final status */ /* Check the parameters */ assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*-------------------------- RTC clock source configuration ----------------------*/ if((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC) { FlagStatus pwrclkchanged = RESET; /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); /* Enable Power Clock */ if(__HAL_RCC_PWR_IS_CLK_DISABLED()) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } /* Enable write access to Backup domain */ SET_BIT(PWR->CR1, PWR_CR1_DBP); /* Wait for Backup domain Write protection disable */ tickstart = HAL_GetTick(); while((PWR->CR1 & PWR_CR1_DBP) == 0U) { if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { ret = HAL_TIMEOUT; break; } } if(ret == HAL_OK) { /* Reset the Backup domain only if the RTC Clock source selection is modified from default */ tmpregister = READ_BIT(RCC->BDCR, RCC_BDCR_RTCSEL); if((tmpregister != RCC_RTCCLKSOURCE_NONE) && (tmpregister != PeriphClkInit->RTCClockSelection)) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpregister = READ_BIT(RCC->BDCR, ~(RCC_BDCR_RTCSEL)); /* RTC Clock selection can be changed only if the Backup Domain is reset */ __HAL_RCC_BACKUPRESET_FORCE(); __HAL_RCC_BACKUPRESET_RELEASE(); /* Restore the Content of BDCR register */ RCC->BDCR = tmpregister; } /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ if (HAL_IS_BIT_SET(tmpregister, RCC_BDCR_LSEON)) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ while(READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) == 0U) { if((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { ret = HAL_TIMEOUT; break; } } } if(ret == HAL_OK) { /* Apply new RTC clock source selection */ __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection); } else { /* set overall return value */ status = ret; } } else { /* set overall return value */ status = ret; } /* Restore clock configuration if changed */ if(pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } } /*-------------------------- USART1 clock source configuration -------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) { /* Check the parameters */ assert_param(IS_RCC_USART1CLKSOURCE(PeriphClkInit->Usart1ClockSelection)); /* Configure the USART1 clock source */ __HAL_RCC_USART1_CONFIG(PeriphClkInit->Usart1ClockSelection); } /*-------------------------- USART2 clock source configuration -------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2) { /* Check the parameters */ assert_param(IS_RCC_USART2CLKSOURCE(PeriphClkInit->Usart2ClockSelection)); /* Configure the USART2 clock source */ __HAL_RCC_USART2_CONFIG(PeriphClkInit->Usart2ClockSelection); } /*-------------------------- USART3 clock source configuration -------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART3) == RCC_PERIPHCLK_USART3) { /* Check the parameters */ assert_param(IS_RCC_USART3CLKSOURCE(PeriphClkInit->Usart3ClockSelection)); /* Configure the USART3 clock source */ __HAL_RCC_USART3_CONFIG(PeriphClkInit->Usart3ClockSelection); } #if defined(UART4) /*-------------------------- UART4 clock source configuration --------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_UART4) == RCC_PERIPHCLK_UART4) { /* Check the parameters */ assert_param(IS_RCC_UART4CLKSOURCE(PeriphClkInit->Uart4ClockSelection)); /* Configure the UART4 clock source */ __HAL_RCC_UART4_CONFIG(PeriphClkInit->Uart4ClockSelection); } #endif /* UART4 */ #if defined(UART5) /*-------------------------- UART5 clock source configuration --------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_UART5) == RCC_PERIPHCLK_UART5) { /* Check the parameters */ assert_param(IS_RCC_UART5CLKSOURCE(PeriphClkInit->Uart5ClockSelection)); /* Configure the UART5 clock source */ __HAL_RCC_UART5_CONFIG(PeriphClkInit->Uart5ClockSelection); } #endif /* UART5 */ /*-------------------------- LPUART1 clock source configuration ------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPUART1) == RCC_PERIPHCLK_LPUART1) { /* Check the parameters */ assert_param(IS_RCC_LPUART1CLKSOURCE(PeriphClkInit->Lpuart1ClockSelection)); /* Configure the LPUAR1 clock source */ __HAL_RCC_LPUART1_CONFIG(PeriphClkInit->Lpuart1ClockSelection); } /*-------------------------- I2C1 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) { /* Check the parameters */ assert_param(IS_RCC_I2C1CLKSOURCE(PeriphClkInit->I2c1ClockSelection)); /* Configure the I2C1 clock source */ __HAL_RCC_I2C1_CONFIG(PeriphClkInit->I2c1ClockSelection); } /*-------------------------- I2C2 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C2) == RCC_PERIPHCLK_I2C2) { /* Check the parameters */ assert_param(IS_RCC_I2C2CLKSOURCE(PeriphClkInit->I2c2ClockSelection)); /* Configure the I2C2 clock source */ __HAL_RCC_I2C2_CONFIG(PeriphClkInit->I2c2ClockSelection); } /*-------------------------- I2C3 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C3) == RCC_PERIPHCLK_I2C3) { /* Check the parameters */ assert_param(IS_RCC_I2C3CLKSOURCE(PeriphClkInit->I2c3ClockSelection)); /* Configure the I2C3 clock source */ __HAL_RCC_I2C3_CONFIG(PeriphClkInit->I2c3ClockSelection); } #if defined(I2C4) /*-------------------------- I2C4 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C4) == RCC_PERIPHCLK_I2C4) { /* Check the parameters */ assert_param(IS_RCC_I2C4CLKSOURCE(PeriphClkInit->I2c4ClockSelection)); /* Configure the I2C4 clock source */ __HAL_RCC_I2C4_CONFIG(PeriphClkInit->I2c4ClockSelection); } #endif /* I2C4 */ /*-------------------------- LPTIM1 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) { /* Check the parameters */ assert_param(IS_RCC_LPTIM1CLKSOURCE(PeriphClkInit->Lptim1ClockSelection)); /* Configure the LPTIM1 clock source */ __HAL_RCC_LPTIM1_CONFIG(PeriphClkInit->Lptim1ClockSelection); } /*-------------------------- SAI1 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) { /* Check the parameters */ assert_param(IS_RCC_SAI1CLKSOURCE(PeriphClkInit->Sai1ClockSelection)); /* Configure the SAI1 interface clock source */ __HAL_RCC_SAI1_CONFIG(PeriphClkInit->Sai1ClockSelection); if(PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } /*-------------------------- I2S clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) { /* Check the parameters */ assert_param(IS_RCC_I2SCLKSOURCE(PeriphClkInit->I2sClockSelection)); /* Configure the I2S interface clock source */ __HAL_RCC_I2S_CONFIG(PeriphClkInit->I2sClockSelection); if(PeriphClkInit->I2sClockSelection == RCC_I2SCLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } #if defined(FDCAN1) /*-------------------------- FDCAN clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FDCAN) == RCC_PERIPHCLK_FDCAN) { /* Check the parameters */ assert_param(IS_RCC_FDCANCLKSOURCE(PeriphClkInit->FdcanClockSelection)); /* Configure the FDCAN interface clock source */ __HAL_RCC_FDCAN_CONFIG(PeriphClkInit->FdcanClockSelection); if(PeriphClkInit->FdcanClockSelection == RCC_FDCANCLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } #endif /* FDCAN1 */ #if defined(USB) /*-------------------------- USB clock source configuration ----------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == (RCC_PERIPHCLK_USB)) { assert_param(IS_RCC_USBCLKSOURCE(PeriphClkInit->UsbClockSelection)); __HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection); if(PeriphClkInit->UsbClockSelection == RCC_USBCLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } #endif /* USB */ /*-------------------------- RNG clock source configuration ----------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RNG) == (RCC_PERIPHCLK_RNG)) { assert_param(IS_RCC_RNGCLKSOURCE(PeriphClkInit->RngClockSelection)); __HAL_RCC_RNG_CONFIG(PeriphClkInit->RngClockSelection); if(PeriphClkInit->RngClockSelection == RCC_RNGCLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } /*-------------------------- ADC12 clock source configuration ----------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADC12) == RCC_PERIPHCLK_ADC12) { /* Check the parameters */ assert_param(IS_RCC_ADC12CLKSOURCE(PeriphClkInit->Adc12ClockSelection)); /* Configure the ADC12 interface clock source */ __HAL_RCC_ADC12_CONFIG(PeriphClkInit->Adc12ClockSelection); if(PeriphClkInit->Adc12ClockSelection == RCC_ADC12CLKSOURCE_PLL) { /* Enable PLLADCCLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_ADCCLK); } } #if defined(ADC345_COMMON) /*-------------------------- ADC345 clock source configuration ----------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADC345) == RCC_PERIPHCLK_ADC345) { /* Check the parameters */ assert_param(IS_RCC_ADC345CLKSOURCE(PeriphClkInit->Adc345ClockSelection)); /* Configure the ADC345 interface clock source */ __HAL_RCC_ADC345_CONFIG(PeriphClkInit->Adc345ClockSelection); if(PeriphClkInit->Adc345ClockSelection == RCC_ADC345CLKSOURCE_PLL) { /* Enable PLLADCCLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_ADCCLK); } } #endif /* ADC345_COMMON */ #if defined(QUADSPI) /*-------------------------- QuadSPIx clock source configuration ----------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_QSPI) == RCC_PERIPHCLK_QSPI) { /* Check the parameters */ assert_param(IS_RCC_QSPICLKSOURCE(PeriphClkInit->QspiClockSelection)); /* Configure the QuadSPI clock source */ __HAL_RCC_QSPI_CONFIG(PeriphClkInit->QspiClockSelection); if(PeriphClkInit->QspiClockSelection == RCC_QSPICLKSOURCE_PLL) { /* Enable PLL48M1CLK output */ __HAL_RCC_PLLCLKOUT_ENABLE(RCC_PLL_48M1CLK); } } #endif /* QUADSPI */ return status; } /** * @brief Get the RCC_ClkInitStruct according to the internal RCC configuration registers. * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that * returns the configuration information for the Extended Peripherals * clocks(USART1, USART2, USART3, UART4, UART5, LPUART1, I2C1, I2C2, I2C3, I2C4, * LPTIM1, SAI1, I2Sx, FDCANx, USB, RNG, ADCx, RTC, QSPI). * @retval None */ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) { /* Set all possible values for the extended clock type parameter------------*/ #if defined(STM32G474xx) || defined(STM32G484xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ RCC_PERIPHCLK_UART5 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_I2C4 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_FDCAN | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | RCC_PERIPHCLK_ADC345 | \ RCC_PERIPHCLK_QSPI | \ RCC_PERIPHCLK_RTC; #elif defined(STM32G491xx) || defined(STM32G4A1xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ RCC_PERIPHCLK_UART5 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_FDCAN | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | RCC_PERIPHCLK_ADC345 | \ RCC_PERIPHCLK_QSPI | \ RCC_PERIPHCLK_RTC; #elif defined(STM32G473xx) || defined(STM32G483xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ RCC_PERIPHCLK_UART5 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_I2C4 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | RCC_PERIPHCLK_ADC345 | \ RCC_PERIPHCLK_QSPI | \ RCC_PERIPHCLK_RTC; #elif defined(STM32G471xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ RCC_PERIPHCLK_UART5 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_I2C4 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | \ RCC_PERIPHCLK_RTC; #elif defined(STM32G431xx) || defined(STM32G441xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_FDCAN | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | \ RCC_PERIPHCLK_RTC; #elif defined(STM32GBK1CB) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | \ RCC_PERIPHCLK_LPUART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_I2C3 | \ RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_FDCAN | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | \ RCC_PERIPHCLK_RTC; #endif /* STM32G431xx */ /* Get the USART1 clock source ---------------------------------------------*/ PeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE(); /* Get the USART2 clock source ---------------------------------------------*/ PeriphClkInit->Usart2ClockSelection = __HAL_RCC_GET_USART2_SOURCE(); /* Get the USART3 clock source ---------------------------------------------*/ PeriphClkInit->Usart3ClockSelection = __HAL_RCC_GET_USART3_SOURCE(); #if defined(UART4) /* Get the UART4 clock source ----------------------------------------------*/ PeriphClkInit->Uart4ClockSelection = __HAL_RCC_GET_UART4_SOURCE(); #endif /* UART4 */ #if defined(UART5) /* Get the UART5 clock source ----------------------------------------------*/ PeriphClkInit->Uart5ClockSelection = __HAL_RCC_GET_UART5_SOURCE(); #endif /* UART5 */ /* Get the LPUART1 clock source --------------------------------------------*/ PeriphClkInit->Lpuart1ClockSelection = __HAL_RCC_GET_LPUART1_SOURCE(); /* Get the I2C1 clock source -----------------------------------------------*/ PeriphClkInit->I2c1ClockSelection = __HAL_RCC_GET_I2C1_SOURCE(); /* Get the I2C2 clock source ----------------------------------------------*/ PeriphClkInit->I2c2ClockSelection = __HAL_RCC_GET_I2C2_SOURCE(); /* Get the I2C3 clock source -----------------------------------------------*/ PeriphClkInit->I2c3ClockSelection = __HAL_RCC_GET_I2C3_SOURCE(); #if defined(I2C4) /* Get the I2C4 clock source -----------------------------------------------*/ PeriphClkInit->I2c4ClockSelection = __HAL_RCC_GET_I2C4_SOURCE(); #endif /* I2C4 */ /* Get the LPTIM1 clock source ---------------------------------------------*/ PeriphClkInit->Lptim1ClockSelection = __HAL_RCC_GET_LPTIM1_SOURCE(); /* Get the SAI1 clock source -----------------------------------------------*/ PeriphClkInit->Sai1ClockSelection = __HAL_RCC_GET_SAI1_SOURCE(); /* Get the I2S clock source -----------------------------------------------*/ PeriphClkInit->I2sClockSelection = __HAL_RCC_GET_I2S_SOURCE(); #if defined(FDCAN1) /* Get the FDCAN clock source -----------------------------------------------*/ PeriphClkInit->FdcanClockSelection = __HAL_RCC_GET_FDCAN_SOURCE(); #endif /* FDCAN1 */ #if defined(USB) /* Get the USB clock source ------------------------------------------------*/ PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE(); #endif /* USB */ /* Get the RNG clock source ------------------------------------------------*/ PeriphClkInit->RngClockSelection = __HAL_RCC_GET_RNG_SOURCE(); /* Get the ADC12 clock source -----------------------------------------------*/ PeriphClkInit->Adc12ClockSelection = __HAL_RCC_GET_ADC12_SOURCE(); #if defined(ADC345_COMMON) /* Get the ADC345 clock source ----------------------------------------------*/ PeriphClkInit->Adc345ClockSelection = __HAL_RCC_GET_ADC345_SOURCE(); #endif /* ADC345_COMMON */ #if defined(QUADSPI) /* Get the QuadSPIclock source --------------------------------------------*/ PeriphClkInit->QspiClockSelection = __HAL_RCC_GET_QSPI_SOURCE(); #endif /* QUADSPI */ /* Get the RTC clock source ------------------------------------------------*/ PeriphClkInit->RTCClockSelection = __HAL_RCC_GET_RTC_SOURCE(); } /** * @brief Return the peripheral clock frequency for peripherals with clock source from PLL * @note Return 0 if peripheral clock identifier not managed by this API * @param PeriphClk Peripheral clock identifier * This parameter can be one of the following values: * @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock * @arg @ref RCC_PERIPHCLK_USART2 USART2 peripheral clock * @arg @ref RCC_PERIPHCLK_USART3 USART3 peripheral clock * @arg @ref RCC_PERIPHCLK_UART4 UART4 peripheral clock (only for devices with UART4) * @arg @ref RCC_PERIPHCLK_UART5 UART5 peripheral clock (only for devices with UART5) * @arg @ref RCC_PERIPHCLK_LPUART1 LPUART1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C2 I2C2 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C3 I2C3 peripheral clock * @arg @ref RCC_PERIPHCLK_I2C4 I2C4 peripheral clock (only for devices with I2C4) * @arg @ref RCC_PERIPHCLK_LPTIM1 LPTIM1 peripheral clock * @arg @ref RCC_PERIPHCLK_SAI1 SAI1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2S SPI peripheral clock * @arg @ref RCC_PERIPHCLK_FDCAN FDCAN peripheral clock (only for devices with FDCAN) * @arg @ref RCC_PERIPHCLK_RNG RNG peripheral clock * @arg @ref RCC_PERIPHCLK_USB USB peripheral clock (only for devices with USB) * @arg @ref RCC_PERIPHCLK_ADC12 ADC1 and ADC2 peripheral clock * @arg @ref RCC_PERIPHCLK_ADC345 ADC3, ADC4 and ADC5 peripheral clock (only for devices with ADC3, ADC4, ADC5) * @arg @ref RCC_PERIPHCLK_QSPI QSPI peripheral clock (only for devices with QSPI) * @arg @ref RCC_PERIPHCLK_RTC RTC peripheral clock * @retval Frequency in Hz */ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { uint32_t frequency = 0U; uint32_t srcclk; uint32_t pllvco, plln, pllp; /* Check the parameters */ assert_param(IS_RCC_PERIPHCLOCK(PeriphClk)); if(PeriphClk == RCC_PERIPHCLK_RTC) { /* Get the current RTC source */ srcclk = __HAL_RCC_GET_RTC_SOURCE(); /* Check if LSE is ready and if RTC clock selection is LSE */ if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_RTCCLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Check if LSI is ready and if RTC clock selection is LSI */ else if ((HAL_IS_BIT_SET(RCC->CSR, RCC_CSR_LSIRDY)) && (srcclk == RCC_RTCCLKSOURCE_LSI)) { frequency = LSI_VALUE; } /* Check if HSE is ready and if RTC clock selection is HSI_DIV32*/ else if ((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)) && (srcclk == RCC_RTCCLKSOURCE_HSE_DIV32)) { frequency = HSE_VALUE / 32U; } /* Clock not enabled for RTC*/ else { /* nothing to do: frequency already initialized to 0 */ } } else { /* Other external peripheral clock source than RTC */ /* Compute PLL clock input */ if(__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI) /* HSI ? */ { if(HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) { pllvco = HSI_VALUE; } else { pllvco = 0U; } } else if(__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) /* HSE ? */ { if(HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)) { pllvco = HSE_VALUE; } else { pllvco = 0U; } } else /* No source */ { pllvco = 0U; } /* f(PLL Source) / PLLM */ pllvco = (pllvco / ((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1U)); switch(PeriphClk) { case RCC_PERIPHCLK_USART1: /* Get the current USART1 source */ srcclk = __HAL_RCC_GET_USART1_SOURCE(); if(srcclk == RCC_USART1CLKSOURCE_PCLK2) { frequency = HAL_RCC_GetPCLK2Freq(); } else if(srcclk == RCC_USART1CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART1CLKSOURCE_HSI) ) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART1CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for USART1 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_USART2: /* Get the current USART2 source */ srcclk = __HAL_RCC_GET_USART2_SOURCE(); if(srcclk == RCC_USART2CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_USART2CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART2CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART2CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for USART2 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_USART3: /* Get the current USART3 source */ srcclk = __HAL_RCC_GET_USART3_SOURCE(); if(srcclk == RCC_USART3CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_USART3CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_USART3CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_USART3CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for USART3 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #if defined(UART4) case RCC_PERIPHCLK_UART4: /* Get the current UART4 source */ srcclk = __HAL_RCC_GET_UART4_SOURCE(); if(srcclk == RCC_UART4CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_UART4CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_UART4CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_UART4CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for UART4 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* UART4 */ #if defined(UART5) case RCC_PERIPHCLK_UART5: /* Get the current UART5 source */ srcclk = __HAL_RCC_GET_UART5_SOURCE(); if(srcclk == RCC_UART5CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_UART5CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_UART5CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_UART5CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for UART5 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* UART5 */ case RCC_PERIPHCLK_LPUART1: /* Get the current LPUART1 source */ srcclk = __HAL_RCC_GET_LPUART1_SOURCE(); if(srcclk == RCC_LPUART1CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_LPUART1CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPUART1CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPUART1CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for LPUART1 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_I2C1: /* Get the current I2C1 source */ srcclk = __HAL_RCC_GET_I2C1_SOURCE(); if(srcclk == RCC_I2C1CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_I2C1CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C1CLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for I2C1 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_I2C2: /* Get the current I2C2 source */ srcclk = __HAL_RCC_GET_I2C2_SOURCE(); if(srcclk == RCC_I2C2CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_I2C2CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C2CLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for I2C2 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_I2C3: /* Get the current I2C3 source */ srcclk = __HAL_RCC_GET_I2C3_SOURCE(); if(srcclk == RCC_I2C3CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_I2C3CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C3CLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for I2C3 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #if defined(I2C4) case RCC_PERIPHCLK_I2C4: /* Get the current I2C4 source */ srcclk = __HAL_RCC_GET_I2C4_SOURCE(); if(srcclk == RCC_I2C4CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_I2C4CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2C4CLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for I2C4 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* I2C4 */ case RCC_PERIPHCLK_LPTIM1: /* Get the current LPTIM1 source */ srcclk = __HAL_RCC_GET_LPTIM1_SOURCE(); if(srcclk == RCC_LPTIM1CLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if((HAL_IS_BIT_SET(RCC->CSR, RCC_CSR_LSIRDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_LSI)) { frequency = LSI_VALUE; } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_HSI)) { frequency = HSI_VALUE; } else if ((HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSERDY)) && (srcclk == RCC_LPTIM1CLKSOURCE_LSE)) { frequency = LSE_VALUE; } /* Clock not enabled for LPTIM1 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_SAI1: /* Get the current SAI1 source */ srcclk = __HAL_RCC_GET_SAI1_SOURCE(); if(srcclk == RCC_SAI1CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if(srcclk == RCC_SAI1CLKSOURCE_PLL) { if(__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL_48M1CLK) != 0U) { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } } else if(srcclk == RCC_SAI1CLKSOURCE_EXT) { /* External clock used.*/ frequency = EXTERNAL_CLOCK_VALUE; } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_SAI1CLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for SAI1 */ else { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_I2S: /* Get the current I2Sx source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); if(srcclk == RCC_I2SCLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else if(srcclk == RCC_I2SCLKSOURCE_PLL) { if(__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL_48M1CLK) != 0U) { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } } else if(srcclk == RCC_I2SCLKSOURCE_EXT) { /* External clock used.*/ frequency = EXTERNAL_CLOCK_VALUE; } else if((HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSIRDY)) && (srcclk == RCC_I2SCLKSOURCE_HSI)) { frequency = HSI_VALUE; } /* Clock not enabled for I2S */ else { /* nothing to do: frequency already initialized to 0 */ } break; #if defined(FDCAN1) case RCC_PERIPHCLK_FDCAN: /* Get the current FDCANx source */ srcclk = __HAL_RCC_GET_FDCAN_SOURCE(); if(srcclk == RCC_FDCANCLKSOURCE_PCLK1) { frequency = HAL_RCC_GetPCLK1Freq(); } else if(srcclk == RCC_FDCANCLKSOURCE_HSE) { frequency = HSE_VALUE; } else if(srcclk == RCC_FDCANCLKSOURCE_PLL) { if(__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL_48M1CLK) != 0U) { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } } /* Clock not enabled for FDCAN */ else { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* FDCAN1 */ #if defined(USB) case RCC_PERIPHCLK_USB: /* Get the current USB source */ srcclk = __HAL_RCC_GET_USB_SOURCE(); if(srcclk == RCC_USBCLKSOURCE_PLL) /* PLL ? */ { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } else if((HAL_IS_BIT_SET(RCC->CRRCR, RCC_CRRCR_HSI48RDY)) && (srcclk == RCC_USBCLKSOURCE_HSI48)) /* HSI48 ? */ { frequency = HSI48_VALUE; } else /* No clock source */ { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* USB */ case RCC_PERIPHCLK_RNG: /* Get the current RNG source */ srcclk = __HAL_RCC_GET_RNG_SOURCE(); if(srcclk == RCC_RNGCLKSOURCE_PLL) /* PLL ? */ { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } else if( (HAL_IS_BIT_SET(RCC->CRRCR, RCC_CRRCR_HSI48RDY)) && (srcclk == RCC_RNGCLKSOURCE_HSI48)) /* HSI48 ? */ { frequency = HSI48_VALUE; } else /* No clock source */ { /* nothing to do: frequency already initialized to 0 */ } break; case RCC_PERIPHCLK_ADC12: /* Get the current ADC12 source */ srcclk = __HAL_RCC_GET_ADC12_SOURCE(); if(srcclk == RCC_ADC12CLKSOURCE_PLL) { if(__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL_ADCCLK) != 0U) { /* f(PLLP) = f(VCO input) * PLLN / PLLP */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; pllp = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLPDIV) >> RCC_PLLCFGR_PLLPDIV_Pos; if(pllp == 0U) { if(READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLP) != 0U) { pllp = 17U; } else { pllp = 7U; } } frequency = (pllvco * plln) / pllp; } } else if(srcclk == RCC_ADC12CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } /* Clock not enabled for ADC12 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #if defined(ADC345_COMMON) case RCC_PERIPHCLK_ADC345: /* Get the current ADC345 source */ srcclk = __HAL_RCC_GET_ADC345_SOURCE(); if(srcclk == RCC_ADC345CLKSOURCE_PLL) { if(__HAL_RCC_GET_PLLCLKOUT_CONFIG(RCC_PLL_ADCCLK) != 0U) { /* f(PLLP) = f(VCO input) * PLLN / PLLP */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; pllp = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLPDIV) >> RCC_PLLCFGR_PLLPDIV_Pos; if(pllp == 0U) { if(READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLP) != 0U) { pllp = 17U; } else { pllp = 7U; } } frequency = (pllvco * plln) / pllp; } } else if(srcclk == RCC_ADC345CLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } /* Clock not enabled for ADC345 */ else { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* ADC345_COMMON */ #if defined(QUADSPI) case RCC_PERIPHCLK_QSPI: /* Get the current QSPI source */ srcclk = __HAL_RCC_GET_QSPI_SOURCE(); if(srcclk == RCC_QSPICLKSOURCE_PLL) /* PLL ? */ { /* f(PLLQ) = f(VCO input) * PLLN / PLLQ */ plln = READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; frequency = (pllvco * plln) / (((READ_BIT(RCC->PLLCFGR, RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos) + 1U) << 1U); } else if(srcclk == RCC_QSPICLKSOURCE_HSI) { frequency = HSI_VALUE; } else if(srcclk == RCC_QSPICLKSOURCE_SYSCLK) { frequency = HAL_RCC_GetSysClockFreq(); } else /* No clock source */ { /* nothing to do: frequency already initialized to 0 */ } break; #endif /* QUADSPI */ default: break; } } return(frequency); } /** * @} */ /** @defgroup RCCEx_Exported_Functions_Group2 Extended Clock management functions * @brief Extended Clock management functions * @verbatim =============================================================================== ##### Extended clock management functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the activation or deactivation of LSE CSS, Low speed clock output and clock after wake-up from STOP mode. @endverbatim * @{ */ /** * @brief Enable the LSE Clock Security System. * @note Prior to enable the LSE Clock Security System, LSE oscillator is to be enabled * with HAL_RCC_OscConfig() and the LSE oscillator clock is to be selected as RTC * clock with HAL_RCCEx_PeriphCLKConfig(). * @retval None */ void HAL_RCCEx_EnableLSECSS(void) { SET_BIT(RCC->BDCR, RCC_BDCR_LSECSSON) ; } /** * @brief Disable the LSE Clock Security System. * @note LSE Clock Security System can only be disabled after a LSE failure detection. * @retval None */ void HAL_RCCEx_DisableLSECSS(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSECSSON) ; /* Disable LSE CSS IT if any */ __HAL_RCC_DISABLE_IT(RCC_IT_LSECSS); } /** * @brief Enable the LSE Clock Security System Interrupt & corresponding EXTI line. * @note LSE Clock Security System Interrupt is mapped on RTC EXTI line 19 * @retval None */ void HAL_RCCEx_EnableLSECSS_IT(void) { /* Enable LSE CSS */ SET_BIT(RCC->BDCR, RCC_BDCR_LSECSSON) ; /* Enable LSE CSS IT */ __HAL_RCC_ENABLE_IT(RCC_IT_LSECSS); /* Enable IT on EXTI Line 19 */ __HAL_RCC_LSECSS_EXTI_ENABLE_IT(); __HAL_RCC_LSECSS_EXTI_ENABLE_RISING_EDGE(); } /** * @brief Handle the RCC LSE Clock Security System interrupt request. * @retval None */ void HAL_RCCEx_LSECSS_IRQHandler(void) { /* Check RCC LSE CSSF flag */ if(__HAL_RCC_GET_IT(RCC_IT_LSECSS)) { /* RCC LSE Clock Security System interrupt user callback */ HAL_RCCEx_LSECSS_Callback(); /* Clear RCC LSE CSS pending bit */ __HAL_RCC_CLEAR_IT(RCC_IT_LSECSS); } } /** * @brief RCCEx LSE Clock Security System interrupt callback. * @retval none */ __weak void HAL_RCCEx_LSECSS_Callback(void) { /* NOTE : This function should not be modified, when the callback is needed, the @ref HAL_RCCEx_LSECSS_Callback should be implemented in the user file */ } /** * @brief Select the Low Speed clock source to output on LSCO pin (PA2). * @param LSCOSource specifies the Low Speed clock source to output. * This parameter can be one of the following values: * @arg @ref RCC_LSCOSOURCE_LSI LSI clock selected as LSCO source * @arg @ref RCC_LSCOSOURCE_LSE LSE clock selected as LSCO source * @retval None */ void HAL_RCCEx_EnableLSCO(uint32_t LSCOSource) { GPIO_InitTypeDef GPIO_InitStruct; FlagStatus pwrclkchanged = RESET; FlagStatus backupchanged = RESET; /* Check the parameters */ assert_param(IS_RCC_LSCOSOURCE(LSCOSource)); /* LSCO Pin Clock Enable */ __LSCO_CLK_ENABLE(); /* Configure the LSCO pin in analog mode */ GPIO_InitStruct.Pin = LSCO_PIN; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(LSCO_GPIO_PORT, &GPIO_InitStruct); /* Update LSCOSEL clock source in Backup Domain control register */ if(__HAL_RCC_PWR_IS_CLK_DISABLED()) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } if(HAL_IS_BIT_CLR(PWR->CR1, PWR_CR1_DBP)) { HAL_PWR_EnableBkUpAccess(); backupchanged = SET; } MODIFY_REG(RCC->BDCR, RCC_BDCR_LSCOSEL | RCC_BDCR_LSCOEN, LSCOSource | RCC_BDCR_LSCOEN); if(backupchanged == SET) { HAL_PWR_DisableBkUpAccess(); } if(pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } } /** * @brief Disable the Low Speed clock output. * @retval None */ void HAL_RCCEx_DisableLSCO(void) { FlagStatus pwrclkchanged = RESET; FlagStatus backupchanged = RESET; /* Update LSCOEN bit in Backup Domain control register */ if(__HAL_RCC_PWR_IS_CLK_DISABLED()) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } if(HAL_IS_BIT_CLR(PWR->CR1, PWR_CR1_DBP)) { /* Enable access to the backup domain */ HAL_PWR_EnableBkUpAccess(); backupchanged = SET; } CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSCOEN); /* Restore previous configuration */ if(backupchanged == SET) { /* Disable access to the backup domain */ HAL_PWR_DisableBkUpAccess(); } if(pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } } /** * @} */ #if defined(CRS) /** @defgroup RCCEx_Exported_Functions_Group3 Extended Clock Recovery System Control functions * @brief Extended Clock Recovery System Control functions * @verbatim =============================================================================== ##### Extended Clock Recovery System Control functions ##### =============================================================================== [..] For devices with Clock Recovery System feature (CRS), RCC Extension HAL driver can be used as follows: (#) In System clock config, HSI48 needs to be enabled (#) Enable CRS clock in IP MSP init which will use CRS functions (#) Call CRS functions as follows: (##) Prepare synchronization configuration necessary for HSI48 calibration (+++) Default values can be set for frequency Error Measurement (reload and error limit) and also HSI48 oscillator smooth trimming. (+++) Macro __HAL_RCC_CRS_RELOADVALUE_CALCULATE can be also used to calculate directly reload value with target and sychronization frequencies values (##) Call function HAL_RCCEx_CRSConfig which (+++) Resets CRS registers to their default values. (+++) Configures CRS registers with synchronization configuration (+++) Enables automatic calibration and frequency error counter feature Note: When using USB LPM (Link Power Management) and the device is in Sleep mode, the periodic USB SOF will not be generated by the host. No SYNC signal will therefore be provided to the CRS to calibrate the HSI48 on the run. To guarantee the required clock precision after waking up from Sleep mode, the LSE or reference clock on the GPIOs should be used as SYNC signal. (##) A polling function is provided to wait for complete synchronization (+++) Call function HAL_RCCEx_CRSWaitSynchronization() (+++) According to CRS status, user can decide to adjust again the calibration or continue application if synchronization is OK (#) User can retrieve information related to synchronization in calling function HAL_RCCEx_CRSGetSynchronizationInfo() (#) Regarding synchronization status and synchronization information, user can try a new calibration in changing synchronization configuration and call again HAL_RCCEx_CRSConfig. Note: When the SYNC event is detected during the downcounting phase (before reaching the zero value), it means that the actual frequency is lower than the target (and so, that the TRIM value should be incremented), while when it is detected during the upcounting phase it means that the actual frequency is higher (and that the TRIM value should be decremented). (#) In interrupt mode, user can resort to the available macros (__HAL_RCC_CRS_XXX_IT). Interrupts will go through CRS Handler (CRS_IRQn/CRS_IRQHandler) (++) Call function HAL_RCCEx_CRSConfig() (++) Enable CRS_IRQn (thanks to NVIC functions) (++) Enable CRS interrupt (__HAL_RCC_CRS_ENABLE_IT) (++) Implement CRS status management in the following user callbacks called from HAL_RCCEx_CRS_IRQHandler(): (+++) HAL_RCCEx_CRS_SyncOkCallback() (+++) HAL_RCCEx_CRS_SyncWarnCallback() (+++) HAL_RCCEx_CRS_ExpectedSyncCallback() (+++) HAL_RCCEx_CRS_ErrorCallback() (#) To force a SYNC EVENT, user can use the function HAL_RCCEx_CRSSoftwareSynchronizationGenerate(). This function can be called before calling HAL_RCCEx_CRSConfig (for instance in Systick handler) @endverbatim * @{ */ /** * @brief Start automatic synchronization for polling mode * @param pInit Pointer on RCC_CRSInitTypeDef structure * @retval None */ void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit) { uint32_t value; /* Check the parameters */ assert_param(IS_RCC_CRS_SYNC_DIV(pInit->Prescaler)); assert_param(IS_RCC_CRS_SYNC_SOURCE(pInit->Source)); assert_param(IS_RCC_CRS_SYNC_POLARITY(pInit->Polarity)); assert_param(IS_RCC_CRS_RELOADVALUE(pInit->ReloadValue)); assert_param(IS_RCC_CRS_ERRORLIMIT(pInit->ErrorLimitValue)); assert_param(IS_RCC_CRS_HSI48CALIBRATION(pInit->HSI48CalibrationValue)); /* CONFIGURATION */ /* Before configuration, reset CRS registers to their default values*/ __HAL_RCC_CRS_FORCE_RESET(); __HAL_RCC_CRS_RELEASE_RESET(); /* Set the SYNCDIV[2:0] bits according to Prescaler value */ /* Set the SYNCSRC[1:0] bits according to Source value */ /* Set the SYNCSPOL bit according to Polarity value */ value = (pInit->Prescaler | pInit->Source | pInit->Polarity); /* Set the RELOAD[15:0] bits according to ReloadValue value */ value |= pInit->ReloadValue; /* Set the FELIM[7:0] bits according to ErrorLimitValue value */ value |= (pInit->ErrorLimitValue << CRS_CFGR_FELIM_Pos); WRITE_REG(CRS->CFGR, value); /* Adjust HSI48 oscillator smooth trimming */ /* Set the TRIM[6:0] bits according to RCC_CRS_HSI48CalibrationValue value */ MODIFY_REG(CRS->CR, CRS_CR_TRIM, (pInit->HSI48CalibrationValue << CRS_CR_TRIM_Pos)); /* START AUTOMATIC SYNCHRONIZATION*/ /* Enable Automatic trimming & Frequency error counter */ SET_BIT(CRS->CR, CRS_CR_AUTOTRIMEN | CRS_CR_CEN); } /** * @brief Generate the software synchronization event * @retval None */ void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void) { SET_BIT(CRS->CR, CRS_CR_SWSYNC); } /** * @brief Return synchronization info * @param pSynchroInfo Pointer on RCC_CRSSynchroInfoTypeDef structure * @retval None */ void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo) { /* Check the parameter */ assert_param(pSynchroInfo != (void *)NULL); /* Get the reload value */ pSynchroInfo->ReloadValue = (READ_BIT(CRS->CFGR, CRS_CFGR_RELOAD)); /* Get HSI48 oscillator smooth trimming */ pSynchroInfo->HSI48CalibrationValue = (READ_BIT(CRS->CR, CRS_CR_TRIM) >> CRS_CR_TRIM_Pos); /* Get Frequency error capture */ pSynchroInfo->FreqErrorCapture = (READ_BIT(CRS->ISR, CRS_ISR_FECAP) >> CRS_ISR_FECAP_Pos); /* Get Frequency error direction */ pSynchroInfo->FreqErrorDirection = (READ_BIT(CRS->ISR, CRS_ISR_FEDIR)); } /** * @brief Wait for CRS Synchronization status. * @param Timeout Duration of the timeout * @note Timeout is based on the maximum time to receive a SYNC event based on synchronization * frequency. * @note If Timeout set to HAL_MAX_DELAY, HAL_TIMEOUT will be never returned. * @retval Combination of Synchronization status * This parameter can be a combination of the following values: * @arg @ref RCC_CRS_TIMEOUT * @arg @ref RCC_CRS_SYNCOK * @arg @ref RCC_CRS_SYNCWARN * @arg @ref RCC_CRS_SYNCERR * @arg @ref RCC_CRS_SYNCMISS * @arg @ref RCC_CRS_TRIMOVF */ uint32_t HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout) { uint32_t crsstatus = RCC_CRS_NONE; uint32_t tickstart; /* Get timeout */ tickstart = HAL_GetTick(); /* Wait for CRS flag or timeout detection */ do { if(Timeout != HAL_MAX_DELAY) { if(((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) { crsstatus = RCC_CRS_TIMEOUT; } } /* Check CRS SYNCOK flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCOK)) { /* CRS SYNC event OK */ crsstatus |= RCC_CRS_SYNCOK; /* Clear CRS SYNC event OK bit */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCOK); } /* Check CRS SYNCWARN flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCWARN)) { /* CRS SYNC warning */ crsstatus |= RCC_CRS_SYNCWARN; /* Clear CRS SYNCWARN bit */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCWARN); } /* Check CRS TRIM overflow flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_TRIMOVF)) { /* CRS SYNC Error */ crsstatus |= RCC_CRS_TRIMOVF; /* Clear CRS Error bit */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_TRIMOVF); } /* Check CRS Error flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCERR)) { /* CRS SYNC Error */ crsstatus |= RCC_CRS_SYNCERR; /* Clear CRS Error bit */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCERR); } /* Check CRS SYNC Missed flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCMISS)) { /* CRS SYNC Missed */ crsstatus |= RCC_CRS_SYNCMISS; /* Clear CRS SYNC Missed bit */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCMISS); } /* Check CRS Expected SYNC flag */ if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_ESYNC)) { /* frequency error counter reached a zero value */ __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_ESYNC); } } while(RCC_CRS_NONE == crsstatus); return crsstatus; } /** * @brief Handle the Clock Recovery System interrupt request. * @retval None */ void HAL_RCCEx_CRS_IRQHandler(void) { uint32_t crserror = RCC_CRS_NONE; /* Get current IT flags and IT sources values */ uint32_t itflags = READ_REG(CRS->ISR); uint32_t itsources = READ_REG(CRS->CR); /* Check CRS SYNCOK flag */ if(((itflags & RCC_CRS_FLAG_SYNCOK) != 0U) && ((itsources & RCC_CRS_IT_SYNCOK) != 0U)) { /* Clear CRS SYNC event OK flag */ WRITE_REG(CRS->ICR, CRS_ICR_SYNCOKC); /* user callback */ HAL_RCCEx_CRS_SyncOkCallback(); } /* Check CRS SYNCWARN flag */ else if(((itflags & RCC_CRS_FLAG_SYNCWARN) != 0U) && ((itsources & RCC_CRS_IT_SYNCWARN) != 0U)) { /* Clear CRS SYNCWARN flag */ WRITE_REG(CRS->ICR, CRS_ICR_SYNCWARNC); /* user callback */ HAL_RCCEx_CRS_SyncWarnCallback(); } /* Check CRS Expected SYNC flag */ else if(((itflags & RCC_CRS_FLAG_ESYNC) != 0U) && ((itsources & RCC_CRS_IT_ESYNC) != 0U)) { /* frequency error counter reached a zero value */ WRITE_REG(CRS->ICR, CRS_ICR_ESYNCC); /* user callback */ HAL_RCCEx_CRS_ExpectedSyncCallback(); } /* Check CRS Error flags */ else { if(((itflags & RCC_CRS_FLAG_ERR) != 0U) && ((itsources & RCC_CRS_IT_ERR) != 0U)) { if((itflags & RCC_CRS_FLAG_SYNCERR) != 0U) { crserror |= RCC_CRS_SYNCERR; } if((itflags & RCC_CRS_FLAG_SYNCMISS) != 0U) { crserror |= RCC_CRS_SYNCMISS; } if((itflags & RCC_CRS_FLAG_TRIMOVF) != 0U) { crserror |= RCC_CRS_TRIMOVF; } /* Clear CRS Error flags */ WRITE_REG(CRS->ICR, CRS_ICR_ERRC); /* user error callback */ HAL_RCCEx_CRS_ErrorCallback(crserror); } } } /** * @brief RCCEx Clock Recovery System SYNCOK interrupt callback. * @retval none */ __weak void HAL_RCCEx_CRS_SyncOkCallback(void) { /* NOTE : This function should not be modified, when the callback is needed, the @ref HAL_RCCEx_CRS_SyncOkCallback should be implemented in the user file */ } /** * @brief RCCEx Clock Recovery System SYNCWARN interrupt callback. * @retval none */ __weak void HAL_RCCEx_CRS_SyncWarnCallback(void) { /* NOTE : This function should not be modified, when the callback is needed, the @ref HAL_RCCEx_CRS_SyncWarnCallback should be implemented in the user file */ } /** * @brief RCCEx Clock Recovery System Expected SYNC interrupt callback. * @retval none */ __weak void HAL_RCCEx_CRS_ExpectedSyncCallback(void) { /* NOTE : This function should not be modified, when the callback is needed, the @ref HAL_RCCEx_CRS_ExpectedSyncCallback should be implemented in the user file */ } /** * @brief RCCEx Clock Recovery System Error interrupt callback. * @param Error Combination of Error status. * This parameter can be a combination of the following values: * @arg @ref RCC_CRS_SYNCERR * @arg @ref RCC_CRS_SYNCMISS * @arg @ref RCC_CRS_TRIMOVF * @retval none */ __weak void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error) { /* Prevent unused argument(s) compilation warning */ UNUSED(Error); /* NOTE : This function should not be modified, when the callback is needed, the @ref HAL_RCCEx_CRS_ErrorCallback should be implemented in the user file */ } /** * @} */ #endif /* CRS */ /** * @} */ /** @addtogroup RCCEx_Private_Functions * @{ */ /** * @} */ /** * @} */ #endif /* HAL_RCC_MODULE_ENABLED */ /** * @} */ /** * @} */
62,528
C
33.243702
136
0.581771
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
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_timebase_tim_template.c
/** ****************************************************************************** * @file stm32g4xx_hal_timebase_tim_template.c * @author MCD Application Team * @brief HAL time base based on the hardware TIM Template. * * This file override the native HAL time base functions (defined as weak) * the TIM time base: * + Initializes the TIM peripheral to generate a Period elapsed Event each 1ms * + HAL_IncTick is called inside HAL_TIM_PeriodElapsedCallback ie each 1ms ****************************************************************************** * @attention * * Copyright (c) 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 file must be copied to the application folder and modified as follows: (#) Rename it to 'stm32g4xx_hal_timebase_tim.c' (#) Add this file and the TIM HAL driver files to your project and make sure HAL_TIM_MODULE_ENABLED is defined in stm32g4xx_hal_conf.h [..] (@) The application needs to ensure that the time base is always set to 1 millisecond to have correct HAL operation. @endverbatim ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup HAL_TimeBase * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ TIM_HandleTypeDef TimHandle; /* Private function prototypes -----------------------------------------------*/ void TIM6_DAC_IRQHandler(void); /* Private functions ---------------------------------------------------------*/ /** * @brief This function configures the TIM6 as a time base source. * The time source is configured to have 1ms time base with a dedicated * Tick interrupt priority. * @note This function is called automatically at the beginning of program after * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). * @param TickPriority: Tick interrupt priority. * @retval HAL status */ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { RCC_ClkInitTypeDef clkconfig; uint32_t uwTimclock; uint32_t uwAPB1Prescaler; uint32_t uwPrescalerValue; uint32_t pFLatency; HAL_StatusTypeDef status; /* Configure the TIM6 IRQ priority */ HAL_NVIC_SetPriority(TIM6_DAC_IRQn, TickPriority, 0U); /* Enable the TIM6 global Interrupt */ HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn); /* Enable TIM6 clock */ __HAL_RCC_TIM6_CLK_ENABLE(); /* Get clock configuration */ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); /* Get APB1 prescaler */ uwAPB1Prescaler = clkconfig.APB1CLKDivider; /* Compute TIM6 clock */ if (uwAPB1Prescaler == RCC_HCLK_DIV1) { uwTimclock = HAL_RCC_GetPCLK1Freq(); } else { uwTimclock = 2U * HAL_RCC_GetPCLK1Freq(); } /* Compute the prescaler value to have TIM6 counter clock equal to 1MHz */ uwPrescalerValue = (uint32_t)((uwTimclock / 1000000U) - 1U); /* Initialize TIM6 */ TimHandle.Instance = TIM6; /* Initialize TIMx peripheral as follow: + Period = [(TIM6CLK/1000) - 1]. to have a (1/1000) s time base. + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + ClockDivision = 0 + Counter direction = Up */ TimHandle.Init.Period = (1000000U / 1000U) - 1U; TimHandle.Init.Prescaler = uwPrescalerValue; TimHandle.Init.ClockDivision = 0; TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; status = HAL_TIM_Base_Init(&TimHandle); if (status == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ status = HAL_TIM_Base_Start_IT(&TimHandle); if (status == HAL_OK) { /* Configure the SysTick IRQ priority */ if (TickPriority < (1UL << __NVIC_PRIO_BITS)) { /* Configure the TIM IRQ priority */ HAL_NVIC_SetPriority(TIM6_DAC_IRQn, TickPriority, 0U); uwTickPrio = TickPriority; } else { status = HAL_ERROR; } } } /* Return function status */ return status; } /** * @brief Suspend Tick increment. * @note Disable the tick increment by disabling TIM6 update interrupt. * @param None * @retval None */ void HAL_SuspendTick(void) { /* Disable TIM6 update interrupt */ __HAL_TIM_DISABLE_IT(&TimHandle, TIM_IT_UPDATE); } /** * @brief Resume Tick increment. * @note Enable the tick increment by enabling TIM6 update interrupt. * @param None * @retval None */ void HAL_ResumeTick(void) { /* Enable TIM6 update interrupt */ __HAL_TIM_ENABLE_IT(&TimHandle, TIM_IT_UPDATE); } /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM6 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { HAL_IncTick(); } /** * @brief This function handles TIM interrupt request. * @param None * @retval None */ void TIM6_DAC_IRQHandler(void) { HAL_TIM_IRQHandler(&TimHandle); } /** * @} */ /** * @} */
6,177
C
30.045226
98
0.558524
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_flash.c
/** ****************************************************************************** * @file stm32g4xx_hal_flash.c * @author MCD Application Team * @brief FLASH HAL module driver. * This file provides firmware functions to manage the following * functionalities of the internal FLASH memory: * + Program operations functions * + Memory Control functions * + Peripheral Errors functions * @verbatim ============================================================================== ##### FLASH peripheral features ##### ============================================================================== [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses to the Flash memory. It implements the erase and program Flash memory operations and the read and write protection mechanisms. [..] The Flash memory interface accelerates code execution with a system of instruction prefetch and cache lines. [..] The FLASH main features are: (+) Flash memory read operations (+) Flash memory program/erase operations (+) Read / write protections (+) Option bytes programming (+) Prefetch on I-Code (+) 32 cache lines of 4*64 or 2*128 bits on I-Code (+) 8 cache lines of 4*64 or 2*128 bits on D-Code (+) Error code correction (ECC) : Data in flash are 72-bits word (8 bits added per double word) ##### How to use this driver ##### ============================================================================== [..] This driver provides functions and macros to configure and program the FLASH memory of all STM32G4xx devices. (#) Flash Memory IO Programming functions: (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and HAL_FLASH_Lock() functions (++) Program functions: double word and fast program (full row programming) (++) There are two modes of programming : (+++) Polling mode using HAL_FLASH_Program() function (+++) Interrupt mode using HAL_FLASH_Program_IT() function (#) Interrupts and flags management functions: (++) Handle FLASH interrupts by calling HAL_FLASH_IRQHandler() (++) Callback functions are called when the flash operations are finished : HAL_FLASH_EndOfOperationCallback() when everything is ok, otherwise HAL_FLASH_OperationErrorCallback() (++) Get error flag status by calling HAL_GetError() (#) Option bytes management functions: (++) Lock and Unlock the option bytes using HAL_FLASH_OB_Unlock() and HAL_FLASH_OB_Lock() functions (++) Launch the reload of the option bytes using HAL_FLASH_Launch() function. In this case, a reset is generated [..] In addition to these functions, this driver includes a set of macros allowing to handle the following operations: (+) Set the latency (+) Enable/Disable the prefetch buffer (+) Enable/Disable the Instruction cache and the Data cache (+) Reset the Instruction cache and the Data cache (+) Enable/Disable the Flash power-down during low-power run and sleep modes (+) Enable/Disable the Flash interrupts (+) Monitor the Flash flags status @endverbatim ****************************************************************************** * @attention * * Copyright (c) 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 FLASH FLASH * @brief FLASH HAL module driver * @{ */ #ifdef HAL_FLASH_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /** @defgroup FLASH_Private_Constants FLASH Private Constants * @{ */ #define FLASH_NB_DOUBLE_WORDS_IN_ROW 32 /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Variables FLASH Private Variables * @{ */ /** * @brief Variable used for Program/Erase sectors under interruption */ FLASH_ProcessTypeDef pFlash = {.Lock = HAL_UNLOCKED, .ErrorCode = HAL_FLASH_ERROR_NONE, .ProcedureOnGoing = FLASH_PROC_NONE, .Address = 0U, .Bank = FLASH_BANK_1, .Page = 0U, .NbPagesToErase = 0U, .CacheToReactivate = FLASH_CACHE_DISABLED}; /** * @} */ /* Private function prototypes -----------------------------------------------*/ /** @defgroup FLASH_Private_Functions FLASH Private Functions * @{ */ static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data); static void FLASH_Program_Fast(uint32_t Address, uint32_t DataAddress); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Functions FLASH Exported Functions * @{ */ /** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions * @brief Programming operation functions * @verbatim =============================================================================== ##### Programming operation functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the FLASH program operations. @endverbatim * @{ */ /** * @brief Program double word or fast program of a row at a specified address. * @param TypeProgram Indicate the way to program at a specified address. * This parameter can be a value of @ref FLASH_Type_Program. * @param Address specifies the address to be programmed. * @param Data specifies the data to be programmed. * This parameter is the data for the double word program and the address where * are stored the data for the row fast program. * * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data) { HAL_StatusTypeDef status; uint32_t prog_bit = 0; /* Check the parameters */ assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); /* Process Locked */ __HAL_LOCK(&pFlash); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; if (TypeProgram == FLASH_TYPEPROGRAM_DOUBLEWORD) { /* Program double-word (64-bit) at a specified address */ FLASH_Program_DoubleWord(Address, Data); prog_bit = FLASH_CR_PG; } else if ((TypeProgram == FLASH_TYPEPROGRAM_FAST) || (TypeProgram == FLASH_TYPEPROGRAM_FAST_AND_LAST)) { /* Fast program a 32 row double-word (64-bit) at a specified address */ FLASH_Program_Fast(Address, (uint32_t)Data); /* If it is the last row, the bit will be cleared at the end of the operation */ if (TypeProgram == FLASH_TYPEPROGRAM_FAST_AND_LAST) { prog_bit = FLASH_CR_FSTPG; } } else { /* Nothing to do */ } /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); /* If the program operation is completed, disable the PG or FSTPG Bit */ if (prog_bit != 0U) { CLEAR_BIT(FLASH->CR, prog_bit); } } /* Process Unlocked */ __HAL_UNLOCK(&pFlash); /* return status */ return status; } /** * @brief Program double word or fast program of a row at a specified address with interrupt enabled. * @param TypeProgram Indicate the way to program at a specified address. * This parameter can be a value of @ref FLASH_Type_Program. * @param Address specifies the address to be programmed. * @param Data specifies the data to be programmed. * This parameter is the data for the double word program and the address where * are stored the data for the row fast program. * * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data) { HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); /* Process Locked */ __HAL_LOCK(&pFlash); /* Reset error code */ pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); if (status != HAL_OK) { /* Process Unlocked */ __HAL_UNLOCK(&pFlash); } else { /* Set internal variables used by the IRQ handler */ if (TypeProgram == FLASH_TYPEPROGRAM_FAST_AND_LAST) { pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM_LAST; } else { pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM; } pFlash.Address = Address; /* Enable End of Operation and Error interrupts */ __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_OPERR); if (TypeProgram == FLASH_TYPEPROGRAM_DOUBLEWORD) { /* Program double-word (64-bit) at a specified address */ FLASH_Program_DoubleWord(Address, Data); } else if ((TypeProgram == FLASH_TYPEPROGRAM_FAST) || (TypeProgram == FLASH_TYPEPROGRAM_FAST_AND_LAST)) { /* Fast program a 32 row double-word (64-bit) at a specified address */ FLASH_Program_Fast(Address, (uint32_t)Data); } else { /* Nothing to do */ } } return status; } /** * @brief Handle FLASH interrupt request. * @retval None */ void HAL_FLASH_IRQHandler(void) { uint32_t tmp_page; uint32_t error; FLASH_ProcedureTypeDef procedure; /* If the operation is completed, disable the PG, PNB, MER1, MER2 and PER Bit */ CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_MER1 | FLASH_CR_PER | FLASH_CR_PNB)); #if defined (FLASH_OPTR_DBANK) CLEAR_BIT(FLASH->CR, FLASH_CR_MER2); #endif /* Disable the FSTPG Bit only if it is the last row programmed */ if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAM_LAST) { CLEAR_BIT(FLASH->CR, FLASH_CR_FSTPG); } /* Check FLASH operation error flags */ error = (FLASH->SR & FLASH_FLAG_SR_ERRORS); if (error != 0U) { /* Save the error code */ pFlash.ErrorCode |= error; /* Clear error programming flags */ __HAL_FLASH_CLEAR_FLAG(error); /* Flush the caches to be sure of the data consistency */ FLASH_FlushCaches() ; /* FLASH error interrupt user callback */ procedure = pFlash.ProcedureOnGoing; if (procedure == FLASH_PROC_PAGE_ERASE) { HAL_FLASH_OperationErrorCallback(pFlash.Page); } else if (procedure == FLASH_PROC_MASS_ERASE) { HAL_FLASH_OperationErrorCallback(pFlash.Bank); } else if ((procedure == FLASH_PROC_PROGRAM) || (procedure == FLASH_PROC_PROGRAM_LAST)) { HAL_FLASH_OperationErrorCallback(pFlash.Address); } else { /* Nothing to do */ } /*Stop the procedure ongoing*/ pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } /* Check FLASH End of Operation flag */ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) { /* Clear FLASH End of Operation pending bit */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); if (pFlash.ProcedureOnGoing == FLASH_PROC_PAGE_ERASE) { /* Nb of pages to erased can be decreased */ pFlash.NbPagesToErase--; /* Check if there are still pages to erase*/ if (pFlash.NbPagesToErase != 0U) { /* Indicate user which page has been erased*/ HAL_FLASH_EndOfOperationCallback(pFlash.Page); /* Increment page number */ pFlash.Page++; tmp_page = pFlash.Page; FLASH_PageErase(tmp_page, pFlash.Bank); } else { /* No more pages to Erase */ /* Reset Address and stop Erase pages procedure */ pFlash.Page = 0xFFFFFFFFU; pFlash.ProcedureOnGoing = FLASH_PROC_NONE; /* Flush the caches to be sure of the data consistency */ FLASH_FlushCaches() ; /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(pFlash.Page); } } else { /* Flush the caches to be sure of the data consistency */ FLASH_FlushCaches() ; procedure = pFlash.ProcedureOnGoing; if (procedure == FLASH_PROC_MASS_ERASE) { /* MassErase ended. Return the selected bank */ /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(pFlash.Bank); } else if ((procedure == FLASH_PROC_PROGRAM) || (procedure == FLASH_PROC_PROGRAM_LAST)) { /* Program ended. Return the selected address */ /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(pFlash.Address); } else { /* Nothing to do */ } /*Clear the procedure ongoing*/ pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } } if (pFlash.ProcedureOnGoing == FLASH_PROC_NONE) { /* Disable End of Operation and Error interrupts */ __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP | FLASH_IT_OPERR); /* Process Unlocked */ __HAL_UNLOCK(&pFlash); } } /** * @brief FLASH end of operation interrupt callback. * @param ReturnValue The value saved in this parameter depends on the ongoing procedure: * @arg Mass Erase: Bank number which has been requested to erase * @arg Page Erase: Page which has been erased * (if 0xFFFFFFFF, it means that all the selected pages have been erased) * @arg Program: Address which was selected for data program * @retval None */ __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) { /* Prevent unused argument(s) compilation warning */ UNUSED(ReturnValue); /* NOTE : This function should not be modified, when the callback is needed, the HAL_FLASH_EndOfOperationCallback could be implemented in the user file */ } /** * @brief FLASH operation error interrupt callback. * @param ReturnValue The value saved in this parameter depends on the ongoing procedure: * @arg Mass Erase: Bank number which has been requested to erase * @arg Page Erase: Page number which returned an error * @arg Program: Address which was selected for data program * @retval None */ __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) { /* Prevent unused argument(s) compilation warning */ UNUSED(ReturnValue); /* NOTE : This function should not be modified, when the callback is needed, the HAL_FLASH_OperationErrorCallback could be implemented in the user file */ } /** * @} */ /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions * @brief Management functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the FLASH memory operations. @endverbatim * @{ */ /** * @brief Unlock the FLASH control register access. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_Unlock(void) { HAL_StatusTypeDef status = HAL_OK; if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) { /* Authorize the FLASH Registers access */ WRITE_REG(FLASH->KEYR, FLASH_KEY1); WRITE_REG(FLASH->KEYR, FLASH_KEY2); /* verify Flash is unlocked */ if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) { status = HAL_ERROR; } } return status; } /** * @brief Lock the FLASH control register access. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_Lock(void) { HAL_StatusTypeDef status = HAL_ERROR; /* Set the LOCK Bit to lock the FLASH Registers access */ SET_BIT(FLASH->CR, FLASH_CR_LOCK); /* verify Flash is locked */ if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) { status = HAL_OK; } return status; } /** * @brief Unlock the FLASH Option Bytes Registers access. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) { HAL_StatusTypeDef status = HAL_OK; if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0U) { /* Authorizes the Option Byte register programming */ WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1); WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2); /* verify option bytes are unlocked */ if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0U) { status = HAL_ERROR; } } return status; } /** * @brief Lock the FLASH Option Bytes Registers access. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) { HAL_StatusTypeDef status = HAL_ERROR; /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */ SET_BIT(FLASH->CR, FLASH_CR_OPTLOCK); /* Verify option bytes are locked */ if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0U) { status = HAL_OK; } return status; } /** * @brief Launch the option byte loading. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) { /* Set the bit to force the option byte reloading */ SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH); /* Wait for last operation to be completed */ return (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE)); } /** * @} */ /** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions * @brief Peripheral Errors functions * @verbatim =============================================================================== ##### Peripheral Errors functions ##### =============================================================================== [..] This subsection permits to get in run-time Errors of the FLASH peripheral. @endverbatim * @{ */ /** * @brief Get the specific FLASH error flag. * @retval FLASH_ErrorCode. The returned value can be: * @arg HAL_FLASH_ERROR_RD: FLASH Read Protection error flag (PCROP) * @arg HAL_FLASH_ERROR_PGS: FLASH Programming Sequence error flag * @arg HAL_FLASH_ERROR_PGP: FLASH Programming Parallelism error flag * @arg HAL_FLASH_ERROR_PGA: FLASH Programming Alignment error flag * @arg HAL_FLASH_ERROR_WRP: FLASH Write protected error flag * @arg HAL_FLASH_ERROR_OPERATION: FLASH operation Error flag * @arg HAL_FLASH_ERROR_NONE: No error set * @arg HAL_FLASH_ERROR_OP: FLASH Operation error * @arg HAL_FLASH_ERROR_PROG: FLASH Programming error * @arg HAL_FLASH_ERROR_WRP: FLASH Write protection error * @arg HAL_FLASH_ERROR_PGA: FLASH Programming alignment error * @arg HAL_FLASH_ERROR_SIZ: FLASH Size error * @arg HAL_FLASH_ERROR_PGS: FLASH Programming sequence error * @arg HAL_FLASH_ERROR_MIS: FLASH Fast programming data miss error * @arg HAL_FLASH_ERROR_FAST: FLASH Fast programming error * @arg HAL_FLASH_ERROR_RD: FLASH PCROP read error * @arg HAL_FLASH_ERROR_OPTV: FLASH Option validity error */ uint32_t HAL_FLASH_GetError(void) { return pFlash.ErrorCode; } /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @addtogroup FLASH_Private_Functions * @{ */ /** * @brief Wait for a FLASH operation to complete. * @param Timeout maximum flash operation timeout. * @retval HAL_Status */ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) { /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset. Even if the FLASH operation fails, the BUSY flag will be reset and an error flag will be set */ uint32_t tickstart = HAL_GetTick(); uint32_t error; while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) { if ((HAL_GetTick() - tickstart) > Timeout) { return HAL_TIMEOUT; } } /* Check FLASH operation error flags */ error = (FLASH->SR & FLASH_FLAG_SR_ERRORS); if (error != 0u) { /* Save the error code */ pFlash.ErrorCode |= error; /* Clear error programming flags */ __HAL_FLASH_CLEAR_FLAG(error); return HAL_ERROR; } /* Check FLASH End of Operation flag */ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) { /* Clear FLASH End of Operation pending bit */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); } /* If there is an error flag set */ return HAL_OK; } /** * @brief Program double-word (64-bit) at a specified address. * @param Address specifies the address to be programmed. * @param Data specifies the data to be programmed. * @retval None */ static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data) { /* Check the parameters */ assert_param(IS_FLASH_PROGRAM_ADDRESS(Address)); /* Set PG bit */ SET_BIT(FLASH->CR, FLASH_CR_PG); /* Program first word */ *(uint32_t *)Address = (uint32_t)Data; /* Barrier to ensure programming is performed in 2 steps, in right order (independently of compiler optimization behavior) */ __ISB(); /* Program second word */ *(uint32_t *)(Address + 4U) = (uint32_t)(Data >> 32U); } /** * @brief Fast program a row double-word (64-bit) at a specified address. * @param Address specifies the address to be programmed. * @param DataAddress specifies the address where the data are stored. * @retval None */ static void FLASH_Program_Fast(uint32_t Address, uint32_t DataAddress) { uint8_t row_index = (2 * FLASH_NB_DOUBLE_WORDS_IN_ROW); uint32_t *dest_addr = (uint32_t *)Address; uint32_t *src_addr = (uint32_t *)DataAddress; uint32_t primask_bit; /* Check the parameters */ assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); /* Set FSTPG bit */ SET_BIT(FLASH->CR, FLASH_CR_FSTPG); /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ primask_bit = __get_PRIMASK(); __disable_irq(); /* Program the double words of the row */ do { *dest_addr = *src_addr; dest_addr++; src_addr++; row_index--; } while (row_index != 0U); /* Exit critical section: restore previous priority mask */ __set_PRIMASK(primask_bit); } /** * @} */ #endif /* HAL_FLASH_MODULE_ENABLED */ /** * @} */ /** * @} */
23,232
C
29.211964
105
0.596333
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_flash_ex.c
/** ****************************************************************************** * @file stm32g4xx_hal_flash_ex.c * @author MCD Application Team * @brief Extended FLASH HAL module driver. * This file provides firmware functions to manage the following * functionalities of the FLASH extended peripheral: * + Extended programming operations functions * @verbatim ============================================================================== ##### Flash Extended features ##### ============================================================================== [..] Comparing to other previous devices, the FLASH interface for STM32G4xx devices contains the following additional features (+) Capacity up to 512 Kbytes with dual bank architecture supporting read-while-write capability (RWW) (+) Dual bank 64-bits memory organization with possibility of single bank 128-bits (+) Protected areas including WRP, PCROP and Securable memory ##### How to use this driver ##### ============================================================================== [..] This driver provides functions to configure and program the FLASH memory of all STM32G4xx devices. It includes (#) Flash Memory Erase functions: (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and HAL_FLASH_Lock() functions (++) Erase function: Erase pages, or mass erase banks (++) There are two modes of erase : (+++) Polling Mode using HAL_FLASHEx_Erase() (+++) Interrupt Mode using HAL_FLASHEx_Erase_IT() (#) Option Bytes Programming function: Use HAL_FLASHEx_OBProgram() to: (++) Configure the write protection areas (WRP) (++) Set the Read protection Level (RDP) (++) Program the user Option Bytes (++) Configure the Proprietary Code ReadOut protection areas (PCROP) (++) Configure the Securable memory areas (++) Configure the Boot Lock (#) Get Option Bytes Configuration function: Use HAL_FLASHEx_OBGetConfig() to: (++) Get the configuration of write protection areas (WRP) (++) Get the level of read protection (RDP) (++) Get the value of the user Option Bytes (++) Get the configuration of Proprietary Code ReadOut Protection areas (PCROP) (++) Get the configuration of Securable memory areas (++) Get the status of Boot Lock (#) Activation of Securable memory area: Use HAL_FLASHEx_EnableSecMemProtection() (++) Deny the access to securable memory area (#) Enable or disable debugger: Use HAL_FLASHEx_EnableDebugger() or HAL_FLASHEx_DisableDebugger() @endverbatim ****************************************************************************** * @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 FLASHEx FLASHEx * @brief FLASH Extended HAL module driver * @{ */ #ifdef HAL_FLASH_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup FLASHEx_Private_Functions FLASHEx Private Functions * @{ */ static void FLASH_MassErase(uint32_t Banks); static HAL_StatusTypeDef FLASH_OB_WRPConfig(uint32_t WRPArea, uint32_t WRPStartOffset, uint32_t WRDPEndOffset); static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint32_t RDPLevel); static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig); static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t PCROPConfig, uint32_t PCROPStartAddr, uint32_t PCROPEndAddr); static void FLASH_OB_GetWRP(uint32_t WRPArea, uint32_t *WRPStartOffset, uint32_t *WRDPEndOffset); static uint32_t FLASH_OB_GetRDP(void); static uint32_t FLASH_OB_GetUser(void); static void FLASH_OB_GetPCROP(uint32_t *PCROPConfig, uint32_t *PCROPStartAddr, uint32_t *PCROPEndAddr); static HAL_StatusTypeDef FLASH_OB_SecMemConfig(uint32_t SecMemBank, uint32_t SecMemSize); static void FLASH_OB_GetSecMem(uint32_t SecMemBank, uint32_t *SecMemSize); static HAL_StatusTypeDef FLASH_OB_BootLockConfig(uint32_t BootLockConfig); static uint32_t FLASH_OB_GetBootLock(void); /** * @} */ /* Exported functions -------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Functions FLASHEx Exported Functions * @{ */ /** @defgroup FLASHEx_Exported_Functions_Group1 Extended IO operation functions * @brief Extended IO operation functions * @verbatim =============================================================================== ##### Extended programming operation functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the Extended FLASH programming operations Operations. @endverbatim * @{ */ /** * @brief Perform a mass erase or erase the specified FLASH memory pages. * @param[in] pEraseInit pointer to an FLASH_EraseInitTypeDef structure that * contains the configuration information for the erasing. * @param[out] PageError pointer to variable that contains the configuration * information on faulty page in case of error (0xFFFFFFFF means that all * the pages have been correctly erased). * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) { HAL_StatusTypeDef status; uint32_t page_index; /* Check the parameters */ assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); /* Process Locked */ __HAL_LOCK(&pFlash); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; /* Deactivate the cache if they are activated to avoid data misbehavior */ if (READ_BIT(FLASH->ACR, FLASH_ACR_ICEN) != 0U) { if (READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) != 0U) { /* Disable data cache */ __HAL_FLASH_DATA_CACHE_DISABLE(); pFlash.CacheToReactivate = FLASH_CACHE_ICACHE_DCACHE_ENABLED; } else { pFlash.CacheToReactivate = FLASH_CACHE_ICACHE_ENABLED; } } else if (READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) != 0U) { /* Disable data cache */ __HAL_FLASH_DATA_CACHE_DISABLE(); pFlash.CacheToReactivate = FLASH_CACHE_DCACHE_ENABLED; } else { pFlash.CacheToReactivate = FLASH_CACHE_DISABLED; } if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) { /* Mass erase to be done */ FLASH_MassErase(pEraseInit->Banks); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); #if defined (FLASH_OPTR_DBANK) /* If the erase operation is completed, disable the MER1 and MER2 Bits */ CLEAR_BIT(FLASH->CR, (FLASH_CR_MER1 | FLASH_CR_MER2)); #else /* If the erase operation is completed, disable the MER1 Bit */ CLEAR_BIT(FLASH->CR, (FLASH_CR_MER1)); #endif } else { /*Initialization of PageError variable*/ *PageError = 0xFFFFFFFFU; for (page_index = pEraseInit->Page; page_index < (pEraseInit->Page + pEraseInit->NbPages); page_index++) { FLASH_PageErase(page_index, pEraseInit->Banks); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); /* If the erase operation is completed, disable the PER Bit */ CLEAR_BIT(FLASH->CR, (FLASH_CR_PER | FLASH_CR_PNB)); if (status != HAL_OK) { /* In case of error, stop erase procedure and return the faulty page */ *PageError = page_index; break; } } } /* Flush the caches to be sure of the data consistency */ FLASH_FlushCaches(); } /* Process Unlocked */ __HAL_UNLOCK(&pFlash); return status; } /** * @brief Perform a mass erase or erase the specified FLASH memory pages with interrupt enabled. * @param pEraseInit pointer to an FLASH_EraseInitTypeDef structure that * contains the configuration information for the erasing. * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) { HAL_StatusTypeDef status = HAL_OK; /* Process Locked */ __HAL_LOCK(&pFlash); /* Check the parameters */ assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; /* Deactivate the cache if they are activated to avoid data misbehavior */ if (READ_BIT(FLASH->ACR, FLASH_ACR_ICEN) != 0U) { if (READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) != 0U) { /* Disable data cache */ __HAL_FLASH_DATA_CACHE_DISABLE(); pFlash.CacheToReactivate = FLASH_CACHE_ICACHE_DCACHE_ENABLED; } else { pFlash.CacheToReactivate = FLASH_CACHE_ICACHE_ENABLED; } } else if (READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) != 0U) { /* Disable data cache */ __HAL_FLASH_DATA_CACHE_DISABLE(); pFlash.CacheToReactivate = FLASH_CACHE_DCACHE_ENABLED; } else { pFlash.CacheToReactivate = FLASH_CACHE_DISABLED; } /* Enable End of Operation and Error interrupts */ __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_OPERR); pFlash.Bank = pEraseInit->Banks; if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) { /* Mass erase to be done */ pFlash.ProcedureOnGoing = FLASH_PROC_MASS_ERASE; FLASH_MassErase(pEraseInit->Banks); } else { /* Erase by page to be done */ pFlash.ProcedureOnGoing = FLASH_PROC_PAGE_ERASE; pFlash.NbPagesToErase = pEraseInit->NbPages; pFlash.Page = pEraseInit->Page; /*Erase 1st page and wait for IT */ FLASH_PageErase(pEraseInit->Page, pEraseInit->Banks); } return status; } /** * @brief Program Option bytes. * @param pOBInit pointer to an FLASH_OBInitStruct structure that * contains the configuration information for the programming. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @retval HAL_Status */ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit) { HAL_StatusTypeDef status = HAL_OK; /* Check the parameters */ assert_param(IS_OPTIONBYTE(pOBInit->OptionType)); /* Process Locked */ __HAL_LOCK(&pFlash); pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; /* Write protection configuration */ if ((pOBInit->OptionType & OPTIONBYTE_WRP) != 0U) { /* Configure of Write protection on the selected area */ if (FLASH_OB_WRPConfig(pOBInit->WRPArea, pOBInit->WRPStartOffset, pOBInit->WRPEndOffset) != HAL_OK) { status = HAL_ERROR; } } /* Read protection configuration */ if ((pOBInit->OptionType & OPTIONBYTE_RDP) != 0U) { /* Configure the Read protection level */ if (FLASH_OB_RDPConfig(pOBInit->RDPLevel) != HAL_OK) { status = HAL_ERROR; } } /* User Configuration */ if ((pOBInit->OptionType & OPTIONBYTE_USER) != 0U) { /* Configure the user option bytes */ if (FLASH_OB_UserConfig(pOBInit->USERType, pOBInit->USERConfig) != HAL_OK) { status = HAL_ERROR; } } /* PCROP Configuration */ if ((pOBInit->OptionType & OPTIONBYTE_PCROP) != 0U) { if (pOBInit->PCROPStartAddr != pOBInit->PCROPEndAddr) { /* Configure the Proprietary code readout protection */ if (FLASH_OB_PCROPConfig(pOBInit->PCROPConfig, pOBInit->PCROPStartAddr, pOBInit->PCROPEndAddr) != HAL_OK) { status = HAL_ERROR; } } } /* Securable memory Configuration */ if ((pOBInit->OptionType & OPTIONBYTE_SEC) != 0U) { /* Configure the securable memory area */ if (FLASH_OB_SecMemConfig(pOBInit->SecBank, pOBInit->SecSize) != HAL_OK) { status = HAL_ERROR; } } /* Boot Entry Point Configuration */ if ((pOBInit->OptionType & OPTIONBYTE_BOOT_LOCK) != 0U) { /* Configure the boot unique entry point option */ if (FLASH_OB_BootLockConfig(pOBInit->BootEntryPoint) != HAL_OK) { status = HAL_ERROR; } } /* Process Unlocked */ __HAL_UNLOCK(&pFlash); return status; } /** * @brief Get the Option bytes configuration. * @param pOBInit pointer to an FLASH_OBInitStruct structure that contains the * configuration information. * @note The fields pOBInit->WRPArea and pOBInit->PCROPConfig should indicate * which area is requested for the WRP and PCROP, else no information will be returned. * @retval None */ void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) { pOBInit->OptionType = (OPTIONBYTE_RDP | OPTIONBYTE_USER); #if defined (FLASH_OPTR_DBANK) if ((pOBInit->WRPArea == OB_WRPAREA_BANK1_AREAA) || (pOBInit->WRPArea == OB_WRPAREA_BANK1_AREAB) || (pOBInit->WRPArea == OB_WRPAREA_BANK2_AREAA) || (pOBInit->WRPArea == OB_WRPAREA_BANK2_AREAB)) #else if ((pOBInit->WRPArea == OB_WRPAREA_BANK1_AREAA) || (pOBInit->WRPArea == OB_WRPAREA_BANK1_AREAB)) #endif { pOBInit->OptionType |= OPTIONBYTE_WRP; /* Get write protection on the selected area */ FLASH_OB_GetWRP(pOBInit->WRPArea, &(pOBInit->WRPStartOffset), &(pOBInit->WRPEndOffset)); } /* Get Read protection level */ pOBInit->RDPLevel = FLASH_OB_GetRDP(); /* Get the user option bytes */ pOBInit->USERConfig = FLASH_OB_GetUser(); #if defined (FLASH_OPTR_DBANK) if ((pOBInit->PCROPConfig == FLASH_BANK_1) || (pOBInit->PCROPConfig == FLASH_BANK_2)) #else if (pOBInit->PCROPConfig == FLASH_BANK_1) #endif { pOBInit->OptionType |= OPTIONBYTE_PCROP; /* Get the Proprietary code readout protection */ FLASH_OB_GetPCROP(&(pOBInit->PCROPConfig), &(pOBInit->PCROPStartAddr), &(pOBInit->PCROPEndAddr)); } pOBInit->OptionType |= OPTIONBYTE_BOOT_LOCK; /* Get the boot entry point */ pOBInit->BootEntryPoint = FLASH_OB_GetBootLock(); /* Get the securable memory area configuration */ #if defined (FLASH_OPTR_DBANK) if ((pOBInit->SecBank == FLASH_BANK_1) || (pOBInit->SecBank == FLASH_BANK_2)) #else if (pOBInit->SecBank == FLASH_BANK_1) #endif { pOBInit->OptionType |= OPTIONBYTE_SEC; FLASH_OB_GetSecMem(pOBInit->SecBank, &(pOBInit->SecSize)); } } /** * @brief Enable the FLASH Securable Memory protection. * @param Bank: Bank to be protected * This parameter can be one of the following values: * @arg FLASH_BANK_1: Bank1 to be protected * @arg FLASH_BANK_2: Bank2 to be protected (*) * @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be protected (*) * @note (*) availability depends on devices * @retval HAL Status */ HAL_StatusTypeDef HAL_FLASHEx_EnableSecMemProtection(uint32_t Bank) { #if defined (FLASH_OPTR_DBANK) if (READ_BIT(FLASH->OPTR, FLASH_OPTR_DBANK) != 0U) { /* Check the parameters */ assert_param(IS_FLASH_BANK(Bank)); /* Enable the Securable Memory Protection Bit for the bank 1 if requested */ if ((Bank & FLASH_BANK_1) != 0U) { SET_BIT(FLASH->CR, FLASH_CR_SEC_PROT1); } /* Enable the Securable Memory Protection Bit for the bank 2 if requested */ if ((Bank & FLASH_BANK_2) != 0U) { SET_BIT(FLASH->CR, FLASH_CR_SEC_PROT2); } } else #endif { SET_BIT(FLASH->CR, FLASH_CR_SEC_PROT1); } return HAL_OK; } /** * @brief Enable Debugger. * @note After calling this API, flash interface allow debugger intrusion. * @retval None */ void HAL_FLASHEx_EnableDebugger(void) { FLASH->ACR |= FLASH_ACR_DBG_SWEN; } /** * @brief Disable Debugger. * @note After calling this API, Debugger is disabled: it's no more possible to * break, see CPU register, etc... * @retval None */ void HAL_FLASHEx_DisableDebugger(void) { FLASH->ACR &= ~FLASH_ACR_DBG_SWEN; } /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @addtogroup FLASHEx_Private_Functions * @{ */ /** * @brief Mass erase of FLASH memory. * @param Banks Banks to be erased. * This parameter can be one of the following values: * @arg FLASH_BANK_1: Bank1 to be erased * @arg FLASH_BANK_2: Bank2 to be erased (*) * @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be erased (*) * @note (*) availability depends on devices * @retval None */ static void FLASH_MassErase(uint32_t Banks) { #if defined (FLASH_OPTR_DBANK) if (READ_BIT(FLASH->OPTR, FLASH_OPTR_DBANK) != 0U) #endif { /* Check the parameters */ assert_param(IS_FLASH_BANK(Banks)); /* Set the Mass Erase Bit for the bank 1 if requested */ if ((Banks & FLASH_BANK_1) != 0U) { SET_BIT(FLASH->CR, FLASH_CR_MER1); } #if defined (FLASH_OPTR_DBANK) /* Set the Mass Erase Bit for the bank 2 if requested */ if ((Banks & FLASH_BANK_2) != 0U) { SET_BIT(FLASH->CR, FLASH_CR_MER2); } #endif } #if defined (FLASH_OPTR_DBANK) else { SET_BIT(FLASH->CR, (FLASH_CR_MER1 | FLASH_CR_MER2)); } #endif /* Proceed to erase all sectors */ SET_BIT(FLASH->CR, FLASH_CR_STRT); } /** * @brief Erase the specified FLASH memory page. * @param Page FLASH page to erase. * This parameter must be a value between 0 and (max number of pages in the bank - 1). * @param Banks Bank where the page will be erased. * This parameter can be one of the following values: * @arg FLASH_BANK_1: Page in bank 1 to be erased * @arg FLASH_BANK_2: Page in bank 2 to be erased (*) * @note (*) availability depends on devices * @retval None */ void FLASH_PageErase(uint32_t Page, uint32_t Banks) { /* Check the parameters */ assert_param(IS_FLASH_PAGE(Page)); #if defined (FLASH_OPTR_DBANK) if (READ_BIT(FLASH->OPTR, FLASH_OPTR_DBANK) == 0U) { CLEAR_BIT(FLASH->CR, FLASH_CR_BKER); } else { assert_param(IS_FLASH_BANK_EXCLUSIVE(Banks)); if ((Banks & FLASH_BANK_1) != 0U) { CLEAR_BIT(FLASH->CR, FLASH_CR_BKER); } else { SET_BIT(FLASH->CR, FLASH_CR_BKER); } } #endif /* Proceed to erase the page */ MODIFY_REG(FLASH->CR, FLASH_CR_PNB, ((Page & 0xFFU) << FLASH_CR_PNB_Pos)); SET_BIT(FLASH->CR, FLASH_CR_PER); SET_BIT(FLASH->CR, FLASH_CR_STRT); } /** * @brief Flush the instruction and data caches. * @retval None */ void FLASH_FlushCaches(void) { FLASH_CacheTypeDef cache = pFlash.CacheToReactivate; /* Flush instruction cache */ if ((cache == FLASH_CACHE_ICACHE_ENABLED) || (cache == FLASH_CACHE_ICACHE_DCACHE_ENABLED)) { /* Disable instruction cache */ __HAL_FLASH_INSTRUCTION_CACHE_DISABLE(); /* Reset instruction cache */ __HAL_FLASH_INSTRUCTION_CACHE_RESET(); /* Enable instruction cache */ __HAL_FLASH_INSTRUCTION_CACHE_ENABLE(); } /* Flush data cache */ if ((cache == FLASH_CACHE_DCACHE_ENABLED) || (cache == FLASH_CACHE_ICACHE_DCACHE_ENABLED)) { /* Reset data cache */ __HAL_FLASH_DATA_CACHE_RESET(); /* Enable data cache */ __HAL_FLASH_DATA_CACHE_ENABLE(); } /* Reset internal variable */ pFlash.CacheToReactivate = FLASH_CACHE_DISABLED; } /** * @brief Configure the write protection area into Option Bytes. * @note When the memory read protection level is selected (RDP level = 1), * it is not possible to program or erase Flash memory if the CPU debug * features are connected (JTAG or single wire) or boot code is being * executed from RAM or System flash, even if WRP is not activated. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @param WRPArea specifies the area to be configured. * This parameter can be one of the following values: * @arg OB_WRPAREA_BANK1_AREAA: Flash Bank 1 Area A * @arg OB_WRPAREA_BANK1_AREAB: Flash Bank 1 Area B * @arg OB_WRPAREA_BANK2_AREAA: Flash Bank 2 Area A (*) * @arg OB_WRPAREA_BANK2_AREAB: Flash Bank 2 Area B (*) * @note (*) availability depends on devices * @param WRPStartOffset specifies the start page of the write protected area. * This parameter can be page number between 0 and (max number of pages in the bank - 1). * @param WRDPEndOffset specifies the end page of the write protected area. * This parameter can be page number between WRPStartOffset and (max number of pages in the bank - 1). * @retval HAL_Status */ static HAL_StatusTypeDef FLASH_OB_WRPConfig(uint32_t WRPArea, uint32_t WRPStartOffset, uint32_t WRDPEndOffset) { HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_OB_WRPAREA(WRPArea)); assert_param(IS_FLASH_PAGE(WRPStartOffset)); assert_param(IS_FLASH_PAGE(WRDPEndOffset)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { /* Configure the write protected area */ if (WRPArea == OB_WRPAREA_BANK1_AREAA) { FLASH->WRP1AR = ((WRDPEndOffset << FLASH_WRP1AR_WRP1A_END_Pos) | WRPStartOffset); } else if (WRPArea == OB_WRPAREA_BANK1_AREAB) { FLASH->WRP1BR = ((WRDPEndOffset << FLASH_WRP1BR_WRP1B_END_Pos) | WRPStartOffset); } #if defined (FLASH_OPTR_DBANK) else if (WRPArea == OB_WRPAREA_BANK2_AREAA) { FLASH->WRP2AR = ((WRDPEndOffset << FLASH_WRP2AR_WRP2A_END_Pos) | WRPStartOffset); } else if (WRPArea == OB_WRPAREA_BANK2_AREAB) { FLASH->WRP2BR = ((WRDPEndOffset << FLASH_WRP2BR_WRP2B_END_Pos) | WRPStartOffset); } #endif else { /* Nothing to do */ } /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Set the read protection level into Option Bytes. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @note !!! Warning : When enabling OB_RDP level 2 it's no more possible * to go back to level 1 or 0 !!! * @param RDPLevel specifies the read protection level. * This parameter can be one of the following values: * @arg OB_RDP_LEVEL_0: No protection * @arg OB_RDP_LEVEL_1: Memory Read protection * @arg OB_RDP_LEVEL_2: Full chip protection * * @retval HAL_Status */ static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint32_t RDPLevel) { HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_OB_RDP_LEVEL(RDPLevel)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { /* Configure the RDP level in the option bytes register */ MODIFY_REG(FLASH->OPTR, FLASH_OPTR_RDP, RDPLevel); /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Program the FLASH User Option Bytes. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @param UserType The FLASH User Option Bytes to be modified. * This parameter can be a combination of @ref FLASH_OB_USER_Type. * @param UserConfig The selected User Option Bytes values: * This parameter can be a combination of @ref FLASH_OB_USER_BOR_LEVEL, * @ref FLASH_OB_USER_nRST_STOP, @ref FLASH_OB_USER_nRST_STANDBY , * @ref FLASH_OB_USER_nRST_SHUTDOWN, @ref FLASH_OB_USER_IWDG_SW, * @ref FLASH_OB_USER_IWDG_STOP, @ref FLASH_OB_USER_IWDG_STANDBY, * @ref FLASH_OB_USER_WWDG_SW, @ref FLASH_OB_USER_WWDG_SW, * @ref FLASH_OB_USER_BFB2 (*), @ref FLASH_OB_USER_nBOOT1, * @ref FLASH_OB_USER_SRAM_PE, @ref FLASH_OB_USER_CCMSRAM_RST, * @ref FLASH_OB_USER_nSWBOOT0, @ref FLASH_OB_USER_nBOOT0, * @ref FLASH_OB_USER_NRST_MODE, @ref FLASH_OB_USER_INTERNAL_RESET_HOLDER * @note (*) availability depends on devices * @retval HAL_Status */ static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig) { uint32_t optr_reg_val = 0; uint32_t optr_reg_mask = 0; HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_OB_USER_TYPE(UserType)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { if ((UserType & OB_USER_BOR_LEV) != 0U) { /* BOR level option byte should be modified */ assert_param(IS_OB_USER_BOR_LEVEL(UserConfig & FLASH_OPTR_BOR_LEV)); /* Set value and mask for BOR level option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_BOR_LEV); optr_reg_mask |= FLASH_OPTR_BOR_LEV; } if ((UserType & OB_USER_nRST_STOP) != 0U) { /* nRST_STOP option byte should be modified */ assert_param(IS_OB_USER_STOP(UserConfig & FLASH_OPTR_nRST_STOP)); /* Set value and mask for nRST_STOP option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nRST_STOP); optr_reg_mask |= FLASH_OPTR_nRST_STOP; } if ((UserType & OB_USER_nRST_STDBY) != 0U) { /* nRST_STDBY option byte should be modified */ assert_param(IS_OB_USER_STANDBY(UserConfig & FLASH_OPTR_nRST_STDBY)); /* Set value and mask for nRST_STDBY option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nRST_STDBY); optr_reg_mask |= FLASH_OPTR_nRST_STDBY; } if ((UserType & OB_USER_nRST_SHDW) != 0U) { /* nRST_SHDW option byte should be modified */ assert_param(IS_OB_USER_SHUTDOWN(UserConfig & FLASH_OPTR_nRST_SHDW)); /* Set value and mask for nRST_SHDW option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nRST_SHDW); optr_reg_mask |= FLASH_OPTR_nRST_SHDW; } if ((UserType & OB_USER_IWDG_SW) != 0U) { /* IWDG_SW option byte should be modified */ assert_param(IS_OB_USER_IWDG(UserConfig & FLASH_OPTR_IWDG_SW)); /* Set value and mask for IWDG_SW option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_IWDG_SW); optr_reg_mask |= FLASH_OPTR_IWDG_SW; } if ((UserType & OB_USER_IWDG_STOP) != 0U) { /* IWDG_STOP option byte should be modified */ assert_param(IS_OB_USER_IWDG_STOP(UserConfig & FLASH_OPTR_IWDG_STOP)); /* Set value and mask for IWDG_STOP option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_IWDG_STOP); optr_reg_mask |= FLASH_OPTR_IWDG_STOP; } if ((UserType & OB_USER_IWDG_STDBY) != 0U) { /* IWDG_STDBY option byte should be modified */ assert_param(IS_OB_USER_IWDG_STDBY(UserConfig & FLASH_OPTR_IWDG_STDBY)); /* Set value and mask for IWDG_STDBY option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_IWDG_STDBY); optr_reg_mask |= FLASH_OPTR_IWDG_STDBY; } if ((UserType & OB_USER_WWDG_SW) != 0U) { /* WWDG_SW option byte should be modified */ assert_param(IS_OB_USER_WWDG(UserConfig & FLASH_OPTR_WWDG_SW)); /* Set value and mask for WWDG_SW option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_WWDG_SW); optr_reg_mask |= FLASH_OPTR_WWDG_SW; } #if defined (FLASH_OPTR_BFB2) if ((UserType & OB_USER_BFB2) != 0U) { /* BFB2 option byte should be modified */ assert_param(IS_OB_USER_BFB2(UserConfig & FLASH_OPTR_BFB2)); /* Set value and mask for BFB2 option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_BFB2); optr_reg_mask |= FLASH_OPTR_BFB2; } #endif if ((UserType & OB_USER_nBOOT1) != 0U) { /* nBOOT1 option byte should be modified */ assert_param(IS_OB_USER_BOOT1(UserConfig & FLASH_OPTR_nBOOT1)); /* Set value and mask for nBOOT1 option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nBOOT1); optr_reg_mask |= FLASH_OPTR_nBOOT1; } if ((UserType & OB_USER_SRAM_PE) != 0U) { /* SRAM_PE option byte should be modified */ assert_param(IS_OB_USER_SRAM_PARITY(UserConfig & FLASH_OPTR_SRAM_PE)); /* Set value and mask for SRAM_PE option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_SRAM_PE); optr_reg_mask |= FLASH_OPTR_SRAM_PE; } if ((UserType & OB_USER_CCMSRAM_RST) != 0U) { /* CCMSRAM_RST option byte should be modified */ assert_param(IS_OB_USER_CCMSRAM_RST(UserConfig & FLASH_OPTR_CCMSRAM_RST)); /* Set value and mask for CCMSRAM_RST option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_CCMSRAM_RST); optr_reg_mask |= FLASH_OPTR_CCMSRAM_RST; } if ((UserType & OB_USER_nSWBOOT0) != 0U) { /* nSWBOOT0 option byte should be modified */ assert_param(IS_OB_USER_SWBOOT0(UserConfig & FLASH_OPTR_nSWBOOT0)); /* Set value and mask for nSWBOOT0 option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nSWBOOT0); optr_reg_mask |= FLASH_OPTR_nSWBOOT0; } if ((UserType & OB_USER_nBOOT0) != 0U) { /* nBOOT0 option byte should be modified */ assert_param(IS_OB_USER_BOOT0(UserConfig & FLASH_OPTR_nBOOT0)); /* Set value and mask for nBOOT0 option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_nBOOT0); optr_reg_mask |= FLASH_OPTR_nBOOT0; } if ((UserType & OB_USER_NRST_MODE) != 0U) { /* Reset Configuration option byte should be modified */ assert_param(IS_OB_USER_NRST_MODE(UserConfig & FLASH_OPTR_NRST_MODE)); /* Set value and mask for Reset Configuration option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_NRST_MODE); optr_reg_mask |= FLASH_OPTR_NRST_MODE; } if ((UserType & OB_USER_IRHEN) != 0U) { /* IRH option byte should be modified */ assert_param(IS_OB_USER_IRHEN(UserConfig & FLASH_OPTR_IRHEN)); /* Set value and mask for IRH option byte */ optr_reg_val |= (UserConfig & FLASH_OPTR_IRHEN); optr_reg_mask |= FLASH_OPTR_IRHEN; } /* Configure the option bytes register */ MODIFY_REG(FLASH->OPTR, optr_reg_mask, optr_reg_val); /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Configure the Proprietary code readout protection area into Option Bytes. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @param PCROPConfig specifies the configuration (Bank to be configured and PCROP_RDP option). * This parameter must be a combination of FLASH_BANK_1 or FLASH_BANK_2 (*) * with OB_PCROP_RDP_NOT_ERASE or OB_PCROP_RDP_ERASE. * @note (*) availability depends on devices * @param PCROPStartAddr specifies the start address of the Proprietary code readout protection. * This parameter can be an address between begin and end of the bank. * @param PCROPEndAddr specifies the end address of the Proprietary code readout protection. * This parameter can be an address between PCROPStartAddr and end of the bank. * @retval HAL_Status */ static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t PCROPConfig, uint32_t PCROPStartAddr, uint32_t PCROPEndAddr) { HAL_StatusTypeDef status; uint32_t reg_value; uint32_t bank1_addr; #if defined (FLASH_OPTR_DBANK) uint32_t bank2_addr; #endif /* Check the parameters */ assert_param(IS_FLASH_BANK_EXCLUSIVE(PCROPConfig & FLASH_BANK_BOTH)); assert_param(IS_OB_PCROP_RDP(PCROPConfig & FLASH_PCROP1ER_PCROP_RDP)); assert_param(IS_FLASH_MAIN_MEM_ADDRESS(PCROPStartAddr)); assert_param(IS_FLASH_MAIN_MEM_ADDRESS(PCROPEndAddr)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { #if defined (FLASH_OPTR_DBANK) /* Get the information about the bank swapping */ if (READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE) == 0U) { bank1_addr = FLASH_BASE; bank2_addr = FLASH_BASE + FLASH_BANK_SIZE; } else { bank1_addr = FLASH_BASE + FLASH_BANK_SIZE; bank2_addr = FLASH_BASE; } #else bank1_addr = FLASH_BASE; #endif #if defined (FLASH_OPTR_DBANK) if (READ_BIT(FLASH->OPTR, FLASH_OPTR_DBANK) == 0U) { /* Configure the Proprietary code readout protection */ if ((PCROPConfig & FLASH_BANK_BOTH) == FLASH_BANK_1) { reg_value = ((PCROPStartAddr - FLASH_BASE) >> 4); MODIFY_REG(FLASH->PCROP1SR, FLASH_PCROP1SR_PCROP1_STRT, reg_value); reg_value = ((PCROPEndAddr - FLASH_BASE) >> 4); MODIFY_REG(FLASH->PCROP1ER, FLASH_PCROP1ER_PCROP1_END, reg_value); } else if ((PCROPConfig & FLASH_BANK_BOTH) == FLASH_BANK_2) { reg_value = ((PCROPStartAddr - FLASH_BASE) >> 4); MODIFY_REG(FLASH->PCROP2SR, FLASH_PCROP2SR_PCROP2_STRT, reg_value); reg_value = ((PCROPEndAddr - FLASH_BASE) >> 4); MODIFY_REG(FLASH->PCROP2ER, FLASH_PCROP2ER_PCROP2_END, reg_value); } else { /* Nothing to do */ } } else #endif { /* Configure the Proprietary code readout protection */ if ((PCROPConfig & FLASH_BANK_BOTH) == FLASH_BANK_1) { reg_value = ((PCROPStartAddr - bank1_addr) >> 3); MODIFY_REG(FLASH->PCROP1SR, FLASH_PCROP1SR_PCROP1_STRT, reg_value); reg_value = ((PCROPEndAddr - bank1_addr) >> 3); MODIFY_REG(FLASH->PCROP1ER, FLASH_PCROP1ER_PCROP1_END, reg_value); } #if defined (FLASH_OPTR_DBANK) else if ((PCROPConfig & FLASH_BANK_BOTH) == FLASH_BANK_2) { reg_value = ((PCROPStartAddr - bank2_addr) >> 3); MODIFY_REG(FLASH->PCROP2SR, FLASH_PCROP2SR_PCROP2_STRT, reg_value); reg_value = ((PCROPEndAddr - bank2_addr) >> 3); MODIFY_REG(FLASH->PCROP2ER, FLASH_PCROP2ER_PCROP2_END, reg_value); } #endif else { /* Nothing to do */ } } MODIFY_REG(FLASH->PCROP1ER, FLASH_PCROP1ER_PCROP_RDP, (PCROPConfig & FLASH_PCROP1ER_PCROP_RDP)); /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Configure the Securable memory area into Option Bytes. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @param SecBank specifies bank of securable memory area to be configured. * This parameter can be one of the following values: * @arg FLASH_BANK_1: Securable memory in Bank1 to be configured * @arg FLASH_BANK_2: Securable memory in Bank2 to be configured (*) * @note (*) availability depends on devices * @param SecSize specifies the number of pages of the Securable memory area, * starting from first page of the bank. * This parameter can be page number between 0 and (max number of pages in the bank - 1) * @retval HAL Status */ static HAL_StatusTypeDef FLASH_OB_SecMemConfig(uint32_t SecBank, uint32_t SecSize) { HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_FLASH_BANK_EXCLUSIVE(SecBank)); assert_param(IS_OB_SECMEM_SIZE(SecSize)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { /* Configure the write protected area */ if (SecBank == FLASH_BANK_1) { MODIFY_REG(FLASH->SEC1R, FLASH_SEC1R_SEC_SIZE1, SecSize); } #if defined (FLASH_OPTR_DBANK) else if (SecBank == FLASH_BANK_2) { MODIFY_REG(FLASH->SEC2R, FLASH_SEC2R_SEC_SIZE2, SecSize); } else { /* Nothing to do */ } #endif /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Configure the Boot Lock into Option Bytes. * @note To configure any option bytes, the option lock bit OPTLOCK must be * cleared with the call of HAL_FLASH_OB_Unlock() function. * @note New option bytes configuration will be taken into account in two cases: * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() * - after a power reset (BOR reset or exit from Standby/Shutdown modes) * @param BootLockConfig specifies the boot lock configuration. * This parameter can be one of the following values: * @arg OB_BOOT_LOCK_ENABLE: Enable Boot Lock * @arg OB_BOOT_LOCK_DISABLE: Disable Boot Lock * * @retval HAL_Status */ static HAL_StatusTypeDef FLASH_OB_BootLockConfig(uint32_t BootLockConfig) { HAL_StatusTypeDef status; /* Check the parameters */ assert_param(IS_OB_BOOT_LOCK(BootLockConfig)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); if (status == HAL_OK) { MODIFY_REG(FLASH->SEC1R, FLASH_SEC1R_BOOT_LOCK, BootLockConfig); /* Set OPTSTRT Bit */ SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); } return status; } /** * @brief Return the Securable memory area configuration into Option Bytes. * @param[in] SecBank specifies the bank where securable memory area is located. * This parameter can be one of the following values: * @arg FLASH_BANK_1: Securable memory in Bank1 * @arg FLASH_BANK_2: Securable memory in Bank2 (*) * @note (*) availability depends on devices * @param[out] SecSize specifies the number of pages used in the securable memory area of the bank. * @retval None */ static void FLASH_OB_GetSecMem(uint32_t SecBank, uint32_t *SecSize) { /* Get the configuration of the securable memory area */ if (SecBank == FLASH_BANK_1) { *SecSize = READ_BIT(FLASH->SEC1R, FLASH_SEC1R_SEC_SIZE1); } #if defined (FLASH_OPTR_DBANK) else if (SecBank == FLASH_BANK_2) { *SecSize = READ_BIT(FLASH->SEC2R, FLASH_SEC2R_SEC_SIZE2); } else { /* Nothing to do */ } #endif } /** * @brief Return the Boot Lock configuration into Option Byte. * @retval BootLockConfig. * This return value can be one of the following values: * @arg OB_BOOT_LOCK_ENABLE: Boot lock enabled * @arg OB_BOOT_LOCK_DISABLE: Boot lock disabled */ static uint32_t FLASH_OB_GetBootLock(void) { return (READ_REG(FLASH->SEC1R) & FLASH_SEC1R_BOOT_LOCK); } /** * @brief Return the Write Protection configuration into Option Bytes. * @param[in] WRPArea specifies the area to be returned. * This parameter can be one of the following values: * @arg OB_WRPAREA_BANK1_AREAA: Flash Bank 1 Area A * @arg OB_WRPAREA_BANK1_AREAB: Flash Bank 1 Area B * @arg OB_WRPAREA_BANK2_AREAA: Flash Bank 2 Area A (don't apply to STM32G43x/STM32G44x devices) * @arg OB_WRPAREA_BANK2_AREAB: Flash Bank 2 Area B (don't apply to STM32G43x/STM32G44x devices) * @param[out] WRPStartOffset specifies the address where to copied the start page * of the write protected area. * @param[out] WRDPEndOffset specifies the address where to copied the end page of * the write protected area. * @retval None */ static void FLASH_OB_GetWRP(uint32_t WRPArea, uint32_t *WRPStartOffset, uint32_t *WRDPEndOffset) { /* Get the configuration of the write protected area */ if (WRPArea == OB_WRPAREA_BANK1_AREAA) { *WRPStartOffset = READ_BIT(FLASH->WRP1AR, FLASH_WRP1AR_WRP1A_STRT); *WRDPEndOffset = (READ_BIT(FLASH->WRP1AR, FLASH_WRP1AR_WRP1A_END) >> FLASH_WRP1AR_WRP1A_END_Pos); } else if (WRPArea == OB_WRPAREA_BANK1_AREAB) { *WRPStartOffset = READ_BIT(FLASH->WRP1BR, FLASH_WRP1BR_WRP1B_STRT); *WRDPEndOffset = (READ_BIT(FLASH->WRP1BR, FLASH_WRP1BR_WRP1B_END) >> FLASH_WRP1BR_WRP1B_END_Pos); } #if defined (FLASH_OPTR_DBANK) else if (WRPArea == OB_WRPAREA_BANK2_AREAA) { *WRPStartOffset = READ_BIT(FLASH->WRP2AR, FLASH_WRP2AR_WRP2A_STRT); *WRDPEndOffset = (READ_BIT(FLASH->WRP2AR, FLASH_WRP2AR_WRP2A_END) >> FLASH_WRP2AR_WRP2A_END_Pos); } else if (WRPArea == OB_WRPAREA_BANK2_AREAB) { *WRPStartOffset = READ_BIT(FLASH->WRP2BR, FLASH_WRP2BR_WRP2B_STRT); *WRDPEndOffset = (READ_BIT(FLASH->WRP2BR, FLASH_WRP2BR_WRP2B_END) >> FLASH_WRP2BR_WRP2B_END_Pos); } #endif else { /* Nothing to do */ } } /** * @brief Return the FLASH Read Protection level into Option Bytes. * @retval RDP_Level * This return value can be one of the following values: * @arg OB_RDP_LEVEL_0: No protection * @arg OB_RDP_LEVEL_1: Read protection of the memory * @arg OB_RDP_LEVEL_2: Full chip protection */ static uint32_t FLASH_OB_GetRDP(void) { uint32_t rdp_level = READ_BIT(FLASH->OPTR, FLASH_OPTR_RDP); if ((rdp_level != OB_RDP_LEVEL_0) && (rdp_level != OB_RDP_LEVEL_2)) { return (OB_RDP_LEVEL_1); } else { return rdp_level; } } /** * @brief Return the FLASH User Option Byte value. * @retval OB_user_config * This return value is a combination of @ref FLASH_OB_USER_BOR_LEVEL, * @ref FLASH_OB_USER_nRST_STOP, @ref FLASH_OB_USER_nRST_STANDBY, * @ref FLASH_OB_USER_nRST_SHUTDOWN, @ref FLASH_OB_USER_IWDG_SW, * @ref FLASH_OB_USER_IWDG_STOP, @ref FLASH_OB_USER_IWDG_STANDBY, * @ref FLASH_OB_USER_WWDG_SW, @ref FLASH_OB_USER_WWDG_SW, * @ref FLASH_OB_USER_BFB2 (*), @ref FLASH_OB_USER_DBANK (*), * @ref FLASH_OB_USER_nBOOT1, @ref FLASH_OB_USER_SRAM_PE, * @ref FLASH_OB_USER_CCMSRAM_RST, @ref OB_USER_nSWBOOT0,@ref FLASH_OB_USER_nBOOT0, * @ref FLASH_OB_USER_NRST_MODE, @ref FLASH_OB_USER_INTERNAL_RESET_HOLDER * @note (*) availability depends on devices */ static uint32_t FLASH_OB_GetUser(void) { uint32_t user_config = READ_REG(FLASH->OPTR); CLEAR_BIT(user_config, FLASH_OPTR_RDP); return user_config; } /** * @brief Return the FLASH PCROP configuration into Option Bytes. * @param[in,out] PCROPConfig specifies the configuration (Bank to be configured and PCROP_RDP option). * This parameter must be a combination of FLASH_BANK_1 or FLASH_BANK_2 * with OB_PCROP_RDP_NOT_ERASE or OB_PCROP_RDP_ERASE. * @param[out] PCROPStartAddr specifies the address where to copied the start address * of the Proprietary code readout protection. * @param[out] PCROPEndAddr specifies the address where to copied the end address of * the Proprietary code readout protection. * @retval None */ static void FLASH_OB_GetPCROP(uint32_t *PCROPConfig, uint32_t *PCROPStartAddr, uint32_t *PCROPEndAddr) { uint32_t reg_value; uint32_t bank1_addr; #if defined (FLASH_OPTR_DBANK) uint32_t bank2_addr; /* Get the information about the bank swapping */ if (READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE) == 0U) { bank1_addr = FLASH_BASE; bank2_addr = FLASH_BASE + FLASH_BANK_SIZE; } else { bank1_addr = FLASH_BASE + FLASH_BANK_SIZE; bank2_addr = FLASH_BASE; } #else bank1_addr = FLASH_BASE; #endif #if defined (FLASH_OPTR_DBANK) if (READ_BIT(FLASH->OPTR, FLASH_OPTR_DBANK) == 0U) { if (((*PCROPConfig) & FLASH_BANK_BOTH) == FLASH_BANK_1) { reg_value = (READ_REG(FLASH->PCROP1SR) & FLASH_PCROP1SR_PCROP1_STRT); *PCROPStartAddr = (reg_value << 4) + FLASH_BASE; reg_value = (READ_REG(FLASH->PCROP1ER) & FLASH_PCROP1ER_PCROP1_END); *PCROPEndAddr = (reg_value << 4) + FLASH_BASE; } else if (((*PCROPConfig) & FLASH_BANK_BOTH) == FLASH_BANK_2) { reg_value = (READ_REG(FLASH->PCROP2SR) & FLASH_PCROP2SR_PCROP2_STRT); *PCROPStartAddr = (reg_value << 4) + FLASH_BASE; reg_value = (READ_REG(FLASH->PCROP2ER) & FLASH_PCROP2ER_PCROP2_END); *PCROPEndAddr = (reg_value << 4) + FLASH_BASE; } else { /* Nothing to do */ } } else #endif { if (((*PCROPConfig) & FLASH_BANK_BOTH) == FLASH_BANK_1) { reg_value = (READ_REG(FLASH->PCROP1SR) & FLASH_PCROP1SR_PCROP1_STRT); *PCROPStartAddr = (reg_value << 3) + bank1_addr; reg_value = (READ_REG(FLASH->PCROP1ER) & FLASH_PCROP1ER_PCROP1_END); *PCROPEndAddr = (reg_value << 3) + bank1_addr; } #if defined (FLASH_OPTR_DBANK) else if (((*PCROPConfig) & FLASH_BANK_BOTH) == FLASH_BANK_2) { reg_value = (READ_REG(FLASH->PCROP2SR) & FLASH_PCROP2SR_PCROP2_STRT); *PCROPStartAddr = (reg_value << 3) + bank2_addr; reg_value = (READ_REG(FLASH->PCROP2ER) & FLASH_PCROP2ER_PCROP2_END); *PCROPEndAddr = (reg_value << 3) + bank2_addr; } #endif else { /* Nothing to do */ } } *PCROPConfig |= (READ_REG(FLASH->PCROP1ER) & FLASH_PCROP1ER_PCROP_RDP); } /** * @} */ /** * @} */ #endif /* HAL_FLASH_MODULE_ENABLED */ /** * @} */ /** * @} */
48,306
C
33.139223
116
0.632385
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_hal_smbus.c
/** ****************************************************************************** * @file stm32g4xx_hal_smbus.c * @author MCD Application Team * @brief SMBUS HAL module driver. * This file provides firmware functions to manage the following * functionalities of the System Management Bus (SMBus) peripheral, * based on I2C principles of operation : * + Initialization and de-initialization functions * + IO operation functions * + Peripheral State and Errors functions * ****************************************************************************** * @attention * * Copyright (c) 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 SMBUS HAL driver can be used as follows: (#) Declare a SMBUS_HandleTypeDef handle structure, for example: SMBUS_HandleTypeDef hsmbus; (#)Initialize the SMBUS low level resources by implementing the HAL_SMBUS_MspInit() API: (##) Enable the SMBUSx interface clock (##) SMBUS pins configuration (+++) Enable the clock for the SMBUS GPIOs (+++) Configure SMBUS pins as alternate function open-drain (##) NVIC configuration if you need to use interrupt process (+++) Configure the SMBUSx interrupt priority (+++) Enable the NVIC SMBUS IRQ Channel (#) Configure the Communication Clock Timing, Bus Timeout, Own Address1, Master Addressing mode, Dual Addressing mode, Own Address2, Own Address2 Mask, General call, Nostretch mode, Peripheral mode and Packet Error Check mode in the hsmbus Init structure. (#) Initialize the SMBUS registers by calling the HAL_SMBUS_Init() API: (++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customized HAL_SMBUS_MspInit(&hsmbus) API. (#) To check if target device is ready for communication, use the function HAL_SMBUS_IsDeviceReady() (#) For SMBUS IO operations, only one mode of operations is available within this driver *** Interrupt mode IO operation *** =================================== [..] (+) Transmit in master/host SMBUS mode an amount of data in non-blocking mode using HAL_SMBUS_Master_Transmit_IT() (++) At transmission end of transfer HAL_SMBUS_MasterTxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_MasterTxCpltCallback() (+) Receive in master/host SMBUS mode an amount of data in non-blocking mode using HAL_SMBUS_Master_Receive_IT() (++) At reception end of transfer HAL_SMBUS_MasterRxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_MasterRxCpltCallback() (+) Abort a master/host SMBUS process communication with Interrupt using HAL_SMBUS_Master_Abort_IT() (++) The associated previous transfer callback is called at the end of abort process (++) mean HAL_SMBUS_MasterTxCpltCallback() in case of previous state was master transmit (++) mean HAL_SMBUS_MasterRxCpltCallback() in case of previous state was master receive (+) Enable/disable the Address listen mode in slave/device or host/slave SMBUS mode using HAL_SMBUS_EnableListen_IT() HAL_SMBUS_DisableListen_IT() (++) When address slave/device SMBUS match, HAL_SMBUS_AddrCallback() is executed and users can add their own code to check the Address Match Code and the transmission direction request by master/host (Write/Read). (++) At Listen mode end HAL_SMBUS_ListenCpltCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_ListenCpltCallback() (+) Transmit in slave/device SMBUS mode an amount of data in non-blocking mode using HAL_SMBUS_Slave_Transmit_IT() (++) At transmission end of transfer HAL_SMBUS_SlaveTxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_SlaveTxCpltCallback() (+) Receive in slave/device SMBUS mode an amount of data in non-blocking mode using HAL_SMBUS_Slave_Receive_IT() (++) At reception end of transfer HAL_SMBUS_SlaveRxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_SlaveRxCpltCallback() (+) Enable/Disable the SMBUS alert mode using HAL_SMBUS_EnableAlert_IT() or HAL_SMBUS_DisableAlert_IT() (++) When SMBUS Alert is generated HAL_SMBUS_ErrorCallback() is executed and users can add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() to check the Alert Error Code using function HAL_SMBUS_GetError() (+) Get HAL state machine or error values using HAL_SMBUS_GetState() or HAL_SMBUS_GetError() (+) In case of transfer Error, HAL_SMBUS_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() to check the Error Code using function HAL_SMBUS_GetError() *** SMBUS HAL driver macros list *** ================================== [..] Below the list of most used macros in SMBUS HAL driver. (+) __HAL_SMBUS_ENABLE: Enable the SMBUS peripheral (+) __HAL_SMBUS_DISABLE: Disable the SMBUS peripheral (+) __HAL_SMBUS_GET_FLAG: Check whether the specified SMBUS flag is set or not (+) __HAL_SMBUS_CLEAR_FLAG: Clear the specified SMBUS pending flag (+) __HAL_SMBUS_ENABLE_IT: Enable the specified SMBUS interrupt (+) __HAL_SMBUS_DISABLE_IT: Disable the specified SMBUS interrupt *** Callback registration *** ============================================= [..] The compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. Use Functions HAL_SMBUS_RegisterCallback() or HAL_SMBUS_RegisterAddrCallback() to register an interrupt callback. [..] Function HAL_SMBUS_RegisterCallback() allows to register following callbacks: (+) MasterTxCpltCallback : callback for Master transmission end of transfer. (+) MasterRxCpltCallback : callback for Master reception end of transfer. (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. (+) ListenCpltCallback : callback for end of listen mode. (+) ErrorCallback : callback for error detection. (+) MspInitCallback : callback for Msp Init. (+) MspDeInitCallback : callback for Msp DeInit. This function takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. [..] For specific callback AddrCallback use dedicated register callbacks : HAL_SMBUS_RegisterAddrCallback. [..] Use function HAL_SMBUS_UnRegisterCallback to reset a callback to the default weak function. HAL_SMBUS_UnRegisterCallback takes as parameters the HAL peripheral handle, and the Callback ID. This function allows to reset following callbacks: (+) MasterTxCpltCallback : callback for Master transmission end of transfer. (+) MasterRxCpltCallback : callback for Master reception end of transfer. (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. (+) ListenCpltCallback : callback for end of listen mode. (+) ErrorCallback : callback for error detection. (+) MspInitCallback : callback for Msp Init. (+) MspDeInitCallback : callback for Msp DeInit. [..] For callback AddrCallback use dedicated register callbacks : HAL_SMBUS_UnRegisterAddrCallback. [..] By default, after the HAL_SMBUS_Init() and when the state is HAL_I2C_STATE_RESET all callbacks are set to the corresponding weak functions: examples HAL_SMBUS_MasterTxCpltCallback(), HAL_SMBUS_MasterRxCpltCallback(). Exception done for MspInit and MspDeInit functions that are reset to the legacy weak functions in the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() only when these callbacks are null (not registered beforehand). If MspInit or MspDeInit are not null, the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. [..] Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only. Exception done MspInit/MspDeInit functions that can be registered/unregistered in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state, thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. Then, the user first registers the MspInit/MspDeInit user callbacks using HAL_SMBUS_RegisterCallback() before calling HAL_SMBUS_DeInit() or HAL_SMBUS_Init() function. [..] When the compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration feature is not available and all callbacks are set to the corresponding weak functions. [..] (@) You can refer to the SMBUS HAL driver header file for more useful macros @endverbatim */ /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @defgroup SMBUS SMBUS * @brief SMBUS HAL module driver * @{ */ #ifdef HAL_SMBUS_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SMBUS_Private_Define SMBUS Private Constants * @{ */ #define TIMING_CLEAR_MASK (0xF0FFFFFFUL) /*!< SMBUS TIMING clear register Mask */ #define HAL_TIMEOUT_ADDR (10000U) /*!< 10 s */ #define HAL_TIMEOUT_BUSY (25U) /*!< 25 ms */ #define HAL_TIMEOUT_DIR (25U) /*!< 25 ms */ #define HAL_TIMEOUT_RXNE (25U) /*!< 25 ms */ #define HAL_TIMEOUT_STOPF (25U) /*!< 25 ms */ #define HAL_TIMEOUT_TC (25U) /*!< 25 ms */ #define HAL_TIMEOUT_TCR (25U) /*!< 25 ms */ #define HAL_TIMEOUT_TXIS (25U) /*!< 25 ms */ #define MAX_NBYTE_SIZE 255U /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @addtogroup SMBUS_Private_Functions SMBUS Private Functions * @{ */ /* Private functions to handle flags during polling transfer */ static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /* Private functions for SMBUS transfer IRQ handler */ static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus); /* Private functions to centralize the enable/disable of Interrupts */ static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); /* Private function to flush TXDR register */ static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus); /* Private function to handle start, restart or stop a transfer */ static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request); /* Private function to Convert Specific options */ static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup SMBUS_Exported_Functions SMBUS Exported Functions * @{ */ /** @defgroup SMBUS_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to initialize and deinitialize the SMBUSx peripheral: (+) User must Implement HAL_SMBUS_MspInit() function in which he configures all related peripherals resources (CLOCK, GPIO, IT and NVIC ). (+) Call the function HAL_SMBUS_Init() to configure the selected device with the selected configuration: (++) Clock Timing (++) Bus Timeout (++) Analog Filer mode (++) Own Address 1 (++) Addressing mode (Master, Slave) (++) Dual Addressing mode (++) Own Address 2 (++) Own Address 2 Mask (++) General call mode (++) Nostretch mode (++) Packet Error Check mode (++) Peripheral mode (+) Call the function HAL_SMBUS_DeInit() to restore the default configuration of the selected SMBUSx peripheral. (+) Enable/Disable Analog/Digital filters with HAL_SMBUS_ConfigAnalogFilter() and HAL_SMBUS_ConfigDigitalFilter(). @endverbatim * @{ */ /** * @brief Initialize the SMBUS according to the specified parameters * in the SMBUS_InitTypeDef and initialize the associated handle. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) { /* Check the SMBUS handle allocation */ if (hsmbus == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); assert_param(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); assert_param(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); assert_param(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); assert_param(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); assert_param(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); assert_param(IS_SMBUS_OWN_ADDRESS2_MASK(hsmbus->Init.OwnAddress2Masks)); assert_param(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); assert_param(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); assert_param(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); assert_param(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); if (hsmbus->State == HAL_SMBUS_STATE_RESET) { /* Allocate lock resource and initialize it */ hsmbus->Lock = HAL_UNLOCKED; #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ if (hsmbus->MspInitCallback == NULL) { hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ } /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ hsmbus->MspInitCallback(hsmbus); #else /* Init the low level hardware : GPIO, CLOCK, NVIC */ HAL_SMBUS_MspInit(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } hsmbus->State = HAL_SMBUS_STATE_BUSY; /* Disable the selected SMBUS peripheral */ __HAL_SMBUS_DISABLE(hsmbus); /*---------------------------- SMBUSx TIMINGR Configuration ------------------------*/ /* Configure SMBUSx: Frequency range */ hsmbus->Instance->TIMINGR = hsmbus->Init.Timing & TIMING_CLEAR_MASK; /*---------------------------- SMBUSx TIMEOUTR Configuration ------------------------*/ /* Configure SMBUSx: Bus Timeout */ hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TIMOUTEN; hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TEXTEN; hsmbus->Instance->TIMEOUTR = hsmbus->Init.SMBusTimeout; /*---------------------------- SMBUSx OAR1 Configuration -----------------------*/ /* Configure SMBUSx: Own Address1 and ack own address1 mode */ hsmbus->Instance->OAR1 &= ~I2C_OAR1_OA1EN; if (hsmbus->Init.OwnAddress1 != 0UL) { if (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) { hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | hsmbus->Init.OwnAddress1); } else /* SMBUS_ADDRESSINGMODE_10BIT */ { hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hsmbus->Init.OwnAddress1); } } /*---------------------------- SMBUSx CR2 Configuration ------------------------*/ /* Configure SMBUSx: Addressing Master mode */ if (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_10BIT) { hsmbus->Instance->CR2 = (I2C_CR2_ADD10); } /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process) */ /* AUTOEND and NACK bit will be manage during Transfer process */ hsmbus->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); /*---------------------------- SMBUSx OAR2 Configuration -----------------------*/ /* Configure SMBUSx: Dual mode and Own Address2 */ hsmbus->Instance->OAR2 = (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2 | \ (hsmbus->Init.OwnAddress2Masks << 8U)); /*---------------------------- SMBUSx CR1 Configuration ------------------------*/ /* Configure SMBUSx: Generalcall and NoStretch mode */ hsmbus->Instance->CR1 = (hsmbus->Init.GeneralCallMode | hsmbus->Init.NoStretchMode | \ hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode | \ hsmbus->Init.AnalogFilter); /* Enable Slave Byte Control only in case of Packet Error Check is enabled and SMBUS Peripheral is set in Slave mode */ if ((hsmbus->Init.PacketErrorCheckMode == SMBUS_PEC_ENABLE) && \ ((hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP))) { hsmbus->Instance->CR1 |= I2C_CR1_SBC; } /* Enable the selected SMBUS peripheral */ __HAL_SMBUS_ENABLE(hsmbus); hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; hsmbus->PreviousState = HAL_SMBUS_STATE_READY; hsmbus->State = HAL_SMBUS_STATE_READY; return HAL_OK; } /** * @brief DeInitialize the SMBUS peripheral. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) { /* Check the SMBUS handle allocation */ if (hsmbus == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); hsmbus->State = HAL_SMBUS_STATE_BUSY; /* Disable the SMBUS Peripheral Clock */ __HAL_SMBUS_DISABLE(hsmbus); #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) if (hsmbus->MspDeInitCallback == NULL) { hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ } /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ hsmbus->MspDeInitCallback(hsmbus); #else /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ HAL_SMBUS_MspDeInit(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; hsmbus->PreviousState = HAL_SMBUS_STATE_RESET; hsmbus->State = HAL_SMBUS_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hsmbus); return HAL_OK; } /** * @brief Initialize the SMBUS MSP. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_MspInit could be implemented in the user file */ } /** * @brief DeInitialize the SMBUS MSP. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_MspDeInit could be implemented in the user file */ } /** * @brief Configure Analog noise filter. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param AnalogFilter This parameter can be one of the following values: * @arg @ref SMBUS_ANALOGFILTER_ENABLE * @arg @ref SMBUS_ANALOGFILTER_DISABLE * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_ConfigAnalogFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t AnalogFilter) { /* Check the parameters */ assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); assert_param(IS_SMBUS_ANALOG_FILTER(AnalogFilter)); if (hsmbus->State == HAL_SMBUS_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = HAL_SMBUS_STATE_BUSY; /* Disable the selected SMBUS peripheral */ __HAL_SMBUS_DISABLE(hsmbus); /* Reset ANOFF bit */ hsmbus->Instance->CR1 &= ~(I2C_CR1_ANFOFF); /* Set analog filter bit*/ hsmbus->Instance->CR1 |= AnalogFilter; __HAL_SMBUS_ENABLE(hsmbus); hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Configure Digital noise filter. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param DigitalFilter Coefficient of digital noise filter between Min_Data=0x00 and Max_Data=0x0F. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_ConfigDigitalFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t DigitalFilter) { uint32_t tmpreg; /* Check the parameters */ assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); assert_param(IS_SMBUS_DIGITAL_FILTER(DigitalFilter)); if (hsmbus->State == HAL_SMBUS_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = HAL_SMBUS_STATE_BUSY; /* Disable the selected SMBUS peripheral */ __HAL_SMBUS_DISABLE(hsmbus); /* Get the old register value */ tmpreg = hsmbus->Instance->CR1; /* Reset I2C DNF bits [11:8] */ tmpreg &= ~(I2C_CR1_DNF); /* Set I2Cx DNF coefficient */ tmpreg |= DigitalFilter << I2C_CR1_DNF_Pos; /* Store the new register value */ hsmbus->Instance->CR1 = tmpreg; __HAL_SMBUS_ENABLE(hsmbus); hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_OK; } else { return HAL_BUSY; } } #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) /** * @brief Register a User SMBUS Callback * To be used instead of the weak predefined callback * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param CallbackID ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID * @param pCallback pointer to the Callback function * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_RegisterCallback(SMBUS_HandleTypeDef *hsmbus, HAL_SMBUS_CallbackIDTypeDef CallbackID, pSMBUS_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hsmbus); if (HAL_SMBUS_STATE_READY == hsmbus->State) { switch (CallbackID) { case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : hsmbus->MasterTxCpltCallback = pCallback; break; case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : hsmbus->MasterRxCpltCallback = pCallback; break; case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : hsmbus->SlaveTxCpltCallback = pCallback; break; case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : hsmbus->SlaveRxCpltCallback = pCallback; break; case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : hsmbus->ListenCpltCallback = pCallback; break; case HAL_SMBUS_ERROR_CB_ID : hsmbus->ErrorCallback = pCallback; break; case HAL_SMBUS_MSPINIT_CB_ID : hsmbus->MspInitCallback = pCallback; break; case HAL_SMBUS_MSPDEINIT_CB_ID : hsmbus->MspDeInitCallback = pCallback; break; default : /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else if (HAL_SMBUS_STATE_RESET == hsmbus->State) { switch (CallbackID) { case HAL_SMBUS_MSPINIT_CB_ID : hsmbus->MspInitCallback = pCallback; break; case HAL_SMBUS_MSPDEINIT_CB_ID : hsmbus->MspDeInitCallback = pCallback; break; default : /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsmbus); return status; } /** * @brief Unregister an SMBUS Callback * SMBUS callback is redirected to the weak predefined callback * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param CallbackID ID of the callback to be unregistered * This parameter can be one of the following values: * This parameter can be one of the following values: * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_UnRegisterCallback(SMBUS_HandleTypeDef *hsmbus, HAL_SMBUS_CallbackIDTypeDef CallbackID) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(hsmbus); if (HAL_SMBUS_STATE_READY == hsmbus->State) { switch (CallbackID) { case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ break; case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ break; case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ break; case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ break; case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ break; case HAL_SMBUS_ERROR_CB_ID : hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ break; case HAL_SMBUS_MSPINIT_CB_ID : hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ break; case HAL_SMBUS_MSPDEINIT_CB_ID : hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ break; default : /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else if (HAL_SMBUS_STATE_RESET == hsmbus->State) { switch (CallbackID) { case HAL_SMBUS_MSPINIT_CB_ID : hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ break; case HAL_SMBUS_MSPDEINIT_CB_ID : hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ break; default : /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsmbus); return status; } /** * @brief Register the Slave Address Match SMBUS Callback * To be used instead of the weak HAL_SMBUS_AddrCallback() predefined callback * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param pCallback pointer to the Address Match Callback function * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_RegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus, pSMBUS_AddrCallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hsmbus); if (HAL_SMBUS_STATE_READY == hsmbus->State) { hsmbus->AddrCallback = pCallback; } else { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsmbus); return status; } /** * @brief UnRegister the Slave Address Match SMBUS Callback * Info Ready SMBUS Callback is redirected to the weak HAL_SMBUS_AddrCallback() predefined callback * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_UnRegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(hsmbus); if (HAL_SMBUS_STATE_READY == hsmbus->State) { hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ } else { /* Update the error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsmbus); return status; } #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup SMBUS_Exported_Functions_Group2 Input and Output operation functions * @brief Data transfers functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the SMBUS data transfers. (#) Blocking mode function to check if device is ready for usage is : (++) HAL_SMBUS_IsDeviceReady() (#) There is only one mode of transfer: (++) Non-Blocking mode : The communication is performed using Interrupts. These functions return the status of the transfer startup. The end of the data processing will be indicated through the dedicated SMBUS IRQ when using Interrupt mode. (#) Non-Blocking mode functions with Interrupt are : (++) HAL_SMBUS_Master_Transmit_IT() (++) HAL_SMBUS_Master_Receive_IT() (++) HAL_SMBUS_Slave_Transmit_IT() (++) HAL_SMBUS_Slave_Receive_IT() (++) HAL_SMBUS_EnableListen_IT() or alias HAL_SMBUS_EnableListen_IT() (++) HAL_SMBUS_DisableListen_IT() (++) HAL_SMBUS_EnableAlert_IT() (++) HAL_SMBUS_DisableAlert_IT() (#) A set of Transfer Complete Callbacks are provided in non-Blocking mode: (++) HAL_SMBUS_MasterTxCpltCallback() (++) HAL_SMBUS_MasterRxCpltCallback() (++) HAL_SMBUS_SlaveTxCpltCallback() (++) HAL_SMBUS_SlaveRxCpltCallback() (++) HAL_SMBUS_AddrCallback() (++) HAL_SMBUS_ListenCpltCallback() (++) HAL_SMBUS_ErrorCallback() @endverbatim * @{ */ /** * @brief Transmit in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param DevAddress Target device address: The device 7 bits address value * in datasheet must be shifted to the left before calling the interface * @param pData Pointer to data buffer * @param Size Amount of data to be sent * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { uint32_t tmp; /* Check the parameters */ assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); if (hsmbus->State == HAL_SMBUS_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; /* Prepare transfer parameters */ hsmbus->pBuffPtr = pData; hsmbus->XferCount = Size; hsmbus->XferOptions = XferOptions; /* In case of Quick command, remove autoend mode */ /* Manage the stop generation by software */ if (hsmbus->pBuffPtr == NULL) { hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; } if (Size > MAX_NBYTE_SIZE) { hsmbus->XferSize = MAX_NBYTE_SIZE; } else { hsmbus->XferSize = Size; } /* Send Slave Address */ /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) { SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_GENERATE_START_WRITE); } else { /* If transfer direction not change, do not generate Restart Condition */ /* Mean Previous state is same as current state */ /* Store current volatile XferOptions, misra rule */ tmp = hsmbus->XferOptions; if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) && \ (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) { SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); } /* Else transfer direction change, so generate Restart with new transfer direction */ else { /* Convert OTHER_xxx XferOptions if any */ SMBUS_ConvertOtherXferOptions(hsmbus); /* Handle Transfer */ SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_WRITE); } /* If PEC mode is enable, size to transmit manage by SW part should be Size-1 byte, corresponding to PEC byte */ /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) { hsmbus->XferSize--; hsmbus->XferCount--; } } /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Note : The SMBUS interrupts must be enabled after unlocking current process to avoid the risk of SMBUS interrupt handle execution before current process unlock */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param DevAddress Target device address: The device 7 bits address value * in datasheet must be shifted to the left before calling the interface * @param pData Pointer to data buffer * @param Size Amount of data to be sent * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { uint32_t tmp; /* Check the parameters */ assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); if (hsmbus->State == HAL_SMBUS_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; /* Prepare transfer parameters */ hsmbus->pBuffPtr = pData; hsmbus->XferCount = Size; hsmbus->XferOptions = XferOptions; /* In case of Quick command, remove autoend mode */ /* Manage the stop generation by software */ if (hsmbus->pBuffPtr == NULL) { hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; } if (Size > MAX_NBYTE_SIZE) { hsmbus->XferSize = MAX_NBYTE_SIZE; } else { hsmbus->XferSize = Size; } /* Send Slave Address */ /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) { SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_GENERATE_START_READ); } else { /* If transfer direction not change, do not generate Restart Condition */ /* Mean Previous state is same as current state */ /* Store current volatile XferOptions, Misra rule */ tmp = hsmbus->XferOptions; if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) && \ (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) { SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); } /* Else transfer direction change, so generate Restart with new transfer direction */ else { /* Convert OTHER_xxx XferOptions if any */ SMBUS_ConvertOtherXferOptions(hsmbus); /* Handle Transfer */ SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_READ); } } /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Note : The SMBUS interrupts must be enabled after unlocking current process to avoid the risk of SMBUS interrupt handle execution before current process unlock */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Abort a master/host SMBUS process communication with Interrupt. * @note This abort can be called only if state is ready * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param DevAddress Target device address: The device 7 bits address value * in datasheet must be shifted to the left before calling the interface * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) { if (hsmbus->State == HAL_SMBUS_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsmbus); /* Keep the same state as previous */ /* to perform as well the call of the corresponding end of transfer callback */ if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) { hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; } else if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) { hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; } else { /* Wrong usage of abort function */ /* This function should be used only in case of abort monitored by master device */ return HAL_ERROR; } hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; /* Set NBYTES to 1 to generate a dummy read on SMBUS peripheral */ /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ SMBUS_TransferConfig(hsmbus, DevAddress, 1, SMBUS_AUTOEND_MODE, SMBUS_NO_STARTSTOP); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Note : The SMBUS interrupts must be enabled after unlocking current process to avoid the risk of SMBUS interrupt handle execution before current process unlock */ if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) { SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); } else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) { SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); } else { /* Nothing to do */ } return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Transmit in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param pData Pointer to data buffer * @param Size Amount of data to be sent * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { /* Check the parameters */ assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) { if ((pData == NULL) || (Size == 0UL)) { hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; return HAL_ERROR; } /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_TX); /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_TX | HAL_SMBUS_STATE_LISTEN); hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; /* Set SBC bit to manage Acknowledge at each bit */ hsmbus->Instance->CR1 |= I2C_CR1_SBC; /* Enable Address Acknowledge */ hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; /* Prepare transfer parameters */ hsmbus->pBuffPtr = pData; hsmbus->XferCount = Size; hsmbus->XferOptions = XferOptions; /* Convert OTHER_xxx XferOptions if any */ SMBUS_ConvertOtherXferOptions(hsmbus); if (Size > MAX_NBYTE_SIZE) { hsmbus->XferSize = MAX_NBYTE_SIZE; } else { hsmbus->XferSize = Size; } /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) { SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_NO_STARTSTOP); } else { /* Set NBYTE to transmit */ SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) { hsmbus->XferSize--; hsmbus->XferCount--; } } /* Clear ADDR flag after prepare the transfer parameters */ /* This action will generate an acknowledge to the HOST */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Note : The SMBUS interrupts must be enabled after unlocking current process to avoid the risk of SMBUS interrupt handle execution before current process unlock */ /* REnable ADDR interrupt */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX | SMBUS_IT_ADDR); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param pData Pointer to data buffer * @param Size Amount of data to be sent * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { /* Check the parameters */ assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) { if ((pData == NULL) || (Size == 0UL)) { hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; return HAL_ERROR; } /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_RX); /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_RX | HAL_SMBUS_STATE_LISTEN); hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; /* Set SBC bit to manage Acknowledge at each bit */ hsmbus->Instance->CR1 |= I2C_CR1_SBC; /* Enable Address Acknowledge */ hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; /* Prepare transfer parameters */ hsmbus->pBuffPtr = pData; hsmbus->XferSize = Size; hsmbus->XferCount = Size; hsmbus->XferOptions = XferOptions; /* Convert OTHER_xxx XferOptions if any */ SMBUS_ConvertOtherXferOptions(hsmbus); /* Set NBYTE to receive */ /* If XferSize equal "1", or XferSize equal "2" with PEC requested (mean 1 data byte + 1 PEC byte */ /* no need to set RELOAD bit mode, a ACK will be automatically generated in that case */ /* else need to set RELOAD bit mode to generate an automatic ACK at each byte Received */ /* This RELOAD bit will be reset for last BYTE to be receive in SMBUS_Slave_ISR */ if (((SMBUS_GET_PEC_MODE(hsmbus) != 0UL) && (hsmbus->XferSize == 2U)) || (hsmbus->XferSize == 1U)) { SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); } else { SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions | SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); } /* Clear ADDR flag after prepare the transfer parameters */ /* This action will generate an acknowledge to the HOST */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Note : The SMBUS interrupts must be enabled after unlocking current process to avoid the risk of SMBUS interrupt handle execution before current process unlock */ /* REnable ADDR interrupt */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_ADDR); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Enable the Address listen mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus) { hsmbus->State = HAL_SMBUS_STATE_LISTEN; /* Enable the Address Match interrupt */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ADDR); return HAL_OK; } /** * @brief Disable the Address listen mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus) { /* Disable Address listen mode only if a transfer is not ongoing */ if (hsmbus->State == HAL_SMBUS_STATE_LISTEN) { hsmbus->State = HAL_SMBUS_STATE_READY; /* Disable the Address Match interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Enable the SMBUS alert mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUSx peripheral. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) { /* Enable SMBus alert */ hsmbus->Instance->CR1 |= I2C_CR1_ALERTEN; /* Clear ALERT flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); /* Enable Alert Interrupt */ SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ALERT); return HAL_OK; } /** * @brief Disable the SMBUS alert mode with Interrupt. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUSx peripheral. * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) { /* Enable SMBus alert */ hsmbus->Instance->CR1 &= ~I2C_CR1_ALERTEN; /* Disable Alert Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ALERT); return HAL_OK; } /** * @brief Check if target device is ready for communication. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param DevAddress Target device address: The device 7 bits address value * in datasheet must be shifted to the left before calling the interface * @param Trials Number of trials * @param Timeout Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) { uint32_t tickstart; __IO uint32_t SMBUS_Trials = 0UL; FlagStatus tmp1; FlagStatus tmp2; if (hsmbus->State == HAL_SMBUS_STATE_READY) { if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET) { return HAL_BUSY; } /* Process Locked */ __HAL_LOCK(hsmbus); hsmbus->State = HAL_SMBUS_STATE_BUSY; hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; do { /* Generate Start */ hsmbus->Instance->CR2 = SMBUS_GENERATE_START(hsmbus->Init.AddressingMode, DevAddress); /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ /* Wait until STOPF flag is set or a NACK flag is set*/ tickstart = HAL_GetTick(); tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); while ((tmp1 == RESET) && (tmp2 == RESET)) { if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) { /* Device is ready */ hsmbus->State = HAL_SMBUS_STATE_READY; /* Update SMBUS error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_ERROR; } } tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); } /* Check if the NACKF flag has not been set */ if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) { /* Wait until STOPF flag is reset */ if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) { return HAL_ERROR; } /* Clear STOP Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); /* Device is ready */ hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_OK; } else { /* Wait until STOPF flag is reset */ if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) { return HAL_ERROR; } /* Clear NACK Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); /* Clear STOP Flag, auto generated with autoend*/ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); } /* Check if the maximum allowed number of trials has been reached */ if (SMBUS_Trials == Trials) { /* Generate Stop */ hsmbus->Instance->CR2 |= I2C_CR2_STOP; /* Wait until STOPF flag is reset */ if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) { return HAL_ERROR; } /* Clear STOP Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); } /* Increment Trials */ SMBUS_Trials++; } while (SMBUS_Trials < Trials); hsmbus->State = HAL_SMBUS_STATE_READY; /* Update SMBUS error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_ERROR; } else { return HAL_BUSY; } } /** * @} */ /** @defgroup SMBUS_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks * @{ */ /** * @brief Handle SMBUS event interrupt request. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) { /* Use a local variable to store the current ISR flags */ /* This action will avoid a wrong treatment due to ISR flags change during interrupt handler */ uint32_t tmpisrvalue = READ_REG(hsmbus->Instance->ISR); uint32_t tmpcr1value = READ_REG(hsmbus->Instance->CR1); /* SMBUS in mode Transmitter ---------------------------------------------------*/ if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI)) != RESET) && ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TXIS) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) { /* Slave mode selected */ if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) { (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); } /* Master mode selected */ else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_TX) == HAL_SMBUS_STATE_MASTER_BUSY_TX) { (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); } else { /* Nothing to do */ } } /* SMBUS in mode Receiver ----------------------------------------------------*/ if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI)) != RESET) && ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_RXNE) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) { /* Slave mode selected */ if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) { (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); } /* Master mode selected */ else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_RX) == HAL_SMBUS_STATE_MASTER_BUSY_RX) { (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); } else { /* Nothing to do */ } } /* SMBUS in mode Listener Only --------------------------------------------------*/ if (((SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_ADDRI) != RESET) || (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_STOPI) != RESET) || (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_NACKI) != RESET)) && ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_ADDR) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) { if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) { (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); } } } /** * @brief Handle SMBUS error interrupt request. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) { SMBUS_ITErrorHandler(hsmbus); } /** * @brief Master Tx Transfer completed callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_MasterTxCpltCallback() could be implemented in the user file */ } /** * @brief Master Rx Transfer completed callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_MasterRxCpltCallback() could be implemented in the user file */ } /** @brief Slave Tx Transfer completed callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_SlaveTxCpltCallback() could be implemented in the user file */ } /** * @brief Slave Rx Transfer completed callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_SlaveRxCpltCallback() could be implemented in the user file */ } /** * @brief Slave Address Match callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param TransferDirection Master request Transfer Direction (Write/Read) * @param AddrMatchCode Address Match Code * @retval None */ __weak void HAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); UNUSED(TransferDirection); UNUSED(AddrMatchCode); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_AddrCallback() could be implemented in the user file */ } /** * @brief Listen Complete callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_ListenCpltCallback() could be implemented in the user file */ } /** * @brief SMBUS error callback. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval None */ __weak void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsmbus); /* NOTE : This function should not be modified, when the callback is needed, the HAL_SMBUS_ErrorCallback() could be implemented in the user file */ } /** * @} */ /** @defgroup SMBUS_Exported_Functions_Group3 Peripheral State and Errors functions * @brief Peripheral State and Errors functions * @verbatim =============================================================================== ##### Peripheral State and Errors functions ##### =============================================================================== [..] This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim * @{ */ /** * @brief Return the SMBUS handle state. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval HAL state */ uint32_t HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus) { /* Return SMBUS handle state */ return hsmbus->State; } /** * @brief Return the SMBUS error code. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @retval SMBUS Error Code */ uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus) { return hsmbus->ErrorCode; } /** * @} */ /** * @} */ /** @addtogroup SMBUS_Private_Functions SMBUS Private Functions * @brief Data transfers Private functions * @{ */ /** * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param StatusFlags Value of Interrupt Flags. * @retval HAL status */ static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) { uint16_t DevAddress; /* Process Locked */ __HAL_LOCK(hsmbus); if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) { /* Clear NACK Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); /* Set corresponding Error Code */ /* No need to generate STOP, it is automatically done */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; /* Flush TX register */ SMBUS_Flush_TXDR(hsmbus); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the Error callback to inform upper layer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->ErrorCallback(hsmbus); #else HAL_SMBUS_ErrorCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) { /* Check and treat errors if errors occurs during STOP process */ SMBUS_ITErrorHandler(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) { /* Disable Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); /* Clear STOP Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); /* Clear Configuration Register 2 */ SMBUS_RESET_CR2(hsmbus); /* Flush remaining data in Fifo register in case of error occurs before TXEmpty */ /* Disable the selected SMBUS peripheral */ __HAL_SMBUS_DISABLE(hsmbus); hsmbus->PreviousState = HAL_SMBUS_STATE_READY; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Re-enable the selected SMBUS peripheral */ __HAL_SMBUS_ENABLE(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterTxCpltCallback(hsmbus); #else HAL_SMBUS_MasterTxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) { /* Store Last receive data if any */ if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) { /* Read data from RXDR */ *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); /* Increment Buffer pointer */ hsmbus->pBuffPtr++; if ((hsmbus->XferSize > 0U)) { hsmbus->XferSize--; hsmbus->XferCount--; } } /* Disable Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); /* Clear STOP Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); /* Clear Configuration Register 2 */ SMBUS_RESET_CR2(hsmbus); hsmbus->PreviousState = HAL_SMBUS_STATE_READY; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterRxCpltCallback(hsmbus); #else HAL_SMBUS_MasterRxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) { /* Read data from RXDR */ *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); /* Increment Buffer pointer */ hsmbus->pBuffPtr++; /* Increment Size counter */ hsmbus->XferSize--; hsmbus->XferCount--; } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) { /* Write data to TXDR */ hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; /* Increment Buffer pointer */ hsmbus->pBuffPtr++; /* Increment Size counter */ hsmbus->XferSize--; hsmbus->XferCount--; } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET) { if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) { DevAddress = (uint16_t)(hsmbus->Instance->CR2 & I2C_CR2_SADD); if (hsmbus->XferCount > MAX_NBYTE_SIZE) { SMBUS_TransferConfig(hsmbus, DevAddress, MAX_NBYTE_SIZE, (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), SMBUS_NO_STARTSTOP); hsmbus->XferSize = MAX_NBYTE_SIZE; } else { hsmbus->XferSize = hsmbus->XferCount; SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) { hsmbus->XferSize--; hsmbus->XferCount--; } } } else if ((hsmbus->XferCount == 0U) && (hsmbus->XferSize == 0U)) { /* Call TxCpltCallback() if no stop mode is set */ if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) { /* Call the corresponding callback to inform upper layer of End of Transfer */ if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) { /* Disable Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterTxCpltCallback(hsmbus); #else HAL_SMBUS_MasterTxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) { SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterRxCpltCallback(hsmbus); #else HAL_SMBUS_MasterRxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } } else { /* Nothing to do */ } } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TC) != RESET) { if (hsmbus->XferCount == 0U) { /* Specific use case for Quick command */ if (hsmbus->pBuffPtr == NULL) { /* Generate a Stop command */ hsmbus->Instance->CR2 |= I2C_CR2_STOP; } /* Call TxCpltCallback() if no stop mode is set */ else if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) { /* No Generate Stop, to permit restart mode */ /* The stop will be done at the end of transfer, when SMBUS_AUTOEND_MODE enable */ /* Call the corresponding callback to inform upper layer of End of Transfer */ if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) { /* Disable Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterTxCpltCallback(hsmbus); #else HAL_SMBUS_MasterTxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) { SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->MasterRxCpltCallback(hsmbus); #else HAL_SMBUS_MasterRxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else { /* Nothing to do */ } } } else { /* Nothing to do */ } /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_OK; } /** * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param StatusFlags Value of Interrupt Flags. * @retval HAL status */ static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) { uint8_t TransferDirection; uint16_t SlaveAddrCode; /* Process Locked */ __HAL_LOCK(hsmbus); if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) { /* Check that SMBUS transfer finished */ /* if yes, normal usecase, a NACK is sent by the HOST when Transfer is finished */ /* Mean XferCount == 0*/ /* So clear Flag NACKF only */ if (hsmbus->XferCount == 0U) { /* Clear NACK Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); /* Flush TX register */ SMBUS_Flush_TXDR(hsmbus); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); } else { /* if no, error usecase, a Non-Acknowledge of last Data is generated by the HOST*/ /* Clear NACK Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); /* Set HAL State to "Idle" State, mean to LISTEN state */ /* So reset Slave Busy state */ hsmbus->PreviousState = hsmbus->State; hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); /* Disable RX/TX Interrupts, keep only ADDR Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); /* Set ErrorCode corresponding to a Non-Acknowledge */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; /* Flush TX register */ SMBUS_Flush_TXDR(hsmbus); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the Error callback to inform upper layer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->ErrorCallback(hsmbus); #else HAL_SMBUS_ErrorCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_ADDR) != RESET) { TransferDirection = (uint8_t)(SMBUS_GET_DIR(hsmbus)); SlaveAddrCode = (uint16_t)(SMBUS_GET_ADDR_MATCH(hsmbus)); /* Disable ADDR interrupt to prevent multiple ADDRInterrupt*/ /* Other ADDRInterrupt will be treat in next Listen usecase */ __HAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ADDRI); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call Slave Addr callback */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); #else HAL_SMBUS_AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else if ((SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) || (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET)) { if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) { /* Read data from RXDR */ *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); /* Increment Buffer pointer */ hsmbus->pBuffPtr++; hsmbus->XferSize--; hsmbus->XferCount--; if (hsmbus->XferCount == 1U) { /* Receive last Byte, can be PEC byte in case of PEC BYTE enabled */ /* or only the last Byte of Transfer */ /* So reset the RELOAD bit mode */ hsmbus->XferOptions &= ~SMBUS_RELOAD_MODE; SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); } else if (hsmbus->XferCount == 0U) { /* Last Byte is received, disable Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_RX, keep only HAL_SMBUS_STATE_LISTEN */ hsmbus->PreviousState = hsmbus->State; hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->SlaveRxCpltCallback(hsmbus); #else HAL_SMBUS_SlaveRxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } else { /* Set Reload for next Bytes */ SMBUS_TransferConfig(hsmbus, 0, 1, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_NO_STARTSTOP); /* Ack last Byte Read */ hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; } } else if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) { if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) { if (hsmbus->XferCount > MAX_NBYTE_SIZE) { SMBUS_TransferConfig(hsmbus, 0, MAX_NBYTE_SIZE, (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), SMBUS_NO_STARTSTOP); hsmbus->XferSize = MAX_NBYTE_SIZE; } else { hsmbus->XferSize = hsmbus->XferCount; SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) { hsmbus->XferSize--; hsmbus->XferCount--; } } } } else { /* Nothing to do */ } } else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) { /* Write data to TXDR only if XferCount not reach "0" */ /* A TXIS flag can be set, during STOP treatment */ /* Check if all Data have already been sent */ /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ if (hsmbus->XferCount > 0U) { /* Write data to TXDR */ hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; /* Increment Buffer pointer */ hsmbus->pBuffPtr++; hsmbus->XferCount--; hsmbus->XferSize--; } if (hsmbus->XferCount == 0U) { /* Last Byte is Transmitted */ /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_TX, keep only HAL_SMBUS_STATE_LISTEN */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); hsmbus->PreviousState = hsmbus->State; hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the corresponding callback to inform upper layer of End of Transfer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->SlaveTxCpltCallback(hsmbus); #else HAL_SMBUS_SlaveTxCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } } else { /* Nothing to do */ } /* Check if STOPF is set */ if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) { if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) { /* Store Last receive data if any */ if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) { /* Read data from RXDR */ *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); /* Increment Buffer pointer */ hsmbus->pBuffPtr++; if ((hsmbus->XferSize > 0U)) { hsmbus->XferSize--; hsmbus->XferCount--; } } /* Disable RX and TX Interrupts */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); /* Disable ADDR Interrupt */ SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); /* Disable Address Acknowledge */ hsmbus->Instance->CR2 |= I2C_CR2_NACK; /* Clear Configuration Register 2 */ SMBUS_RESET_CR2(hsmbus); /* Clear STOP Flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); /* Clear ADDR flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); hsmbus->XferOptions = 0; hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->ListenCpltCallback(hsmbus); #else HAL_SMBUS_ListenCpltCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } } /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_OK; } /** * @brief Manage the enabling of Interrupts. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. * @retval HAL status */ static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) { uint32_t tmpisr = 0UL; if ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) { /* Enable ERR interrupt */ tmpisr |= SMBUS_IT_ERRI; } if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) { /* Enable ADDR, STOP interrupt */ tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_ERRI; } if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) { /* Enable ERR, TC, STOP, NACK, RXI interrupt */ tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI; } if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) { /* Enable ERR, TC, STOP, NACK, TXI interrupt */ tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI; } /* Enable interrupts only at the end */ /* to avoid the risk of SMBUS interrupt handle execution before */ /* all interrupts requested done */ __HAL_SMBUS_ENABLE_IT(hsmbus, tmpisr); } /** * @brief Manage the disabling of Interrupts. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. * @retval HAL status */ static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) { uint32_t tmpisr = 0UL; uint32_t tmpstate = hsmbus->State; if ((tmpstate == HAL_SMBUS_STATE_READY) && ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT)) { /* Disable ERR interrupt */ tmpisr |= SMBUS_IT_ERRI; } if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) { /* Disable TC, STOP, NACK and TXI interrupt */ tmpisr |= SMBUS_IT_TCI | SMBUS_IT_TXI; if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) { /* Disable ERR interrupt */ tmpisr |= SMBUS_IT_ERRI; } if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) { /* Disable STOP and NACK interrupt */ tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; } } if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) { /* Disable TC, STOP, NACK and RXI interrupt */ tmpisr |= SMBUS_IT_TCI | SMBUS_IT_RXI; if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) { /* Disable ERR interrupt */ tmpisr |= SMBUS_IT_ERRI; } if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) { /* Disable STOP and NACK interrupt */ tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; } } if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) { /* Disable ADDR, STOP and NACK interrupt */ tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI; if (SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) { /* Disable ERR interrupt */ tmpisr |= SMBUS_IT_ERRI; } } /* Disable interrupts only at the end */ /* to avoid a breaking situation like at "t" time */ /* all disable interrupts request are not done */ __HAL_SMBUS_DISABLE_IT(hsmbus, tmpisr); } /** * @brief SMBUS interrupts error handler. * @param hsmbus SMBUS handle. * @retval None */ static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus) { uint32_t itflags = READ_REG(hsmbus->Instance->ISR); uint32_t itsources = READ_REG(hsmbus->Instance->CR1); uint32_t tmpstate; uint32_t tmperror; /* SMBUS Bus error interrupt occurred ------------------------------------*/ if (((itflags & SMBUS_FLAG_BERR) == SMBUS_FLAG_BERR) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BERR; /* Clear BERR flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); } /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ if (((itflags & SMBUS_FLAG_OVR) == SMBUS_FLAG_OVR) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_OVR; /* Clear OVR flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); } /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ if (((itflags & SMBUS_FLAG_ARLO) == SMBUS_FLAG_ARLO) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ARLO; /* Clear ARLO flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); } /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ if (((itflags & SMBUS_FLAG_TIMEOUT) == SMBUS_FLAG_TIMEOUT) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BUSTIMEOUT; /* Clear TIMEOUT flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); } /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ if (((itflags & SMBUS_FLAG_ALERT) == SMBUS_FLAG_ALERT) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ALERT; /* Clear ALERT flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); } /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ if (((itflags & SMBUS_FLAG_PECERR) == SMBUS_FLAG_PECERR) && \ ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) { hsmbus->ErrorCode |= HAL_SMBUS_ERROR_PECERR; /* Clear PEC error flag */ __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); } /* Flush TX register */ SMBUS_Flush_TXDR(hsmbus); /* Store current volatile hsmbus->ErrorCode, misra rule */ tmperror = hsmbus->ErrorCode; /* Call the Error Callback in case of Error detected */ if ((tmperror != HAL_SMBUS_ERROR_NONE) && (tmperror != HAL_SMBUS_ERROR_ACKF)) { /* Do not Reset the HAL state in case of ALERT error */ if ((tmperror & HAL_SMBUS_ERROR_ALERT) != HAL_SMBUS_ERROR_ALERT) { /* Store current volatile hsmbus->State, misra rule */ tmpstate = hsmbus->State; if (((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) || ((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX)) { /* Reset only HAL_SMBUS_STATE_SLAVE_BUSY_XX */ /* keep HAL_SMBUS_STATE_LISTEN if set */ hsmbus->PreviousState = HAL_SMBUS_STATE_READY; hsmbus->State = HAL_SMBUS_STATE_LISTEN; } } /* Call the Error callback to inform upper layer */ #if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) hsmbus->ErrorCallback(hsmbus); #else HAL_SMBUS_ErrorCallback(hsmbus); #endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ } } /** * @brief Handle SMBUS Communication Timeout. * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains * the configuration information for the specified SMBUS. * @param Flag Specifies the SMBUS flag to check. * @param Status The new Flag status (SET or RESET). * @param Timeout Timeout duration * @retval HAL status */ static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { uint32_t tickstart = HAL_GetTick(); /* Wait until flag is set */ while ((FlagStatus)(__HAL_SMBUS_GET_FLAG(hsmbus, Flag)) == Status) { /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) { hsmbus->PreviousState = hsmbus->State; hsmbus->State = HAL_SMBUS_STATE_READY; /* Update SMBUS error code */ hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hsmbus); return HAL_ERROR; } } } return HAL_OK; } /** * @brief SMBUS Tx data register flush process. * @param hsmbus SMBUS handle. * @retval None */ static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus) { /* If a pending TXIS flag is set */ /* Write a dummy data in TXDR to clear it */ if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) { hsmbus->Instance->TXDR = 0x00U; } /* Flush TX register if not empty */ if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXE) == RESET) { __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TXE); } } /** * @brief Handle SMBUSx communication when starting transfer or during transfer (TC or TCR flag are set). * @param hsmbus SMBUS handle. * @param DevAddress specifies the slave address to be programmed. * @param Size specifies the number of bytes to be programmed. * This parameter must be a value between 0 and 255. * @param Mode New state of the SMBUS START condition generation. * This parameter can be one or a combination of the following values: * @arg @ref SMBUS_RELOAD_MODE Enable Reload mode. * @arg @ref SMBUS_AUTOEND_MODE Enable Automatic end mode. * @arg @ref SMBUS_SOFTEND_MODE Enable Software end mode and Reload mode. * @arg @ref SMBUS_SENDPEC_MODE Enable Packet Error Calculation mode. * @param Request New state of the SMBUS START condition generation. * This parameter can be one of the following values: * @arg @ref SMBUS_NO_STARTSTOP Don't Generate stop and start condition. * @arg @ref SMBUS_GENERATE_STOP Generate stop condition (Size should be set to 0). * @arg @ref SMBUS_GENERATE_START_READ Generate Restart for read request. * @arg @ref SMBUS_GENERATE_START_WRITE Generate Restart for write request. * @retval None */ static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request) { /* Check the parameters */ assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); assert_param(IS_SMBUS_TRANSFER_MODE(Mode)); assert_param(IS_SMBUS_TRANSFER_REQUEST(Request)); /* update CR2 register */ MODIFY_REG(hsmbus->Instance->CR2, ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \ (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31UL - I2C_CR2_RD_WRN_Pos))) | \ I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_PECBYTE)), \ (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \ (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ (uint32_t)Mode | (uint32_t)Request)); } /** * @brief Convert SMBUSx OTHER_xxx XferOptions to functional XferOptions. * @param hsmbus SMBUS handle. * @retval None */ static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus) { /* if user set XferOptions to SMBUS_OTHER_FRAME_NO_PEC */ /* it request implicitly to generate a restart condition */ /* set XferOptions to SMBUS_FIRST_FRAME */ if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_NO_PEC) { hsmbus->XferOptions = SMBUS_FIRST_FRAME; } /* else if user set XferOptions to SMBUS_OTHER_FRAME_WITH_PEC */ /* it request implicitly to generate a restart condition */ /* set XferOptions to SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE */ else if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_WITH_PEC) { hsmbus->XferOptions = SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE; } /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_NO_PEC */ /* it request implicitly to generate a restart condition */ /* then generate a stop condition at the end of transfer */ /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_NO_PEC */ else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_NO_PEC) { hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_NO_PEC; } /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC */ /* it request implicitly to generate a restart condition */ /* then generate a stop condition at the end of transfer */ /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC */ else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC) { hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC; } else { /* Nothing to do */ } } /** * @} */ #endif /* HAL_SMBUS_MODULE_ENABLED */ /** * @} */ /** * @} */
97,071
C
33.805307
118
0.627026
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Src/stm32g4xx_ll_rng.c
/** ****************************************************************************** * @file stm32g4xx_ll_rng.c * @author MCD Application Team * @brief RNG 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_rng.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 (RNG) /** @addtogroup RNG_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup RNG_LL_Private_Macros RNG Private Macros * @{ */ #define IS_LL_RNG_CED(__MODE__) (((__MODE__) == LL_RNG_CED_ENABLE) || \ ((__MODE__) == LL_RNG_CED_DISABLE)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RNG_LL_Exported_Functions * @{ */ /** @addtogroup RNG_LL_EF_Init * @{ */ /** * @brief De-initialize RNG registers (Registers restored to their default values). * @param RNGx RNG Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RNG registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_RNG_DeInit(RNG_TypeDef *RNGx) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_RNG_ALL_INSTANCE(RNGx)); if (RNGx == RNG) { /* Enable RNG reset state */ LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_RNG); /* Release RNG from reset state */ LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_RNG); } else { status = ERROR; } return status; } /** * @brief Initialize RNG registers according to the specified parameters in RNG_InitStruct. * @param RNGx RNG Instance * @param RNG_InitStruct pointer to a LL_RNG_InitTypeDef structure * that contains the configuration information for the specified RNG peripheral. * @retval An ErrorStatus enumeration value: * - SUCCESS: RNG registers are initialized according to RNG_InitStruct content * - ERROR: not applicable */ ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, LL_RNG_InitTypeDef *RNG_InitStruct) { /* Check the parameters */ assert_param(IS_RNG_ALL_INSTANCE(RNGx)); assert_param(IS_LL_RNG_CED(RNG_InitStruct->ClockErrorDetection)); /* Clock Error Detection configuration */ MODIFY_REG(RNGx->CR, RNG_CR_CED, RNG_InitStruct->ClockErrorDetection); return (SUCCESS); } /** * @brief Set each @ref LL_RNG_InitTypeDef field to default value. * @param RNG_InitStruct pointer to a @ref LL_RNG_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_RNG_StructInit(LL_RNG_InitTypeDef *RNG_InitStruct) { /* Set RNG_InitStruct fields to default values */ RNG_InitStruct->ClockErrorDetection = LL_RNG_CED_ENABLE; } /** * @} */ /** * @} */ /** * @} */ #endif /* RNG */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */
3,909
C
25.780822
93
0.535687
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_pwr_ex.h
/** ****************************************************************************** * @file stm32g4xx_hal_pwr_ex.h * @author MCD Application Team * @brief Header file of PWR HAL Extended 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_PWR_EX_H #define STM32G4xx_HAL_PWR_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal_def.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup PWREx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PWREx_Exported_Types PWR Extended Exported Types * @{ */ /** * @brief PWR PVM configuration structure definition */ typedef struct { uint32_t PVMType; /*!< PVMType: Specifies which voltage is monitored and against which threshold. This parameter can be a value of @ref PWREx_PVM_Type. */ uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. This parameter can be a value of @ref PWREx_PVM_Mode. */ }PWR_PVMTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWR Extended Exported Constants * @{ */ /** @defgroup PWREx_WUP_Polarity Shift to apply to retrieve polarity information from PWR_WAKEUP_PINy_xxx constants * @{ */ #define PWR_WUP_POLARITY_SHIFT 0x05U /*!< Internal constant used to retrieve wakeup pin polariry */ /** * @} */ /** @defgroup PWREx_WakeUp_Pins PWR wake-up pins * @{ */ #define PWR_WAKEUP_PIN1 PWR_CR3_EWUP1 /*!< Wakeup pin 1 (with high level polarity) */ #define PWR_WAKEUP_PIN2 PWR_CR3_EWUP2 /*!< Wakeup pin 2 (with high level polarity) */ #define PWR_WAKEUP_PIN3 PWR_CR3_EWUP3 /*!< Wakeup pin 3 (with high level polarity) */ #define PWR_WAKEUP_PIN4 PWR_CR3_EWUP4 /*!< Wakeup pin 4 (with high level polarity) */ #define PWR_WAKEUP_PIN5 PWR_CR3_EWUP5 /*!< Wakeup pin 5 (with high level polarity) */ #define PWR_WAKEUP_PIN1_HIGH PWR_CR3_EWUP1 /*!< Wakeup pin 1 (with high level polarity) */ #define PWR_WAKEUP_PIN2_HIGH PWR_CR3_EWUP2 /*!< Wakeup pin 2 (with high level polarity) */ #define PWR_WAKEUP_PIN3_HIGH PWR_CR3_EWUP3 /*!< Wakeup pin 3 (with high level polarity) */ #define PWR_WAKEUP_PIN4_HIGH PWR_CR3_EWUP4 /*!< Wakeup pin 4 (with high level polarity) */ #define PWR_WAKEUP_PIN5_HIGH PWR_CR3_EWUP5 /*!< Wakeup pin 5 (with high level polarity) */ #define PWR_WAKEUP_PIN1_LOW (uint32_t)((PWR_CR4_WP1<<PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP1) /*!< Wakeup pin 1 (with low level polarity) */ #define PWR_WAKEUP_PIN2_LOW (uint32_t)((PWR_CR4_WP2<<PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP2) /*!< Wakeup pin 2 (with low level polarity) */ #define PWR_WAKEUP_PIN3_LOW (uint32_t)((PWR_CR4_WP3<<PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP3) /*!< Wakeup pin 3 (with low level polarity) */ #define PWR_WAKEUP_PIN4_LOW (uint32_t)((PWR_CR4_WP4<<PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP4) /*!< Wakeup pin 4 (with low level polarity) */ #define PWR_WAKEUP_PIN5_LOW (uint32_t)((PWR_CR4_WP5<<PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP5) /*!< Wakeup pin 5 (with low level polarity) */ /** * @} */ /** @defgroup PWREx_PVM_Type Peripheral Voltage Monitoring type * @{ */ #if defined(PWR_CR2_PVME1) #define PWR_PVM_1 PWR_CR2_PVME1 /*!< Peripheral Voltage Monitoring 1 enable: VDDUSB versus 1.2 V (applicable when USB feature is supported) */ #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) #define PWR_PVM_2 PWR_CR2_PVME2 /*!< Peripheral Voltage Monitoring 2 enable: VDDIO2 versus 0.9 V (applicable when VDDIO2 is present on device) */ #endif /* PWR_CR2_PVME2 */ #define PWR_PVM_3 PWR_CR2_PVME3 /*!< Peripheral Voltage Monitoring 3 enable: VDDA versus 1.62 V */ #define PWR_PVM_4 PWR_CR2_PVME4 /*!< Peripheral Voltage Monitoring 4 enable: VDDA versus 2.2 V */ /** * @} */ /** @defgroup PWREx_PVM_Mode PWR PVM interrupt and event mode * @{ */ #define PWR_PVM_MODE_NORMAL 0x00000000U /*!< basic mode is used */ #define PWR_PVM_MODE_IT_RISING 0x00010001U /*!< External Interrupt Mode with Rising edge trigger detection */ #define PWR_PVM_MODE_IT_FALLING 0x00010002U /*!< External Interrupt Mode with Falling edge trigger detection */ #define PWR_PVM_MODE_IT_RISING_FALLING 0x00010003U /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define PWR_PVM_MODE_EVENT_RISING 0x00020001U /*!< Event Mode with Rising edge trigger detection */ #define PWR_PVM_MODE_EVENT_FALLING 0x00020002U /*!< Event Mode with Falling edge trigger detection */ #define PWR_PVM_MODE_EVENT_RISING_FALLING 0x00020003U /*!< Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup PWREx_Regulator_Voltage_Scale PWR Regulator voltage scale * @{ */ #if defined(PWR_CR5_R1MODE) #define PWR_REGULATOR_VOLTAGE_SCALE1_BOOST ((uint32_t)0x00000000) /*!< Voltage scaling range 1 boost mode */ #endif /*PWR_CR5_R1MODE */ #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR1_VOS_0 /*!< Voltage scaling range 1 normal mode */ #define PWR_REGULATOR_VOLTAGE_SCALE2 PWR_CR1_VOS_1 /*!< Voltage scaling range 2 */ /** * @} */ /** @defgroup PWREx_VBAT_Battery_Charging_Selection PWR battery charging resistor selection * @{ */ #define PWR_BATTERY_CHARGING_RESISTOR_5 0x00000000U /*!< VBAT charging through a 5 kOhms resistor */ #define PWR_BATTERY_CHARGING_RESISTOR_1_5 PWR_CR4_VBRS /*!< VBAT charging through a 1.5 kOhms resistor */ /** * @} */ /** @defgroup PWREx_VBAT_Battery_Charging PWR battery charging * @{ */ #define PWR_BATTERY_CHARGING_DISABLE 0x00000000U #define PWR_BATTERY_CHARGING_ENABLE PWR_CR4_VBE /** * @} */ /** @defgroup PWREx_GPIO_Bit_Number GPIO bit number for I/O setting in standby/shutdown mode * @{ */ #define PWR_GPIO_BIT_0 PWR_PUCRA_PA0 /*!< GPIO port I/O pin 0 */ #define PWR_GPIO_BIT_1 PWR_PUCRA_PA1 /*!< GPIO port I/O pin 1 */ #define PWR_GPIO_BIT_2 PWR_PUCRA_PA2 /*!< GPIO port I/O pin 2 */ #define PWR_GPIO_BIT_3 PWR_PUCRA_PA3 /*!< GPIO port I/O pin 3 */ #define PWR_GPIO_BIT_4 PWR_PUCRA_PA4 /*!< GPIO port I/O pin 4 */ #define PWR_GPIO_BIT_5 PWR_PUCRA_PA5 /*!< GPIO port I/O pin 5 */ #define PWR_GPIO_BIT_6 PWR_PUCRA_PA6 /*!< GPIO port I/O pin 6 */ #define PWR_GPIO_BIT_7 PWR_PUCRA_PA7 /*!< GPIO port I/O pin 7 */ #define PWR_GPIO_BIT_8 PWR_PUCRA_PA8 /*!< GPIO port I/O pin 8 */ #define PWR_GPIO_BIT_9 PWR_PUCRA_PA9 /*!< GPIO port I/O pin 9 */ #define PWR_GPIO_BIT_10 PWR_PUCRA_PA10 /*!< GPIO port I/O pin 10 */ #define PWR_GPIO_BIT_11 PWR_PUCRA_PA11 /*!< GPIO port I/O pin 11 */ #define PWR_GPIO_BIT_12 PWR_PUCRA_PA12 /*!< GPIO port I/O pin 12 */ #define PWR_GPIO_BIT_13 PWR_PUCRA_PA13 /*!< GPIO port I/O pin 13 */ #define PWR_GPIO_BIT_14 PWR_PDCRA_PA14 /*!< GPIO port I/O pin 14 */ #define PWR_GPIO_BIT_15 PWR_PUCRA_PA15 /*!< GPIO port I/O pin 15 */ /** * @} */ /** @defgroup PWREx_GPIO GPIO port * @{ */ #define PWR_GPIO_A 0x00000000U /*!< GPIO port A */ #define PWR_GPIO_B 0x00000001U /*!< GPIO port B */ #define PWR_GPIO_C 0x00000002U /*!< GPIO port C */ #define PWR_GPIO_D 0x00000003U /*!< GPIO port D */ #define PWR_GPIO_E 0x00000004U /*!< GPIO port E */ #define PWR_GPIO_F 0x00000005U /*!< GPIO port F */ #define PWR_GPIO_G 0x00000006U /*!< GPIO port G */ /** * @} */ /** @defgroup PWREx_PVM_EXTI_LINE PWR PVM external interrupts lines * @{ */ #if defined(PWR_CR2_PVME1) #define PWR_EXTI_LINE_PVM1 0x00000008U /*!< External interrupt line 35 Connected to the PVM1 EXTI Line */ #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) #define PWR_EXTI_LINE_PVM2 0x00000010U /*!< External interrupt line 36 Connected to the PVM2 EXTI Line */ #endif /* PWR_CR2_PVME2 */ #define PWR_EXTI_LINE_PVM3 0x00000020U /*!< External interrupt line 37 Connected to the PVM3 EXTI Line */ #define PWR_EXTI_LINE_PVM4 0x00000040U /*!< External interrupt line 38 Connected to the PVM4 EXTI Line */ /** * @} */ /** @defgroup PWREx_PVM_EVENT_LINE PWR PVM event lines * @{ */ #if defined(PWR_CR2_PVME1) #define PWR_EVENT_LINE_PVM1 0x00000008U /*!< Event line 35 Connected to the PVM1 EXTI Line */ #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) #define PWR_EVENT_LINE_PVM2 0x00000010U /*!< Event line 36 Connected to the PVM2 EXTI Line */ #endif /* PWR_CR2_PVME2 */ #define PWR_EVENT_LINE_PVM3 0x00000020U /*!< Event line 37 Connected to the PVM3 EXTI Line */ #define PWR_EVENT_LINE_PVM4 0x00000040U /*!< Event line 38 Connected to the PVM4 EXTI Line */ /** * @} */ /** @defgroup PWREx_Flag PWR Status Flags * Elements values convention: 0000 0000 0XXY YYYYb * - Y YYYY : Flag position in the XX register (5 bits) * - XX : Status register (2 bits) * - 01: SR1 register * - 10: SR2 register * The only exception is PWR_FLAG_WU, encompassing all * wake-up flags and set to PWR_SR1_WUF. * @{ */ #define PWR_FLAG_WUF1 0x0020U /*!< Wakeup event on wakeup pin 1 */ #define PWR_FLAG_WUF2 0x0021U /*!< Wakeup event on wakeup pin 2 */ #define PWR_FLAG_WUF3 0x0022U /*!< Wakeup event on wakeup pin 3 */ #define PWR_FLAG_WUF4 0x0023U /*!< Wakeup event on wakeup pin 4 */ #define PWR_FLAG_WUF5 0x0024U /*!< Wakeup event on wakeup pin 5 */ #define PWR_FLAG_WU PWR_SR1_WUF /*!< Encompass wakeup event on all wakeup pins */ #define PWR_FLAG_SB 0x0028U /*!< Standby flag */ #define PWR_FLAG_WUFI 0x002FU /*!< Wakeup on internal wakeup line */ #define PWR_FLAG_REGLPS 0x0048U /*!< Low-power regulator start flag */ #define PWR_FLAG_REGLPF 0x0049U /*!< Low-power regulator flag */ #define PWR_FLAG_VOSF 0x004AU /*!< Voltage scaling flag */ #define PWR_FLAG_PVDO 0x004BU /*!< Power Voltage Detector output flag */ #if defined(PWR_CR2_PVME1) #define PWR_FLAG_PVMO1 0x004CU /*!< Power Voltage Monitoring 1 output flag */ #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) #define PWR_FLAG_PVMO2 0x004DU /*!< Power Voltage Monitoring 2 output flag */ #endif /* PWR_CR2_PVME2 */ #define PWR_FLAG_PVMO3 0x004EU /*!< Power Voltage Monitoring 3 output flag */ #define PWR_FLAG_PVMO4 0x004FU /*!< Power Voltage Monitoring 4 output flag */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup PWREx_Exported_Macros PWR Extended Exported Macros * @{ */ #if defined(PWR_CR2_PVME1) /** * @brief Enable the PVM1 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM1_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM1) /** * @brief Disable the PVM1 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM1_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM1) /** * @brief Enable the PVM1 Event Line. * @retval None */ #define __HAL_PWR_PVM1_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM1) /** * @brief Disable the PVM1 Event Line. * @retval None */ #define __HAL_PWR_PVM1_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM1) /** * @brief Enable the PVM1 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM1) /** * @brief Disable the PVM1 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM1) /** * @brief Enable the PVM1 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM1) /** * @brief Disable the PVM1 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM1) /** * @brief PVM1 EXTI line configuration: set rising & falling edge trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_ENABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM1_EXTI_ENABLE_RISING_EDGE(); \ __HAL_PWR_PVM1_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the PVM1 Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVM1_EXTI_DISABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM1_EXTI_DISABLE_RISING_EDGE(); \ __HAL_PWR_PVM1_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None */ #define __HAL_PWR_PVM1_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER2, PWR_EXTI_LINE_PVM1) /** * @brief Check whether the specified PVM1 EXTI interrupt flag is set or not. * @retval EXTI PVM1 Line Status. */ #define __HAL_PWR_PVM1_EXTI_GET_FLAG() (EXTI->PR2 & PWR_EXTI_LINE_PVM1) /** * @brief Clear the PVM1 EXTI flag. * @retval None */ #define __HAL_PWR_PVM1_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR2, PWR_EXTI_LINE_PVM1) #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) /** * @brief Enable the PVM2 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM2_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM2) /** * @brief Disable the PVM2 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM2_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM2) /** * @brief Enable the PVM2 Event Line. * @retval None */ #define __HAL_PWR_PVM2_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM2) /** * @brief Disable the PVM2 Event Line. * @retval None */ #define __HAL_PWR_PVM2_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM2) /** * @brief Enable the PVM2 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM2) /** * @brief Disable the PVM2 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM2) /** * @brief Enable the PVM2 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM2) /** * @brief Disable the PVM2 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM2) /** * @brief PVM2 EXTI line configuration: set rising & falling edge trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_ENABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM2_EXTI_ENABLE_RISING_EDGE(); \ __HAL_PWR_PVM2_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the PVM2 Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVM2_EXTI_DISABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM2_EXTI_DISABLE_RISING_EDGE(); \ __HAL_PWR_PVM2_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None */ #define __HAL_PWR_PVM2_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER2, PWR_EXTI_LINE_PVM2) /** * @brief Check whether the specified PVM2 EXTI interrupt flag is set or not. * @retval EXTI PVM2 Line Status. */ #define __HAL_PWR_PVM2_EXTI_GET_FLAG() (EXTI->PR2 & PWR_EXTI_LINE_PVM2) /** * @brief Clear the PVM2 EXTI flag. * @retval None */ #define __HAL_PWR_PVM2_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR2, PWR_EXTI_LINE_PVM2) #endif /* PWR_CR2_PVME2 */ /** * @brief Enable the PVM3 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM3_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM3) /** * @brief Disable the PVM3 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM3_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM3) /** * @brief Enable the PVM3 Event Line. * @retval None */ #define __HAL_PWR_PVM3_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM3) /** * @brief Disable the PVM3 Event Line. * @retval None */ #define __HAL_PWR_PVM3_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM3) /** * @brief Enable the PVM3 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM3) /** * @brief Disable the PVM3 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM3) /** * @brief Enable the PVM3 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM3) /** * @brief Disable the PVM3 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM3) /** * @brief PVM3 EXTI line configuration: set rising & falling edge trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_ENABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM3_EXTI_ENABLE_RISING_EDGE(); \ __HAL_PWR_PVM3_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the PVM3 Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVM3_EXTI_DISABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM3_EXTI_DISABLE_RISING_EDGE(); \ __HAL_PWR_PVM3_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None */ #define __HAL_PWR_PVM3_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER2, PWR_EXTI_LINE_PVM3) /** * @brief Check whether the specified PVM3 EXTI interrupt flag is set or not. * @retval EXTI PVM3 Line Status. */ #define __HAL_PWR_PVM3_EXTI_GET_FLAG() (EXTI->PR2 & PWR_EXTI_LINE_PVM3) /** * @brief Clear the PVM3 EXTI flag. * @retval None */ #define __HAL_PWR_PVM3_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR2, PWR_EXTI_LINE_PVM3) /** * @brief Enable the PVM4 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM4_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM4) /** * @brief Disable the PVM4 Extended Interrupt Line. * @retval None */ #define __HAL_PWR_PVM4_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM4) /** * @brief Enable the PVM4 Event Line. * @retval None */ #define __HAL_PWR_PVM4_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM4) /** * @brief Disable the PVM4 Event Line. * @retval None */ #define __HAL_PWR_PVM4_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM4) /** * @brief Enable the PVM4 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM4) /** * @brief Disable the PVM4 Extended Interrupt Rising Trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM4) /** * @brief Enable the PVM4 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM4) /** * @brief Disable the PVM4 Extended Interrupt Falling Trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM4) /** * @brief PVM4 EXTI line configuration: set rising & falling edge trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_ENABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM4_EXTI_ENABLE_RISING_EDGE(); \ __HAL_PWR_PVM4_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the PVM4 Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVM4_EXTI_DISABLE_RISING_FALLING_EDGE() \ do { \ __HAL_PWR_PVM4_EXTI_DISABLE_RISING_EDGE(); \ __HAL_PWR_PVM4_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None */ #define __HAL_PWR_PVM4_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER2, PWR_EXTI_LINE_PVM4) /** * @brief Check whether or not the specified PVM4 EXTI interrupt flag is set. * @retval EXTI PVM4 Line Status. */ #define __HAL_PWR_PVM4_EXTI_GET_FLAG() (EXTI->PR2 & PWR_EXTI_LINE_PVM4) /** * @brief Clear the PVM4 EXTI flag. * @retval None */ #define __HAL_PWR_PVM4_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR2, PWR_EXTI_LINE_PVM4) /** * @brief Configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption. * This parameter can be one of the following values: * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE1_BOOST Regulator voltage output range 1 mode, * typical output voltage at 1.28 V, * system frequency up to 170 MHz. * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE1 Regulator voltage output range 1 mode, * typical output voltage at 1.2 V, * system frequency up to 150 MHz. * @arg @ref PWR_REGULATOR_VOLTAGE_SCALE2 Regulator voltage output range 2 mode, * typical output voltage at 1.0 V, * system frequency up to 26 MHz. * @note This macro is similar to HAL_PWREx_ControlVoltageScaling() API but doesn't check * whether or not VOSF flag is cleared when moving from range 2 to range 1. User * may resort to __HAL_PWR_GET_FLAG() macro to check VOSF bit resetting. * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ __IO uint32_t tmpreg; \ MODIFY_REG(PWR->CR1, PWR_CR1_VOS, (__REGULATOR__)); \ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(PWR->CR1, PWR_CR1_VOS); \ UNUSED(tmpreg); \ } while(0) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @addtogroup PWREx_Private_Macros PWR Extended Private Macros * @{ */ #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ ((PIN) == PWR_WAKEUP_PIN2) || \ ((PIN) == PWR_WAKEUP_PIN3) || \ ((PIN) == PWR_WAKEUP_PIN4) || \ ((PIN) == PWR_WAKEUP_PIN5) || \ ((PIN) == PWR_WAKEUP_PIN1_HIGH) || \ ((PIN) == PWR_WAKEUP_PIN2_HIGH) || \ ((PIN) == PWR_WAKEUP_PIN3_HIGH) || \ ((PIN) == PWR_WAKEUP_PIN4_HIGH) || \ ((PIN) == PWR_WAKEUP_PIN5_HIGH) || \ ((PIN) == PWR_WAKEUP_PIN1_LOW) || \ ((PIN) == PWR_WAKEUP_PIN2_LOW) || \ ((PIN) == PWR_WAKEUP_PIN3_LOW) || \ ((PIN) == PWR_WAKEUP_PIN4_LOW) || \ ((PIN) == PWR_WAKEUP_PIN5_LOW)) #define IS_PWR_PVM_TYPE(TYPE) (((TYPE) == PWR_PVM_1) ||\ ((TYPE) == PWR_PVM_2) ||\ ((TYPE) == PWR_PVM_3) ||\ ((TYPE) == PWR_PVM_4)) #define IS_PWR_PVM_MODE(MODE) (((MODE) == PWR_PVM_MODE_NORMAL) ||\ ((MODE) == PWR_PVM_MODE_IT_RISING) ||\ ((MODE) == PWR_PVM_MODE_IT_FALLING) ||\ ((MODE) == PWR_PVM_MODE_IT_RISING_FALLING) ||\ ((MODE) == PWR_PVM_MODE_EVENT_RISING) ||\ ((MODE) == PWR_PVM_MODE_EVENT_FALLING) ||\ ((MODE) == PWR_PVM_MODE_EVENT_RISING_FALLING)) #if defined(PWR_CR5_R1MODE) #define IS_PWR_VOLTAGE_SCALING_RANGE(RANGE) (((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE1_BOOST) || \ ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE2)) #else #define IS_PWR_VOLTAGE_SCALING_RANGE(RANGE) (((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE2)) #endif #define IS_PWR_BATTERY_RESISTOR_SELECT(RESISTOR) (((RESISTOR) == PWR_BATTERY_CHARGING_RESISTOR_5) ||\ ((RESISTOR) == PWR_BATTERY_CHARGING_RESISTOR_1_5)) #define IS_PWR_BATTERY_CHARGING(CHARGING) (((CHARGING) == PWR_BATTERY_CHARGING_DISABLE) ||\ ((CHARGING) == PWR_BATTERY_CHARGING_ENABLE)) #define IS_PWR_GPIO_BIT_NUMBER(BIT_NUMBER) (((BIT_NUMBER) & GPIO_PIN_MASK) != (uint32_t)0x00U) #define IS_PWR_GPIO(GPIO) (((GPIO) == PWR_GPIO_A) ||\ ((GPIO) == PWR_GPIO_B) ||\ ((GPIO) == PWR_GPIO_C) ||\ ((GPIO) == PWR_GPIO_D) ||\ ((GPIO) == PWR_GPIO_E) ||\ ((GPIO) == PWR_GPIO_F) ||\ ((GPIO) == PWR_GPIO_G)) /** * @} */ /** @addtogroup PWREx_Exported_Functions PWR Extended Exported Functions * @{ */ /** @addtogroup PWREx_Exported_Functions_Group1 Extended Peripheral Control functions * @{ */ /* Peripheral Control functions **********************************************/ uint32_t HAL_PWREx_GetVoltageRange(void); HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling); void HAL_PWREx_EnableBatteryCharging(uint32_t ResistorSelection); void HAL_PWREx_DisableBatteryCharging(void); void HAL_PWREx_EnableInternalWakeUpLine(void); void HAL_PWREx_DisableInternalWakeUpLine(void); HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber); HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber); HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumber); HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumber); void HAL_PWREx_EnablePullUpPullDownConfig(void); void HAL_PWREx_DisablePullUpPullDownConfig(void); void HAL_PWREx_EnableSRAM2ContentRetention(void); void HAL_PWREx_DisableSRAM2ContentRetention(void); #if defined(PWR_CR2_PVME1) void HAL_PWREx_EnablePVM1(void); void HAL_PWREx_DisablePVM1(void); #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) void HAL_PWREx_EnablePVM2(void); void HAL_PWREx_DisablePVM2(void); #endif /* PWR_CR2_PVME2 */ void HAL_PWREx_EnablePVM3(void); void HAL_PWREx_DisablePVM3(void); void HAL_PWREx_EnablePVM4(void); void HAL_PWREx_DisablePVM4(void); HAL_StatusTypeDef HAL_PWREx_ConfigPVM(PWR_PVMTypeDef *sConfigPVM); /* Low Power modes configuration functions ************************************/ void HAL_PWREx_EnableLowPowerRunMode(void); HAL_StatusTypeDef HAL_PWREx_DisableLowPowerRunMode(void); void HAL_PWREx_EnterSTOP0Mode(uint8_t STOPEntry); void HAL_PWREx_EnterSTOP1Mode(uint8_t STOPEntry); void HAL_PWREx_EnterSHUTDOWNMode(void); void HAL_PWREx_PVD_PVM_IRQHandler(void); #if defined(PWR_CR2_PVME1) void HAL_PWREx_PVM1Callback(void); #endif /* PWR_CR2_PVME1 */ #if defined(PWR_CR2_PVME2) void HAL_PWREx_PVM2Callback(void); #endif /* PWR_CR2_PVME2 */ void HAL_PWREx_PVM3Callback(void); void HAL_PWREx_PVM4Callback(void); #if defined(PWR_CR3_UCPD_STDBY) void HAL_PWREx_EnableUCPDStandbyMode(void); void HAL_PWREx_DisableUCPDStandbyMode(void); #endif /* PWR_CR3_UCPD_STDBY */ #if defined(PWR_CR3_UCPD_DBDIS) void HAL_PWREx_EnableUCPDDeadBattery(void); void HAL_PWREx_DisableUCPDDeadBattery(void); #endif /* PWR_CR3_UCPD_DBDIS */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_PWR_EX_H */
30,700
C
36.531785
163
0.578697
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_fdcan.h
/** ****************************************************************************** * @file stm32g4xx_hal_fdcan.h * @author MCD Application Team * @brief Header file of FDCAN HAL 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_FDCAN_H #define STM32G4xx_HAL_FDCAN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal_def.h" #if defined(FDCAN1) /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup FDCAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FDCAN_Exported_Types FDCAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_FDCAN_STATE_RESET = 0x00U, /*!< FDCAN not yet initialized or disabled */ HAL_FDCAN_STATE_READY = 0x01U, /*!< FDCAN initialized and ready for use */ HAL_FDCAN_STATE_BUSY = 0x02U, /*!< FDCAN process is ongoing */ HAL_FDCAN_STATE_ERROR = 0x03U /*!< FDCAN error state */ } HAL_FDCAN_StateTypeDef; /** * @brief FDCAN Init structure definition */ typedef struct { uint32_t ClockDivider; /*!< Specifies the FDCAN kernel clock divider. The clock is common to all FDCAN instances. This parameter is applied only at initialisation of first FDCAN instance. This parameter can be a value of @ref FDCAN_clock_divider. */ uint32_t FrameFormat; /*!< Specifies the FDCAN frame format. This parameter can be a value of @ref FDCAN_frame_format */ uint32_t Mode; /*!< Specifies the FDCAN mode. This parameter can be a value of @ref FDCAN_operating_mode */ FunctionalState AutoRetransmission; /*!< Enable or disable the automatic retransmission mode. This parameter can be set to ENABLE or DISABLE */ FunctionalState TransmitPause; /*!< Enable or disable the Transmit Pause feature. This parameter can be set to ENABLE or DISABLE */ FunctionalState ProtocolException; /*!< Enable or disable the Protocol Exception Handling. This parameter can be set to ENABLE or DISABLE */ uint32_t NominalPrescaler; /*!< Specifies the value by which the oscillator frequency is divided for generating the nominal bit time quanta. This parameter must be a number between 1 and 512 */ uint32_t NominalSyncJumpWidth; /*!< Specifies the maximum number of time quanta the FDCAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter must be a number between 1 and 128 */ uint32_t NominalTimeSeg1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter must be a number between 2 and 256 */ uint32_t NominalTimeSeg2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter must be a number between 2 and 128 */ uint32_t DataPrescaler; /*!< Specifies the value by which the oscillator frequency is divided for generating the data bit time quanta. This parameter must be a number between 1 and 32 */ uint32_t DataSyncJumpWidth; /*!< Specifies the maximum number of time quanta the FDCAN hardware is allowed to lengthen or shorten a data bit to perform resynchronization. This parameter must be a number between 1 and 16 */ uint32_t DataTimeSeg1; /*!< Specifies the number of time quanta in Data Bit Segment 1. This parameter must be a number between 1 and 32 */ uint32_t DataTimeSeg2; /*!< Specifies the number of time quanta in Data Bit Segment 2. This parameter must be a number between 1 and 16 */ uint32_t StdFiltersNbr; /*!< Specifies the number of standard Message ID filters. This parameter must be a number between 0 and 28 */ uint32_t ExtFiltersNbr; /*!< Specifies the number of extended Message ID filters. This parameter must be a number between 0 and 8 */ uint32_t TxFifoQueueMode; /*!< Tx FIFO/Queue Mode selection. This parameter can be a value of @ref FDCAN_txFifoQueue_Mode */ } FDCAN_InitTypeDef; /** * @brief FDCAN filter structure definition */ typedef struct { uint32_t IdType; /*!< Specifies the identifier type. This parameter can be a value of @ref FDCAN_id_type */ uint32_t FilterIndex; /*!< Specifies the filter which will be initialized. This parameter must be a number between: - 0 and (SRAMCAN_FLS_NBR-1), if IdType is FDCAN_STANDARD_ID - 0 and (SRAMCAN_FLE_NBR-1), if IdType is FDCAN_EXTENDED_ID */ uint32_t FilterType; /*!< Specifies the filter type. This parameter can be a value of @ref FDCAN_filter_type. The value FDCAN_FILTER_RANGE_NO_EIDM is permitted only when IdType is FDCAN_EXTENDED_ID. */ uint32_t FilterConfig; /*!< Specifies the filter configuration. This parameter can be a value of @ref FDCAN_filter_config */ uint32_t FilterID1; /*!< Specifies the filter identification 1. This parameter must be a number between: - 0 and 0x7FF, if IdType is FDCAN_STANDARD_ID - 0 and 0x1FFFFFFF, if IdType is FDCAN_EXTENDED_ID */ uint32_t FilterID2; /*!< Specifies the filter identification 2. This parameter must be a number between: - 0 and 0x7FF, if IdType is FDCAN_STANDARD_ID - 0 and 0x1FFFFFFF, if IdType is FDCAN_EXTENDED_ID */ } FDCAN_FilterTypeDef; /** * @brief FDCAN Tx header structure definition */ typedef struct { uint32_t Identifier; /*!< Specifies the identifier. This parameter must be a number between: - 0 and 0x7FF, if IdType is FDCAN_STANDARD_ID - 0 and 0x1FFFFFFF, if IdType is FDCAN_EXTENDED_ID */ uint32_t IdType; /*!< Specifies the identifier type for the message that will be transmitted. This parameter can be a value of @ref FDCAN_id_type */ uint32_t TxFrameType; /*!< Specifies the frame type of the message that will be transmitted. This parameter can be a value of @ref FDCAN_frame_type */ uint32_t DataLength; /*!< Specifies the length of the frame that will be transmitted. This parameter can be a value of @ref FDCAN_data_length_code */ uint32_t ErrorStateIndicator; /*!< Specifies the error state indicator. This parameter can be a value of @ref FDCAN_error_state_indicator */ uint32_t BitRateSwitch; /*!< Specifies whether the Tx frame will be transmitted with or without bit rate switching. This parameter can be a value of @ref FDCAN_bit_rate_switching */ uint32_t FDFormat; /*!< Specifies whether the Tx frame will be transmitted in classic or FD format. This parameter can be a value of @ref FDCAN_format */ uint32_t TxEventFifoControl; /*!< Specifies the event FIFO control. This parameter can be a value of @ref FDCAN_EFC */ uint32_t MessageMarker; /*!< Specifies the message marker to be copied into Tx Event FIFO element for identification of Tx message status. This parameter must be a number between 0 and 0xFF */ } FDCAN_TxHeaderTypeDef; /** * @brief FDCAN Rx header structure definition */ typedef struct { uint32_t Identifier; /*!< Specifies the identifier. This parameter must be a number between: - 0 and 0x7FF, if IdType is FDCAN_STANDARD_ID - 0 and 0x1FFFFFFF, if IdType is FDCAN_EXTENDED_ID */ uint32_t IdType; /*!< Specifies the identifier type of the received message. This parameter can be a value of @ref FDCAN_id_type */ uint32_t RxFrameType; /*!< Specifies the the received message frame type. This parameter can be a value of @ref FDCAN_frame_type */ uint32_t DataLength; /*!< Specifies the received frame length. This parameter can be a value of @ref FDCAN_data_length_code */ uint32_t ErrorStateIndicator; /*!< Specifies the error state indicator. This parameter can be a value of @ref FDCAN_error_state_indicator */ uint32_t BitRateSwitch; /*!< Specifies whether the Rx frame is received with or without bit rate switching. This parameter can be a value of @ref FDCAN_bit_rate_switching */ uint32_t FDFormat; /*!< Specifies whether the Rx frame is received in classic or FD format. This parameter can be a value of @ref FDCAN_format */ uint32_t RxTimestamp; /*!< Specifies the timestamp counter value captured on start of frame reception. This parameter must be a number between 0 and 0xFFFF */ uint32_t FilterIndex; /*!< Specifies the index of matching Rx acceptance filter element. This parameter must be a number between: - 0 and (SRAMCAN_FLS_NBR-1), if IdType is FDCAN_STANDARD_ID - 0 and (SRAMCAN_FLE_NBR-1), if IdType is FDCAN_EXTENDED_ID */ uint32_t IsFilterMatchingFrame; /*!< Specifies whether the accepted frame did not match any Rx filter. Acceptance of non-matching frames may be enabled via HAL_FDCAN_ConfigGlobalFilter(). This parameter can be 0 or 1 */ } FDCAN_RxHeaderTypeDef; /** * @brief FDCAN Tx event FIFO structure definition */ typedef struct { uint32_t Identifier; /*!< Specifies the identifier. This parameter must be a number between: - 0 and 0x7FF, if IdType is FDCAN_STANDARD_ID - 0 and 0x1FFFFFFF, if IdType is FDCAN_EXTENDED_ID */ uint32_t IdType; /*!< Specifies the identifier type for the transmitted message. This parameter can be a value of @ref FDCAN_id_type */ uint32_t TxFrameType; /*!< Specifies the frame type of the transmitted message. This parameter can be a value of @ref FDCAN_frame_type */ uint32_t DataLength; /*!< Specifies the length of the transmitted frame. This parameter can be a value of @ref FDCAN_data_length_code */ uint32_t ErrorStateIndicator; /*!< Specifies the error state indicator. This parameter can be a value of @ref FDCAN_error_state_indicator */ uint32_t BitRateSwitch; /*!< Specifies whether the Tx frame is transmitted with or without bit rate switching. This parameter can be a value of @ref FDCAN_bit_rate_switching */ uint32_t FDFormat; /*!< Specifies whether the Tx frame is transmitted in classic or FD format. This parameter can be a value of @ref FDCAN_format */ uint32_t TxTimestamp; /*!< Specifies the timestamp counter value captured on start of frame transmission. This parameter must be a number between 0 and 0xFFFF */ uint32_t MessageMarker; /*!< Specifies the message marker copied into Tx Event FIFO element for identification of Tx message status. This parameter must be a number between 0 and 0xFF */ uint32_t EventType; /*!< Specifies the event type. This parameter can be a value of @ref FDCAN_event_type */ } FDCAN_TxEventFifoTypeDef; /** * @brief FDCAN High Priority Message Status structure definition */ typedef struct { uint32_t FilterList; /*!< Specifies the filter list of the matching filter element. This parameter can be: - 0 : Standard Filter List - 1 : Extended Filter List */ uint32_t FilterIndex; /*!< Specifies the index of matching filter element. This parameter can be a number between: - 0 and (SRAMCAN_FLS_NBR-1), if FilterList is 0 (Standard) - 0 and (SRAMCAN_FLE_NBR-1), if FilterList is 1 (Extended) */ uint32_t MessageStorage; /*!< Specifies the HP Message Storage. This parameter can be a value of @ref FDCAN_hp_msg_storage */ uint32_t MessageIndex; /*!< Specifies the Index of Rx FIFO element to which the message was stored. This parameter is valid only when MessageStorage is: FDCAN_HP_STORAGE_RXFIFO0 or FDCAN_HP_STORAGE_RXFIFO1 */ } FDCAN_HpMsgStatusTypeDef; /** * @brief FDCAN Protocol Status structure definition */ typedef struct { uint32_t LastErrorCode; /*!< Specifies the type of the last error that occurred on the FDCAN bus. This parameter can be a value of @ref FDCAN_protocol_error_code */ uint32_t DataLastErrorCode; /*!< Specifies the type of the last error that occurred in the data phase of a CAN FD format frame with its BRS flag set. This parameter can be a value of @ref FDCAN_protocol_error_code */ uint32_t Activity; /*!< Specifies the FDCAN module communication state. This parameter can be a value of @ref FDCAN_communication_state */ uint32_t ErrorPassive; /*!< Specifies the FDCAN module error status. This parameter can be: - 0 : The FDCAN is in Error_Active state - 1 : The FDCAN is in Error_Passive state */ uint32_t Warning; /*!< Specifies the FDCAN module warning status. This parameter can be: - 0 : error counters (RxErrorCnt and TxErrorCnt) are below the Error_Warning limit of 96 - 1 : at least one of error counters has reached the Error_Warning limit of 96 */ uint32_t BusOff; /*!< Specifies the FDCAN module Bus_Off status. This parameter can be: - 0 : The FDCAN is not in Bus_Off state - 1 : The FDCAN is in Bus_Off state */ uint32_t RxESIflag; /*!< Specifies ESI flag of last received CAN FD message. This parameter can be: - 0 : Last received CAN FD message did not have its ESI flag set - 1 : Last received CAN FD message had its ESI flag set */ uint32_t RxBRSflag; /*!< Specifies BRS flag of last received CAN FD message. This parameter can be: - 0 : Last received CAN FD message did not have its BRS flag set - 1 : Last received CAN FD message had its BRS flag set */ uint32_t RxFDFflag; /*!< Specifies if CAN FD message (FDF flag set) has been received since last protocol status.This parameter can be: - 0 : No CAN FD message received - 1 : CAN FD message received */ uint32_t ProtocolException; /*!< Specifies the FDCAN module Protocol Exception status. This parameter can be: - 0 : No protocol exception event occurred since last read access - 1 : Protocol exception event occurred */ uint32_t TDCvalue; /*!< Specifies the Transmitter Delay Compensation Value. This parameter can be a number between 0 and 127 */ } FDCAN_ProtocolStatusTypeDef; /** * @brief FDCAN Error Counters structure definition */ typedef struct { uint32_t TxErrorCnt; /*!< Specifies the Transmit Error Counter Value. This parameter can be a number between 0 and 255 */ uint32_t RxErrorCnt; /*!< Specifies the Receive Error Counter Value. This parameter can be a number between 0 and 127 */ uint32_t RxErrorPassive; /*!< Specifies the Receive Error Passive status. This parameter can be: - 0 : The Receive Error Counter (RxErrorCnt) is below the error passive level of 128 - 1 : The Receive Error Counter (RxErrorCnt) has reached the error passive level of 128 */ uint32_t ErrorLogging; /*!< Specifies the Transmit/Receive error logging counter value. This parameter can be a number between 0 and 255. This counter is incremented each time when a FDCAN protocol error causes the TxErrorCnt or the RxErrorCnt to be incremented. The counter stops at 255; the next increment of TxErrorCnt or RxErrorCnt sets interrupt flag FDCAN_FLAG_ERROR_LOGGING_OVERFLOW */ } FDCAN_ErrorCountersTypeDef; /** * @brief FDCAN Message RAM blocks */ typedef struct { uint32_t StandardFilterSA; /*!< Specifies the Standard Filter List Start Address. This parameter must be a 32-bit word address */ uint32_t ExtendedFilterSA; /*!< Specifies the Extended Filter List Start Address. This parameter must be a 32-bit word address */ uint32_t RxFIFO0SA; /*!< Specifies the Rx FIFO 0 Start Address. This parameter must be a 32-bit word address */ uint32_t RxFIFO1SA; /*!< Specifies the Rx FIFO 1 Start Address. This parameter must be a 32-bit word address */ uint32_t TxEventFIFOSA; /*!< Specifies the Tx Event FIFO Start Address. This parameter must be a 32-bit word address */ uint32_t TxFIFOQSA; /*!< Specifies the Tx FIFO/Queue Start Address. This parameter must be a 32-bit word address */ } FDCAN_MsgRamAddressTypeDef; /** * @brief FDCAN handle structure definition */ #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 typedef struct __FDCAN_HandleTypeDef #else typedef struct #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ { FDCAN_GlobalTypeDef *Instance; /*!< Register base address */ FDCAN_InitTypeDef Init; /*!< FDCAN required parameters */ FDCAN_MsgRamAddressTypeDef msgRam; /*!< FDCAN Message RAM blocks */ uint32_t LatestTxFifoQRequest; /*!< FDCAN Tx buffer index of latest Tx FIFO/Queue request */ __IO HAL_FDCAN_StateTypeDef State; /*!< FDCAN communication state */ HAL_LockTypeDef Lock; /*!< FDCAN locking object */ __IO uint32_t ErrorCode; /*!< FDCAN Error code */ #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 void (* TxEventFifoCallback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs); /*!< FDCAN Tx Event Fifo callback */ void (* RxFifo0Callback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs); /*!< FDCAN Rx Fifo 0 callback */ void (* RxFifo1Callback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs); /*!< FDCAN Rx Fifo 1 callback */ void (* TxFifoEmptyCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Tx Fifo Empty callback */ void (* TxBufferCompleteCallback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); /*!< FDCAN Tx Buffer complete callback */ void (* TxBufferAbortCallback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); /*!< FDCAN Tx Buffer abort callback */ void (* HighPriorityMessageCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN High priority message callback */ void (* TimestampWraparoundCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Timestamp wraparound callback */ void (* TimeoutOccurredCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Timeout occurred callback */ void (* ErrorCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Error callback */ void (* ErrorStatusCallback)(struct __FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs); /*!< FDCAN Error status callback */ void (* MspInitCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Msp Init callback */ void (* MspDeInitCallback)(struct __FDCAN_HandleTypeDef *hfdcan); /*!< FDCAN Msp DeInit callback */ #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ } FDCAN_HandleTypeDef; #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 /** * @brief HAL FDCAN common Callback ID enumeration definition */ typedef enum { HAL_FDCAN_TX_FIFO_EMPTY_CB_ID = 0x00U, /*!< FDCAN Tx Fifo Empty callback ID */ HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID = 0x01U, /*!< FDCAN High priority message callback ID */ HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID = 0x02U, /*!< FDCAN Timestamp wraparound callback ID */ HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID = 0x03U, /*!< FDCAN Timeout occurred callback ID */ HAL_FDCAN_ERROR_CALLBACK_CB_ID = 0x04U, /*!< FDCAN Error callback ID */ HAL_FDCAN_MSPINIT_CB_ID = 0x05U, /*!< FDCAN MspInit callback ID */ HAL_FDCAN_MSPDEINIT_CB_ID = 0x06U, /*!< FDCAN MspDeInit callback ID */ } HAL_FDCAN_CallbackIDTypeDef; /** * @brief HAL FDCAN Callback pointer definition */ typedef void (*pFDCAN_CallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan); /*!< pointer to a common FDCAN callback function */ typedef void (*pFDCAN_TxEventFifoCallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs); /*!< pointer to Tx event Fifo FDCAN callback function */ typedef void (*pFDCAN_RxFifo0CallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs); /*!< pointer to Rx Fifo 0 FDCAN callback function */ typedef void (*pFDCAN_RxFifo1CallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs); /*!< pointer to Rx Fifo 1 FDCAN callback function */ typedef void (*pFDCAN_TxBufferCompleteCallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); /*!< pointer to Tx Buffer complete FDCAN callback function */ typedef void (*pFDCAN_TxBufferAbortCallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); /*!< pointer to Tx Buffer abort FDCAN callback function */ typedef void (*pFDCAN_ErrorStatusCallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs); /*!< pointer to Error Status callback function */ #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FDCAN_Exported_Constants FDCAN Exported Constants * @{ */ /** @defgroup HAL_FDCAN_Error_Code HAL FDCAN Error Code * @{ */ #define HAL_FDCAN_ERROR_NONE ((uint32_t)0x00000000U) /*!< No error */ #define HAL_FDCAN_ERROR_TIMEOUT ((uint32_t)0x00000001U) /*!< Timeout error */ #define HAL_FDCAN_ERROR_NOT_INITIALIZED ((uint32_t)0x00000002U) /*!< Peripheral not initialized */ #define HAL_FDCAN_ERROR_NOT_READY ((uint32_t)0x00000004U) /*!< Peripheral not ready */ #define HAL_FDCAN_ERROR_NOT_STARTED ((uint32_t)0x00000008U) /*!< Peripheral not started */ #define HAL_FDCAN_ERROR_NOT_SUPPORTED ((uint32_t)0x00000010U) /*!< Mode not supported */ #define HAL_FDCAN_ERROR_PARAM ((uint32_t)0x00000020U) /*!< Parameter error */ #define HAL_FDCAN_ERROR_PENDING ((uint32_t)0x00000040U) /*!< Pending operation */ #define HAL_FDCAN_ERROR_RAM_ACCESS ((uint32_t)0x00000080U) /*!< Message RAM Access Failure */ #define HAL_FDCAN_ERROR_FIFO_EMPTY ((uint32_t)0x00000100U) /*!< Put element in full FIFO */ #define HAL_FDCAN_ERROR_FIFO_FULL ((uint32_t)0x00000200U) /*!< Get element from empty FIFO */ #define HAL_FDCAN_ERROR_LOG_OVERFLOW FDCAN_IR_ELO /*!< Overflow of CAN Error Logging Counter */ #define HAL_FDCAN_ERROR_RAM_WDG FDCAN_IR_WDI /*!< Message RAM Watchdog event occurred */ #define HAL_FDCAN_ERROR_PROTOCOL_ARBT FDCAN_IR_PEA /*!< Protocol Error in Arbitration Phase (Nominal Bit Time is used) */ #define HAL_FDCAN_ERROR_PROTOCOL_DATA FDCAN_IR_PED /*!< Protocol Error in Data Phase (Data Bit Time is used) */ #define HAL_FDCAN_ERROR_RESERVED_AREA FDCAN_IR_ARA /*!< Access to Reserved Address */ #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 #define HAL_FDCAN_ERROR_INVALID_CALLBACK ((uint32_t)0x00000100U) /*!< Invalid Callback error */ #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup FDCAN_frame_format FDCAN Frame Format * @{ */ #define FDCAN_FRAME_CLASSIC ((uint32_t)0x00000000U) /*!< Classic mode */ #define FDCAN_FRAME_FD_NO_BRS ((uint32_t)FDCAN_CCCR_FDOE) /*!< FD mode without BitRate Switching */ #define FDCAN_FRAME_FD_BRS ((uint32_t)(FDCAN_CCCR_FDOE | FDCAN_CCCR_BRSE)) /*!< FD mode with BitRate Switching */ /** * @} */ /** @defgroup FDCAN_operating_mode FDCAN Operating Mode * @{ */ #define FDCAN_MODE_NORMAL ((uint32_t)0x00000000U) /*!< Normal mode */ #define FDCAN_MODE_RESTRICTED_OPERATION ((uint32_t)0x00000001U) /*!< Restricted Operation mode */ #define FDCAN_MODE_BUS_MONITORING ((uint32_t)0x00000002U) /*!< Bus Monitoring mode */ #define FDCAN_MODE_INTERNAL_LOOPBACK ((uint32_t)0x00000003U) /*!< Internal LoopBack mode */ #define FDCAN_MODE_EXTERNAL_LOOPBACK ((uint32_t)0x00000004U) /*!< External LoopBack mode */ /** * @} */ /** @defgroup FDCAN_clock_divider FDCAN Clock Divider * @{ */ #define FDCAN_CLOCK_DIV1 ((uint32_t)0x00000000U) /*!< Divide kernel clock by 1 */ #define FDCAN_CLOCK_DIV2 ((uint32_t)0x00000001U) /*!< Divide kernel clock by 2 */ #define FDCAN_CLOCK_DIV4 ((uint32_t)0x00000002U) /*!< Divide kernel clock by 4 */ #define FDCAN_CLOCK_DIV6 ((uint32_t)0x00000003U) /*!< Divide kernel clock by 6 */ #define FDCAN_CLOCK_DIV8 ((uint32_t)0x00000004U) /*!< Divide kernel clock by 8 */ #define FDCAN_CLOCK_DIV10 ((uint32_t)0x00000005U) /*!< Divide kernel clock by 10 */ #define FDCAN_CLOCK_DIV12 ((uint32_t)0x00000006U) /*!< Divide kernel clock by 12 */ #define FDCAN_CLOCK_DIV14 ((uint32_t)0x00000007U) /*!< Divide kernel clock by 14 */ #define FDCAN_CLOCK_DIV16 ((uint32_t)0x00000008U) /*!< Divide kernel clock by 16 */ #define FDCAN_CLOCK_DIV18 ((uint32_t)0x00000009U) /*!< Divide kernel clock by 18 */ #define FDCAN_CLOCK_DIV20 ((uint32_t)0x0000000AU) /*!< Divide kernel clock by 20 */ #define FDCAN_CLOCK_DIV22 ((uint32_t)0x0000000BU) /*!< Divide kernel clock by 22 */ #define FDCAN_CLOCK_DIV24 ((uint32_t)0x0000000CU) /*!< Divide kernel clock by 24 */ #define FDCAN_CLOCK_DIV26 ((uint32_t)0x0000000DU) /*!< Divide kernel clock by 26 */ #define FDCAN_CLOCK_DIV28 ((uint32_t)0x0000000EU) /*!< Divide kernel clock by 28 */ #define FDCAN_CLOCK_DIV30 ((uint32_t)0x0000000FU) /*!< Divide kernel clock by 30 */ /** * @} */ /** @defgroup FDCAN_txFifoQueue_Mode FDCAN Tx FIFO/Queue Mode * @{ */ #define FDCAN_TX_FIFO_OPERATION ((uint32_t)0x00000000U) /*!< FIFO mode */ #define FDCAN_TX_QUEUE_OPERATION ((uint32_t)FDCAN_TXBC_TFQM) /*!< Queue mode */ /** * @} */ /** @defgroup FDCAN_id_type FDCAN ID Type * @{ */ #define FDCAN_STANDARD_ID ((uint32_t)0x00000000U) /*!< Standard ID element */ #define FDCAN_EXTENDED_ID ((uint32_t)0x40000000U) /*!< Extended ID element */ /** * @} */ /** @defgroup FDCAN_frame_type FDCAN Frame Type * @{ */ #define FDCAN_DATA_FRAME ((uint32_t)0x00000000U) /*!< Data frame */ #define FDCAN_REMOTE_FRAME ((uint32_t)0x20000000U) /*!< Remote frame */ /** * @} */ /** @defgroup FDCAN_data_length_code FDCAN Data Length Code * @{ */ #define FDCAN_DLC_BYTES_0 ((uint32_t)0x00000000U) /*!< 0 bytes data field */ #define FDCAN_DLC_BYTES_1 ((uint32_t)0x00010000U) /*!< 1 bytes data field */ #define FDCAN_DLC_BYTES_2 ((uint32_t)0x00020000U) /*!< 2 bytes data field */ #define FDCAN_DLC_BYTES_3 ((uint32_t)0x00030000U) /*!< 3 bytes data field */ #define FDCAN_DLC_BYTES_4 ((uint32_t)0x00040000U) /*!< 4 bytes data field */ #define FDCAN_DLC_BYTES_5 ((uint32_t)0x00050000U) /*!< 5 bytes data field */ #define FDCAN_DLC_BYTES_6 ((uint32_t)0x00060000U) /*!< 6 bytes data field */ #define FDCAN_DLC_BYTES_7 ((uint32_t)0x00070000U) /*!< 7 bytes data field */ #define FDCAN_DLC_BYTES_8 ((uint32_t)0x00080000U) /*!< 8 bytes data field */ #define FDCAN_DLC_BYTES_12 ((uint32_t)0x00090000U) /*!< 12 bytes data field */ #define FDCAN_DLC_BYTES_16 ((uint32_t)0x000A0000U) /*!< 16 bytes data field */ #define FDCAN_DLC_BYTES_20 ((uint32_t)0x000B0000U) /*!< 20 bytes data field */ #define FDCAN_DLC_BYTES_24 ((uint32_t)0x000C0000U) /*!< 24 bytes data field */ #define FDCAN_DLC_BYTES_32 ((uint32_t)0x000D0000U) /*!< 32 bytes data field */ #define FDCAN_DLC_BYTES_48 ((uint32_t)0x000E0000U) /*!< 48 bytes data field */ #define FDCAN_DLC_BYTES_64 ((uint32_t)0x000F0000U) /*!< 64 bytes data field */ /** * @} */ /** @defgroup FDCAN_error_state_indicator FDCAN Error State Indicator * @{ */ #define FDCAN_ESI_ACTIVE ((uint32_t)0x00000000U) /*!< Transmitting node is error active */ #define FDCAN_ESI_PASSIVE ((uint32_t)0x80000000U) /*!< Transmitting node is error passive */ /** * @} */ /** @defgroup FDCAN_bit_rate_switching FDCAN Bit Rate Switching * @{ */ #define FDCAN_BRS_OFF ((uint32_t)0x00000000U) /*!< FDCAN frames transmitted/received without bit rate switching */ #define FDCAN_BRS_ON ((uint32_t)0x00100000U) /*!< FDCAN frames transmitted/received with bit rate switching */ /** * @} */ /** @defgroup FDCAN_format FDCAN format * @{ */ #define FDCAN_CLASSIC_CAN ((uint32_t)0x00000000U) /*!< Frame transmitted/received in Classic CAN format */ #define FDCAN_FD_CAN ((uint32_t)0x00200000U) /*!< Frame transmitted/received in FDCAN format */ /** * @} */ /** @defgroup FDCAN_EFC FDCAN Event FIFO control * @{ */ #define FDCAN_NO_TX_EVENTS ((uint32_t)0x00000000U) /*!< Do not store Tx events */ #define FDCAN_STORE_TX_EVENTS ((uint32_t)0x00800000U) /*!< Store Tx events */ /** * @} */ /** @defgroup FDCAN_filter_type FDCAN Filter Type * @{ */ #define FDCAN_FILTER_RANGE ((uint32_t)0x00000000U) /*!< Range filter from FilterID1 to FilterID2 */ #define FDCAN_FILTER_DUAL ((uint32_t)0x00000001U) /*!< Dual ID filter for FilterID1 or FilterID2 */ #define FDCAN_FILTER_MASK ((uint32_t)0x00000002U) /*!< Classic filter: FilterID1 = filter, FilterID2 = mask */ #define FDCAN_FILTER_RANGE_NO_EIDM ((uint32_t)0x00000003U) /*!< Range filter from FilterID1 to FilterID2, EIDM mask not applied */ /** * @} */ /** @defgroup FDCAN_filter_config FDCAN Filter Configuration * @{ */ #define FDCAN_FILTER_DISABLE ((uint32_t)0x00000000U) /*!< Disable filter element */ #define FDCAN_FILTER_TO_RXFIFO0 ((uint32_t)0x00000001U) /*!< Store in Rx FIFO 0 if filter matches */ #define FDCAN_FILTER_TO_RXFIFO1 ((uint32_t)0x00000002U) /*!< Store in Rx FIFO 1 if filter matches */ #define FDCAN_FILTER_REJECT ((uint32_t)0x00000003U) /*!< Reject ID if filter matches */ #define FDCAN_FILTER_HP ((uint32_t)0x00000004U) /*!< Set high priority if filter matches */ #define FDCAN_FILTER_TO_RXFIFO0_HP ((uint32_t)0x00000005U) /*!< Set high priority and store in FIFO 0 if filter matches */ #define FDCAN_FILTER_TO_RXFIFO1_HP ((uint32_t)0x00000006U) /*!< Set high priority and store in FIFO 1 if filter matches */ /** * @} */ /** @defgroup FDCAN_Tx_location FDCAN Tx Location * @{ */ #define FDCAN_TX_BUFFER0 ((uint32_t)0x00000001U) /*!< Add message to Tx Buffer 0 */ #define FDCAN_TX_BUFFER1 ((uint32_t)0x00000002U) /*!< Add message to Tx Buffer 1 */ #define FDCAN_TX_BUFFER2 ((uint32_t)0x00000004U) /*!< Add message to Tx Buffer 2 */ /** * @} */ /** @defgroup FDCAN_Rx_location FDCAN Rx Location * @{ */ #define FDCAN_RX_FIFO0 ((uint32_t)0x00000040U) /*!< Get received message from Rx FIFO 0 */ #define FDCAN_RX_FIFO1 ((uint32_t)0x00000041U) /*!< Get received message from Rx FIFO 1 */ /** * @} */ /** @defgroup FDCAN_event_type FDCAN Event Type * @{ */ #define FDCAN_TX_EVENT ((uint32_t)0x00400000U) /*!< Tx event */ #define FDCAN_TX_IN_SPITE_OF_ABORT ((uint32_t)0x00800000U) /*!< Transmission in spite of cancellation */ /** * @} */ /** @defgroup FDCAN_hp_msg_storage FDCAN High Priority Message Storage * @{ */ #define FDCAN_HP_STORAGE_NO_FIFO ((uint32_t)0x00000000U) /*!< No FIFO selected */ #define FDCAN_HP_STORAGE_MSG_LOST ((uint32_t)0x00000040U) /*!< FIFO message lost */ #define FDCAN_HP_STORAGE_RXFIFO0 ((uint32_t)0x00000080U) /*!< Message stored in FIFO 0 */ #define FDCAN_HP_STORAGE_RXFIFO1 ((uint32_t)0x000000C0U) /*!< Message stored in FIFO 1 */ /** * @} */ /** @defgroup FDCAN_protocol_error_code FDCAN protocol error code * @{ */ #define FDCAN_PROTOCOL_ERROR_NONE ((uint32_t)0x00000000U) /*!< No error occurred */ #define FDCAN_PROTOCOL_ERROR_STUFF ((uint32_t)0x00000001U) /*!< Stuff error */ #define FDCAN_PROTOCOL_ERROR_FORM ((uint32_t)0x00000002U) /*!< Form error */ #define FDCAN_PROTOCOL_ERROR_ACK ((uint32_t)0x00000003U) /*!< Acknowledge error */ #define FDCAN_PROTOCOL_ERROR_BIT1 ((uint32_t)0x00000004U) /*!< Bit 1 (recessive) error */ #define FDCAN_PROTOCOL_ERROR_BIT0 ((uint32_t)0x00000005U) /*!< Bit 0 (dominant) error */ #define FDCAN_PROTOCOL_ERROR_CRC ((uint32_t)0x00000006U) /*!< CRC check sum error */ #define FDCAN_PROTOCOL_ERROR_NO_CHANGE ((uint32_t)0x00000007U) /*!< No change since last read */ /** * @} */ /** @defgroup FDCAN_communication_state FDCAN communication state * @{ */ #define FDCAN_COM_STATE_SYNC ((uint32_t)0x00000000U) /*!< Node is synchronizing on CAN communication */ #define FDCAN_COM_STATE_IDLE ((uint32_t)0x00000008U) /*!< Node is neither receiver nor transmitter */ #define FDCAN_COM_STATE_RX ((uint32_t)0x00000010U) /*!< Node is operating as receiver */ #define FDCAN_COM_STATE_TX ((uint32_t)0x00000018U) /*!< Node is operating as transmitter */ /** * @} */ /** @defgroup FDCAN_Rx_FIFO_operation_mode FDCAN FIFO operation mode * @{ */ #define FDCAN_RX_FIFO_BLOCKING ((uint32_t)0x00000000U) /*!< Rx FIFO blocking mode */ #define FDCAN_RX_FIFO_OVERWRITE ((uint32_t)0x00000001U) /*!< Rx FIFO overwrite mode */ /** * @} */ /** @defgroup FDCAN_Non_Matching_Frames FDCAN non-matching frames * @{ */ #define FDCAN_ACCEPT_IN_RX_FIFO0 ((uint32_t)0x00000000U) /*!< Accept in Rx FIFO 0 */ #define FDCAN_ACCEPT_IN_RX_FIFO1 ((uint32_t)0x00000001U) /*!< Accept in Rx FIFO 1 */ #define FDCAN_REJECT ((uint32_t)0x00000002U) /*!< Reject */ /** * @} */ /** @defgroup FDCAN_Reject_Remote_Frames FDCAN reject remote frames * @{ */ #define FDCAN_FILTER_REMOTE ((uint32_t)0x00000000U) /*!< Filter remote frames */ #define FDCAN_REJECT_REMOTE ((uint32_t)0x00000001U) /*!< Reject all remote frames */ /** * @} */ /** @defgroup FDCAN_Interrupt_Line FDCAN interrupt line * @{ */ #define FDCAN_INTERRUPT_LINE0 ((uint32_t)0x00000001U) /*!< Interrupt Line 0 */ #define FDCAN_INTERRUPT_LINE1 ((uint32_t)0x00000002U) /*!< Interrupt Line 1 */ /** * @} */ /** @defgroup FDCAN_Timestamp FDCAN timestamp * @{ */ #define FDCAN_TIMESTAMP_INTERNAL ((uint32_t)0x00000001U) /*!< Timestamp counter value incremented according to TCP */ #define FDCAN_TIMESTAMP_EXTERNAL ((uint32_t)0x00000002U) /*!< External timestamp counter value used */ /** * @} */ /** @defgroup FDCAN_Timestamp_Prescaler FDCAN timestamp prescaler * @{ */ #define FDCAN_TIMESTAMP_PRESC_1 ((uint32_t)0x00000000U) /*!< Timestamp counter time unit in equal to CAN bit time */ #define FDCAN_TIMESTAMP_PRESC_2 ((uint32_t)0x00010000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 2 */ #define FDCAN_TIMESTAMP_PRESC_3 ((uint32_t)0x00020000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 3 */ #define FDCAN_TIMESTAMP_PRESC_4 ((uint32_t)0x00030000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 4 */ #define FDCAN_TIMESTAMP_PRESC_5 ((uint32_t)0x00040000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 5 */ #define FDCAN_TIMESTAMP_PRESC_6 ((uint32_t)0x00050000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 6 */ #define FDCAN_TIMESTAMP_PRESC_7 ((uint32_t)0x00060000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 7 */ #define FDCAN_TIMESTAMP_PRESC_8 ((uint32_t)0x00070000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 8 */ #define FDCAN_TIMESTAMP_PRESC_9 ((uint32_t)0x00080000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 9 */ #define FDCAN_TIMESTAMP_PRESC_10 ((uint32_t)0x00090000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 10 */ #define FDCAN_TIMESTAMP_PRESC_11 ((uint32_t)0x000A0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 11 */ #define FDCAN_TIMESTAMP_PRESC_12 ((uint32_t)0x000B0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 12 */ #define FDCAN_TIMESTAMP_PRESC_13 ((uint32_t)0x000C0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 13 */ #define FDCAN_TIMESTAMP_PRESC_14 ((uint32_t)0x000D0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 14 */ #define FDCAN_TIMESTAMP_PRESC_15 ((uint32_t)0x000E0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 15 */ #define FDCAN_TIMESTAMP_PRESC_16 ((uint32_t)0x000F0000U) /*!< Timestamp counter time unit in equal to CAN bit time multiplied by 16 */ /** * @} */ /** @defgroup FDCAN_Timeout_Operation FDCAN timeout operation * @{ */ #define FDCAN_TIMEOUT_CONTINUOUS ((uint32_t)0x00000000U) /*!< Timeout continuous operation */ #define FDCAN_TIMEOUT_TX_EVENT_FIFO ((uint32_t)0x00000002U) /*!< Timeout controlled by Tx Event FIFO */ #define FDCAN_TIMEOUT_RX_FIFO0 ((uint32_t)0x00000004U) /*!< Timeout controlled by Rx FIFO 0 */ #define FDCAN_TIMEOUT_RX_FIFO1 ((uint32_t)0x00000006U) /*!< Timeout controlled by Rx FIFO 1 */ /** * @} */ /** @defgroup Interrupt_Masks Interrupt masks * @{ */ #define FDCAN_IR_MASK ((uint32_t)0x00FFFFFFU) /*!< FDCAN interrupts mask */ #define FDCAN_ILS_MASK ((uint32_t)0x0000007FU) /*!< FDCAN interrupts group mask */ /** * @} */ /** @defgroup FDCAN_flags FDCAN Flags * @{ */ #define FDCAN_FLAG_TX_COMPLETE FDCAN_IR_TC /*!< Transmission Completed */ #define FDCAN_FLAG_TX_ABORT_COMPLETE FDCAN_IR_TCF /*!< Transmission Cancellation Finished */ #define FDCAN_FLAG_TX_FIFO_EMPTY FDCAN_IR_TFE /*!< Tx FIFO Empty */ #define FDCAN_FLAG_RX_HIGH_PRIORITY_MSG FDCAN_IR_HPM /*!< High priority message received */ #define FDCAN_FLAG_TX_EVT_FIFO_ELT_LOST FDCAN_IR_TEFL /*!< Tx Event FIFO element lost */ #define FDCAN_FLAG_TX_EVT_FIFO_FULL FDCAN_IR_TEFF /*!< Tx Event FIFO full */ #define FDCAN_FLAG_TX_EVT_FIFO_NEW_DATA FDCAN_IR_TEFN /*!< Tx Handler wrote Tx Event FIFO element */ #define FDCAN_FLAG_RX_FIFO0_MESSAGE_LOST FDCAN_IR_RF0L /*!< Rx FIFO 0 message lost */ #define FDCAN_FLAG_RX_FIFO0_FULL FDCAN_IR_RF0F /*!< Rx FIFO 0 full */ #define FDCAN_FLAG_RX_FIFO0_NEW_MESSAGE FDCAN_IR_RF0N /*!< New message written to Rx FIFO 0 */ #define FDCAN_FLAG_RX_FIFO1_MESSAGE_LOST FDCAN_IR_RF1L /*!< Rx FIFO 1 message lost */ #define FDCAN_FLAG_RX_FIFO1_FULL FDCAN_IR_RF1F /*!< Rx FIFO 1 full */ #define FDCAN_FLAG_RX_FIFO1_NEW_MESSAGE FDCAN_IR_RF1N /*!< New message written to Rx FIFO 1 */ #define FDCAN_FLAG_RAM_ACCESS_FAILURE FDCAN_IR_MRAF /*!< Message RAM access failure occurred */ #define FDCAN_FLAG_ERROR_LOGGING_OVERFLOW FDCAN_IR_ELO /*!< Overflow of FDCAN Error Logging Counter occurred */ #define FDCAN_FLAG_ERROR_PASSIVE FDCAN_IR_EP /*!< Error_Passive status changed */ #define FDCAN_FLAG_ERROR_WARNING FDCAN_IR_EW /*!< Error_Warning status changed */ #define FDCAN_FLAG_BUS_OFF FDCAN_IR_BO /*!< Bus_Off status changed */ #define FDCAN_FLAG_RAM_WATCHDOG FDCAN_IR_WDI /*!< Message RAM Watchdog event due to missing READY */ #define FDCAN_FLAG_ARB_PROTOCOL_ERROR FDCAN_IR_PEA /*!< Protocol error in arbitration phase detected */ #define FDCAN_FLAG_DATA_PROTOCOL_ERROR FDCAN_IR_PED /*!< Protocol error in data phase detected */ #define FDCAN_FLAG_RESERVED_ADDRESS_ACCESS FDCAN_IR_ARA /*!< Access to reserved address occurred */ #define FDCAN_FLAG_TIMESTAMP_WRAPAROUND FDCAN_IR_TSW /*!< Timestamp counter wrapped around */ #define FDCAN_FLAG_TIMEOUT_OCCURRED FDCAN_IR_TOO /*!< Timeout reached */ /** * @} */ /** @defgroup FDCAN_Interrupts FDCAN Interrupts * @{ */ /** @defgroup FDCAN_Tx_Interrupts FDCAN Tx Interrupts * @{ */ #define FDCAN_IT_TX_COMPLETE FDCAN_IE_TCE /*!< Transmission Completed */ #define FDCAN_IT_TX_ABORT_COMPLETE FDCAN_IE_TCFE /*!< Transmission Cancellation Finished */ #define FDCAN_IT_TX_FIFO_EMPTY FDCAN_IE_TFEE /*!< Tx FIFO Empty */ /** * @} */ /** @defgroup FDCAN_Rx_Interrupts FDCAN Rx Interrupts * @{ */ #define FDCAN_IT_RX_HIGH_PRIORITY_MSG FDCAN_IE_HPME /*!< High priority message received */ /** * @} */ /** @defgroup FDCAN_Counter_Interrupts FDCAN Counter Interrupts * @{ */ #define FDCAN_IT_TIMESTAMP_WRAPAROUND FDCAN_IE_TSWE /*!< Timestamp counter wrapped around */ #define FDCAN_IT_TIMEOUT_OCCURRED FDCAN_IE_TOOE /*!< Timeout reached */ /** * @} */ /** @defgroup FDCAN_Tx_Event_Fifo_Interrupts FDCAN Tx Event FIFO Interrupts * @{ */ #define FDCAN_IT_TX_EVT_FIFO_ELT_LOST FDCAN_IE_TEFLE /*!< Tx Event FIFO element lost */ #define FDCAN_IT_TX_EVT_FIFO_FULL FDCAN_IE_TEFFE /*!< Tx Event FIFO full */ #define FDCAN_IT_TX_EVT_FIFO_NEW_DATA FDCAN_IE_TEFNE /*!< Tx Handler wrote Tx Event FIFO element */ /** * @} */ /** @defgroup FDCAN_Rx_Fifo0_Interrupts FDCAN Rx FIFO 0 Interrupts * @{ */ #define FDCAN_IT_RX_FIFO0_MESSAGE_LOST FDCAN_IE_RF0LE /*!< Rx FIFO 0 message lost */ #define FDCAN_IT_RX_FIFO0_FULL FDCAN_IE_RF0FE /*!< Rx FIFO 0 full */ #define FDCAN_IT_RX_FIFO0_NEW_MESSAGE FDCAN_IE_RF0NE /*!< New message written to Rx FIFO 0 */ /** * @} */ /** @defgroup FDCAN_Rx_Fifo1_Interrupts FDCAN Rx FIFO 1 Interrupts * @{ */ #define FDCAN_IT_RX_FIFO1_MESSAGE_LOST FDCAN_IE_RF1LE /*!< Rx FIFO 1 message lost */ #define FDCAN_IT_RX_FIFO1_FULL FDCAN_IE_RF1FE /*!< Rx FIFO 1 full */ #define FDCAN_IT_RX_FIFO1_NEW_MESSAGE FDCAN_IE_RF1NE /*!< New message written to Rx FIFO 1 */ /** * @} */ /** @defgroup FDCAN_Error_Interrupts FDCAN Error Interrupts * @{ */ #define FDCAN_IT_RAM_ACCESS_FAILURE FDCAN_IE_MRAFE /*!< Message RAM access failure occurred */ #define FDCAN_IT_ERROR_LOGGING_OVERFLOW FDCAN_IE_ELOE /*!< Overflow of FDCAN Error Logging Counter occurred */ #define FDCAN_IT_RAM_WATCHDOG FDCAN_IE_WDIE /*!< Message RAM Watchdog event due to missing READY */ #define FDCAN_IT_ARB_PROTOCOL_ERROR FDCAN_IE_PEAE /*!< Protocol error in arbitration phase detected */ #define FDCAN_IT_DATA_PROTOCOL_ERROR FDCAN_IE_PEDE /*!< Protocol error in data phase detected */ #define FDCAN_IT_RESERVED_ADDRESS_ACCESS FDCAN_IE_ARAE /*!< Access to reserved address occurred */ /** * @} */ /** @defgroup FDCAN_Error_Status_Interrupts FDCAN Error Status Interrupts * @{ */ #define FDCAN_IT_ERROR_PASSIVE FDCAN_IE_EPE /*!< Error_Passive status changed */ #define FDCAN_IT_ERROR_WARNING FDCAN_IE_EWE /*!< Error_Warning status changed */ #define FDCAN_IT_BUS_OFF FDCAN_IE_BOE /*!< Bus_Off status changed */ /** * @} */ /** * @} */ /** @defgroup FDCAN_Interrupts_List FDCAN Interrupts List * @{ */ #define FDCAN_IT_LIST_RX_FIFO0 (FDCAN_IT_RX_FIFO0_MESSAGE_LOST | \ FDCAN_IT_RX_FIFO0_FULL | \ FDCAN_IT_RX_FIFO0_NEW_MESSAGE) /*!< RX FIFO 0 Interrupts List */ #define FDCAN_IT_LIST_RX_FIFO1 (FDCAN_IT_RX_FIFO1_MESSAGE_LOST | \ FDCAN_IT_RX_FIFO1_FULL | \ FDCAN_IT_RX_FIFO1_NEW_MESSAGE) /*!< RX FIFO 1 Interrupts List */ #define FDCAN_IT_LIST_SMSG (FDCAN_IT_TX_ABORT_COMPLETE | \ FDCAN_IT_TX_COMPLETE | \ FDCAN_IT_RX_HIGH_PRIORITY_MSG) /*!< Status Message Interrupts List */ #define FDCAN_IT_LIST_TX_FIFO_ERROR (FDCAN_IT_TX_EVT_FIFO_ELT_LOST | \ FDCAN_IT_TX_EVT_FIFO_FULL | \ FDCAN_IT_TX_EVT_FIFO_NEW_DATA | \ FDCAN_IT_TX_FIFO_EMPTY) /*!< TX FIFO Error Interrupts List */ #define FDCAN_IT_LIST_MISC (FDCAN_IT_TIMEOUT_OCCURRED | \ FDCAN_IT_RAM_ACCESS_FAILURE | \ FDCAN_IT_TIMESTAMP_WRAPAROUND) /*!< Misc. Interrupts List */ #define FDCAN_IT_LIST_BIT_LINE_ERROR (FDCAN_IT_ERROR_PASSIVE | \ FDCAN_IT_ERROR_LOGGING_OVERFLOW) /*!< Bit and Line Error Interrupts List */ #define FDCAN_IT_LIST_PROTOCOL_ERROR (FDCAN_IT_RESERVED_ADDRESS_ACCESS | \ FDCAN_IT_DATA_PROTOCOL_ERROR | \ FDCAN_IT_ARB_PROTOCOL_ERROR | \ FDCAN_IT_RAM_WATCHDOG | \ FDCAN_IT_BUS_OFF | \ FDCAN_IT_ERROR_WARNING) /*!< Protocol Error Interrupts List */ /** * @} */ /** @defgroup FDCAN_Interrupts_Group FDCAN Interrupts Group * @{ */ #define FDCAN_IT_GROUP_RX_FIFO0 FDCAN_ILS_RXFIFO0 /*!< RX FIFO 0 Interrupts Group: RF0LL: Rx FIFO 0 Message Lost RF0FL: Rx FIFO 0 is Full RF0NL: Rx FIFO 0 Has New Message */ #define FDCAN_IT_GROUP_RX_FIFO1 FDCAN_ILS_RXFIFO1 /*!< RX FIFO 1 Interrupts Group: RF1LL: Rx FIFO 1 Message Lost RF1FL: Rx FIFO 1 is Full RF1NL: Rx FIFO 1 Has New Message */ #define FDCAN_IT_GROUP_SMSG FDCAN_ILS_SMSG /*!< Status Message Interrupts Group: TCFL: Transmission Cancellation Finished TCL: Transmission Completed HPML: High Priority Message */ #define FDCAN_IT_GROUP_TX_FIFO_ERROR FDCAN_ILS_TFERR /*!< TX FIFO Error Interrupts Group: TEFLL: Tx Event FIFO Element Lost TEFFL: Tx Event FIFO Full TEFNL: Tx Event FIFO New Entry TFEL: Tx FIFO Empty Interrupt Line */ #define FDCAN_IT_GROUP_MISC FDCAN_ILS_MISC /*!< Misc. Interrupts Group: TOOL: Timeout Occurred MRAFL: Message RAM Access Failure TSWL: Timestamp Wraparound */ #define FDCAN_IT_GROUP_BIT_LINE_ERROR FDCAN_ILS_BERR /*!< Bit and Line Error Interrupts Group: EPL: Error Passive ELOL: Error Logging Overflow */ #define FDCAN_IT_GROUP_PROTOCOL_ERROR FDCAN_ILS_PERR /*!< Protocol Error Group: ARAL: Access to Reserved Address Line PEDL: Protocol Error in Data Phase Line PEAL: Protocol Error in Arbitration Phase Line WDIL: Watchdog Interrupt Line BOL: Bus_Off Status EWL: Warning Status */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FDCAN_Exported_Macros FDCAN Exported Macros * @{ */ /** @brief Reset FDCAN handle state. * @param __HANDLE__ FDCAN handle. * @retval None */ #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 #define __HAL_FDCAN_RESET_HANDLE_STATE(__HANDLE__) do{ \ (__HANDLE__)->State = HAL_FDCAN_STATE_RESET; \ (__HANDLE__)->MspInitCallback = NULL; \ (__HANDLE__)->MspDeInitCallback = NULL; \ } while(0) #else #define __HAL_FDCAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_FDCAN_STATE_RESET) #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ /** * @brief Enable the specified FDCAN interrupts. * @param __HANDLE__ FDCAN handle. * @param __INTERRUPT__ FDCAN interrupt. * This parameter can be any combination of @arg FDCAN_Interrupts * @retval None */ #define __HAL_FDCAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ (__HANDLE__)->Instance->IE |= (__INTERRUPT__) /** * @brief Disable the specified FDCAN interrupts. * @param __HANDLE__ FDCAN handle. * @param __INTERRUPT__ FDCAN interrupt. * This parameter can be any combination of @arg FDCAN_Interrupts * @retval None */ #define __HAL_FDCAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ ((__HANDLE__)->Instance->IE) &= ~(__INTERRUPT__) /** * @brief Check whether the specified FDCAN interrupt is set or not. * @param __HANDLE__ FDCAN handle. * @param __INTERRUPT__ FDCAN interrupt. * This parameter can be one of @arg FDCAN_Interrupts * @retval ITStatus */ #define __HAL_FDCAN_GET_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IR & (__INTERRUPT__)) /** * @brief Clear the specified FDCAN interrupts. * @param __HANDLE__ FDCAN handle. * @param __INTERRUPT__ specifies the interrupts to clear. * This parameter can be any combination of @arg FDCAN_Interrupts * @retval None */ #define __HAL_FDCAN_CLEAR_IT(__HANDLE__, __INTERRUPT__) \ ((__HANDLE__)->Instance->IR) = (__INTERRUPT__) /** * @brief Check whether the specified FDCAN flag is set or not. * @param __HANDLE__ FDCAN handle. * @param __FLAG__ FDCAN flag. * This parameter can be one of @arg FDCAN_flags * @retval FlagStatus */ #define __HAL_FDCAN_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->IR & (__FLAG__)) /** * @brief Clear the specified FDCAN flags. * @param __HANDLE__ FDCAN handle. * @param __FLAG__ specifies the flags to clear. * This parameter can be any combination of @arg FDCAN_flags * @retval None */ #define __HAL_FDCAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((__HANDLE__)->Instance->IR) = (__FLAG__) /** @brief Check if the specified FDCAN interrupt source is enabled or disabled. * @param __HANDLE__ FDCAN handle. * @param __INTERRUPT__ specifies the FDCAN interrupt source to check. * This parameter can be a value of @arg FDCAN_Interrupts * @retval ITStatus */ #define __HAL_FDCAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IE & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FDCAN_Exported_Functions * @{ */ /** @addtogroup FDCAN_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_FDCAN_Init(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_DeInit(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_MspInit(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_MspDeInit(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_EnterPowerDownMode(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ExitPowerDownMode(FDCAN_HandleTypeDef *hfdcan); #if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 /* Callbacks Register/UnRegister functions ***********************************/ HAL_StatusTypeDef HAL_FDCAN_RegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID, pFDCAN_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID); HAL_StatusTypeDef HAL_FDCAN_RegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_TxEventFifoCallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_RxFifo0CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_RxFifo1CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_TxBufferCompleteCallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_TxBufferAbortCallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_RegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, pFDCAN_ErrorStatusCallbackTypeDef pCallback); HAL_StatusTypeDef HAL_FDCAN_UnRegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan); #endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ /** * @} */ /** @addtogroup FDCAN_Exported_Functions_Group2 * @{ */ /* Configuration functions ****************************************************/ HAL_StatusTypeDef HAL_FDCAN_ConfigFilter(FDCAN_HandleTypeDef *hfdcan, FDCAN_FilterTypeDef *sFilterConfig); HAL_StatusTypeDef HAL_FDCAN_ConfigGlobalFilter(FDCAN_HandleTypeDef *hfdcan, uint32_t NonMatchingStd, uint32_t NonMatchingExt, uint32_t RejectRemoteStd, uint32_t RejectRemoteExt); HAL_StatusTypeDef HAL_FDCAN_ConfigExtendedIdMask(FDCAN_HandleTypeDef *hfdcan, uint32_t Mask); HAL_StatusTypeDef HAL_FDCAN_ConfigRxFifoOverwrite(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo, uint32_t OperationMode); HAL_StatusTypeDef HAL_FDCAN_ConfigRamWatchdog(FDCAN_HandleTypeDef *hfdcan, uint32_t CounterStartValue); HAL_StatusTypeDef HAL_FDCAN_ConfigTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampPrescaler); HAL_StatusTypeDef HAL_FDCAN_EnableTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampOperation); HAL_StatusTypeDef HAL_FDCAN_DisableTimestampCounter(FDCAN_HandleTypeDef *hfdcan); uint16_t HAL_FDCAN_GetTimestampCounter(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ResetTimestampCounter(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ConfigTimeoutCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimeoutOperation, uint32_t TimeoutPeriod); HAL_StatusTypeDef HAL_FDCAN_EnableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_DisableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan); uint16_t HAL_FDCAN_GetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ResetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ConfigTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan, uint32_t TdcOffset, uint32_t TdcFilter); HAL_StatusTypeDef HAL_FDCAN_EnableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_DisableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_EnableISOMode(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_DisableISOMode(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_EnableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_DisableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan); /** * @} */ /** @addtogroup FDCAN_Exported_Functions_Group3 * @{ */ /* Control functions **********************************************************/ HAL_StatusTypeDef HAL_FDCAN_Start(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_Stop(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_AddMessageToTxFifoQ(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxHeaderTypeDef *pTxHeader, uint8_t *pTxData); uint32_t HAL_FDCAN_GetLatestTxFifoQRequestBuffer(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_AbortTxRequest(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndex); HAL_StatusTypeDef HAL_FDCAN_GetRxMessage(FDCAN_HandleTypeDef *hfdcan, uint32_t RxLocation, FDCAN_RxHeaderTypeDef *pRxHeader, uint8_t *pRxData); HAL_StatusTypeDef HAL_FDCAN_GetTxEvent(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxEventFifoTypeDef *pTxEvent); HAL_StatusTypeDef HAL_FDCAN_GetHighPriorityMessageStatus(FDCAN_HandleTypeDef *hfdcan, FDCAN_HpMsgStatusTypeDef *HpMsgStatus); HAL_StatusTypeDef HAL_FDCAN_GetProtocolStatus(FDCAN_HandleTypeDef *hfdcan, FDCAN_ProtocolStatusTypeDef *ProtocolStatus); HAL_StatusTypeDef HAL_FDCAN_GetErrorCounters(FDCAN_HandleTypeDef *hfdcan, FDCAN_ErrorCountersTypeDef *ErrorCounters); uint32_t HAL_FDCAN_IsTxBufferMessagePending(FDCAN_HandleTypeDef *hfdcan, uint32_t TxBufferIndex); uint32_t HAL_FDCAN_GetRxFifoFillLevel(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo); uint32_t HAL_FDCAN_GetTxFifoFreeLevel(FDCAN_HandleTypeDef *hfdcan); uint32_t HAL_FDCAN_IsRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan); HAL_StatusTypeDef HAL_FDCAN_ExitRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan); /** * @} */ /** @addtogroup FDCAN_Exported_Functions_Group4 * @{ */ /* Interrupts management ******************************************************/ HAL_StatusTypeDef HAL_FDCAN_ConfigInterruptLines(FDCAN_HandleTypeDef *hfdcan, uint32_t ITList, uint32_t InterruptLine); HAL_StatusTypeDef HAL_FDCAN_ActivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t ActiveITs, uint32_t BufferIndexes); HAL_StatusTypeDef HAL_FDCAN_DeactivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t InactiveITs); void HAL_FDCAN_IRQHandler(FDCAN_HandleTypeDef *hfdcan); /** * @} */ /** @addtogroup FDCAN_Exported_Functions_Group5 * @{ */ /* Callback functions *********************************************************/ void HAL_FDCAN_TxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs); void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs); void HAL_FDCAN_RxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs); void HAL_FDCAN_TxFifoEmptyCallback(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_TxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); void HAL_FDCAN_TxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes); void HAL_FDCAN_HighPriorityMessageCallback(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_TimestampWraparoundCallback(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_TimeoutOccurredCallback(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_ErrorCallback(FDCAN_HandleTypeDef *hfdcan); void HAL_FDCAN_ErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs); /** * @} */ /** @addtogroup FDCAN_Exported_Functions_Group6 * @{ */ /* Peripheral State functions *************************************************/ uint32_t HAL_FDCAN_GetError(FDCAN_HandleTypeDef *hfdcan); HAL_FDCAN_StateTypeDef HAL_FDCAN_GetState(FDCAN_HandleTypeDef *hfdcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup FDCAN_Private_Variables FDCAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FDCAN_Private_Constants FDCAN Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FDCAN_Private_Macros FDCAN Private Macros * @{ */ #define IS_FDCAN_FRAME_FORMAT(FORMAT) (((FORMAT) == FDCAN_FRAME_CLASSIC ) || \ ((FORMAT) == FDCAN_FRAME_FD_NO_BRS) || \ ((FORMAT) == FDCAN_FRAME_FD_BRS )) #define IS_FDCAN_MODE(MODE) (((MODE) == FDCAN_MODE_NORMAL ) || \ ((MODE) == FDCAN_MODE_RESTRICTED_OPERATION) || \ ((MODE) == FDCAN_MODE_BUS_MONITORING ) || \ ((MODE) == FDCAN_MODE_INTERNAL_LOOPBACK ) || \ ((MODE) == FDCAN_MODE_EXTERNAL_LOOPBACK )) #define IS_FDCAN_CKDIV(CKDIV) (((CKDIV) == FDCAN_CLOCK_DIV1 ) || \ ((CKDIV) == FDCAN_CLOCK_DIV2 ) || \ ((CKDIV) == FDCAN_CLOCK_DIV4 ) || \ ((CKDIV) == FDCAN_CLOCK_DIV6 ) || \ ((CKDIV) == FDCAN_CLOCK_DIV8 ) || \ ((CKDIV) == FDCAN_CLOCK_DIV10) || \ ((CKDIV) == FDCAN_CLOCK_DIV12) || \ ((CKDIV) == FDCAN_CLOCK_DIV14) || \ ((CKDIV) == FDCAN_CLOCK_DIV16) || \ ((CKDIV) == FDCAN_CLOCK_DIV18) || \ ((CKDIV) == FDCAN_CLOCK_DIV20) || \ ((CKDIV) == FDCAN_CLOCK_DIV22) || \ ((CKDIV) == FDCAN_CLOCK_DIV24) || \ ((CKDIV) == FDCAN_CLOCK_DIV26) || \ ((CKDIV) == FDCAN_CLOCK_DIV28) || \ ((CKDIV) == FDCAN_CLOCK_DIV30)) #define IS_FDCAN_NOMINAL_PRESCALER(PRESCALER) (((PRESCALER) >= 1U) && ((PRESCALER) <= 512U)) #define IS_FDCAN_NOMINAL_SJW(SJW) (((SJW) >= 1U) && ((SJW) <= 128U)) #define IS_FDCAN_NOMINAL_TSEG1(TSEG1) (((TSEG1) >= 1U) && ((TSEG1) <= 256U)) #define IS_FDCAN_NOMINAL_TSEG2(TSEG2) (((TSEG2) >= 1U) && ((TSEG2) <= 128U)) #define IS_FDCAN_DATA_PRESCALER(PRESCALER) (((PRESCALER) >= 1U) && ((PRESCALER) <= 32U)) #define IS_FDCAN_DATA_SJW(SJW) (((SJW) >= 1U) && ((SJW) <= 16U)) #define IS_FDCAN_DATA_TSEG1(TSEG1) (((TSEG1) >= 1U) && ((TSEG1) <= 32U)) #define IS_FDCAN_DATA_TSEG2(TSEG2) (((TSEG2) >= 1U) && ((TSEG2) <= 16U)) #define IS_FDCAN_MAX_VALUE(VALUE, _MAX_) ((VALUE) <= (_MAX_)) #define IS_FDCAN_MIN_VALUE(VALUE, _MIN_) ((VALUE) >= (_MIN_)) #define IS_FDCAN_TX_FIFO_QUEUE_MODE(MODE) (((MODE) == FDCAN_TX_FIFO_OPERATION ) || \ ((MODE) == FDCAN_TX_QUEUE_OPERATION)) #define IS_FDCAN_ID_TYPE(ID_TYPE) (((ID_TYPE) == FDCAN_STANDARD_ID) || \ ((ID_TYPE) == FDCAN_EXTENDED_ID)) #define IS_FDCAN_FILTER_CFG(CONFIG) (((CONFIG) == FDCAN_FILTER_DISABLE ) || \ ((CONFIG) == FDCAN_FILTER_TO_RXFIFO0 ) || \ ((CONFIG) == FDCAN_FILTER_TO_RXFIFO1 ) || \ ((CONFIG) == FDCAN_FILTER_REJECT ) || \ ((CONFIG) == FDCAN_FILTER_HP ) || \ ((CONFIG) == FDCAN_FILTER_TO_RXFIFO0_HP) || \ ((CONFIG) == FDCAN_FILTER_TO_RXFIFO1_HP)) #define IS_FDCAN_TX_LOCATION(LOCATION) (((LOCATION) == FDCAN_TX_BUFFER0 ) || ((LOCATION) == FDCAN_TX_BUFFER1 ) || \ ((LOCATION) == FDCAN_TX_BUFFER2 )) #define IS_FDCAN_TX_LOCATION_LIST(LOCATION) (((LOCATION) >= FDCAN_TX_BUFFER0) && \ ((LOCATION) <= (FDCAN_TX_BUFFER0 | FDCAN_TX_BUFFER1 | FDCAN_TX_BUFFER2))) #define IS_FDCAN_RX_FIFO(FIFO) (((FIFO) == FDCAN_RX_FIFO0) || \ ((FIFO) == FDCAN_RX_FIFO1)) #define IS_FDCAN_RX_FIFO_MODE(MODE) (((MODE) == FDCAN_RX_FIFO_BLOCKING ) || \ ((MODE) == FDCAN_RX_FIFO_OVERWRITE)) #define IS_FDCAN_STD_FILTER_TYPE(TYPE) (((TYPE) == FDCAN_FILTER_RANGE) || \ ((TYPE) == FDCAN_FILTER_DUAL ) || \ ((TYPE) == FDCAN_FILTER_MASK )) #define IS_FDCAN_EXT_FILTER_TYPE(TYPE) (((TYPE) == FDCAN_FILTER_RANGE ) || \ ((TYPE) == FDCAN_FILTER_DUAL ) || \ ((TYPE) == FDCAN_FILTER_MASK ) || \ ((TYPE) == FDCAN_FILTER_RANGE_NO_EIDM)) #define IS_FDCAN_FRAME_TYPE(TYPE) (((TYPE) == FDCAN_DATA_FRAME ) || \ ((TYPE) == FDCAN_REMOTE_FRAME)) #define IS_FDCAN_DLC(DLC) (((DLC) == FDCAN_DLC_BYTES_0 ) || \ ((DLC) == FDCAN_DLC_BYTES_1 ) || \ ((DLC) == FDCAN_DLC_BYTES_2 ) || \ ((DLC) == FDCAN_DLC_BYTES_3 ) || \ ((DLC) == FDCAN_DLC_BYTES_4 ) || \ ((DLC) == FDCAN_DLC_BYTES_5 ) || \ ((DLC) == FDCAN_DLC_BYTES_6 ) || \ ((DLC) == FDCAN_DLC_BYTES_7 ) || \ ((DLC) == FDCAN_DLC_BYTES_8 ) || \ ((DLC) == FDCAN_DLC_BYTES_12) || \ ((DLC) == FDCAN_DLC_BYTES_16) || \ ((DLC) == FDCAN_DLC_BYTES_20) || \ ((DLC) == FDCAN_DLC_BYTES_24) || \ ((DLC) == FDCAN_DLC_BYTES_32) || \ ((DLC) == FDCAN_DLC_BYTES_48) || \ ((DLC) == FDCAN_DLC_BYTES_64)) #define IS_FDCAN_ESI(ESI) (((ESI) == FDCAN_ESI_ACTIVE ) || \ ((ESI) == FDCAN_ESI_PASSIVE)) #define IS_FDCAN_BRS(BRS) (((BRS) == FDCAN_BRS_OFF) || \ ((BRS) == FDCAN_BRS_ON )) #define IS_FDCAN_FDF(FDF) (((FDF) == FDCAN_CLASSIC_CAN) || \ ((FDF) == FDCAN_FD_CAN )) #define IS_FDCAN_EFC(EFC) (((EFC) == FDCAN_NO_TX_EVENTS ) || \ ((EFC) == FDCAN_STORE_TX_EVENTS)) #define IS_FDCAN_IT(IT) (((IT) & ~(FDCAN_IR_MASK)) == 0U) #define IS_FDCAN_IT_GROUP(IT_GROUP) (((IT_GROUP) & ~(FDCAN_ILS_MASK)) == 0U) #define IS_FDCAN_NON_MATCHING(DESTINATION) (((DESTINATION) == FDCAN_ACCEPT_IN_RX_FIFO0) || \ ((DESTINATION) == FDCAN_ACCEPT_IN_RX_FIFO1) || \ ((DESTINATION) == FDCAN_REJECT )) #define IS_FDCAN_REJECT_REMOTE(DESTINATION) (((DESTINATION) == FDCAN_FILTER_REMOTE) || \ ((DESTINATION) == FDCAN_REJECT_REMOTE)) #define IS_FDCAN_IT_LINE(IT_LINE) (((IT_LINE) == FDCAN_INTERRUPT_LINE0) || \ ((IT_LINE) == FDCAN_INTERRUPT_LINE1)) #define IS_FDCAN_TIMESTAMP(OPERATION) (((OPERATION) == FDCAN_TIMESTAMP_INTERNAL) || \ ((OPERATION) == FDCAN_TIMESTAMP_EXTERNAL)) #define IS_FDCAN_TIMESTAMP_PRESCALER(PRESCALER) (((PRESCALER) == FDCAN_TIMESTAMP_PRESC_1 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_2 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_3 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_4 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_5 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_6 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_7 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_8 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_9 ) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_10) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_11) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_12) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_13) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_14) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_15) || \ ((PRESCALER) == FDCAN_TIMESTAMP_PRESC_16)) #define IS_FDCAN_TIMEOUT(OPERATION) (((OPERATION) == FDCAN_TIMEOUT_CONTINUOUS ) || \ ((OPERATION) == FDCAN_TIMEOUT_TX_EVENT_FIFO) || \ ((OPERATION) == FDCAN_TIMEOUT_RX_FIFO0 ) || \ ((OPERATION) == FDCAN_TIMEOUT_RX_FIFO1 )) /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #endif /* FDCAN1 */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_FDCAN_H */
78,679
C
54.020979
171
0.545838
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_nor.h
/** ****************************************************************************** * @file stm32g4xx_hal_nor.h * @author MCD Application Team * @brief Header file of NOR HAL 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_NOR_H #define STM32G4xx_HAL_NOR_H #ifdef __cplusplus extern "C" { #endif #if defined(FMC_BANK1) /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_ll_fmc.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup NOR * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup NOR_Exported_Types NOR Exported Types * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_NOR_STATE_RESET = 0x00U, /*!< NOR not yet initialized or disabled */ HAL_NOR_STATE_READY = 0x01U, /*!< NOR initialized and ready for use */ HAL_NOR_STATE_BUSY = 0x02U, /*!< NOR internal processing is ongoing */ HAL_NOR_STATE_ERROR = 0x03U, /*!< NOR error state */ HAL_NOR_STATE_PROTECTED = 0x04U /*!< NOR NORSRAM device write protected */ } HAL_NOR_StateTypeDef; /** * @brief FMC NOR Status typedef */ typedef enum { HAL_NOR_STATUS_SUCCESS = 0U, HAL_NOR_STATUS_ONGOING, HAL_NOR_STATUS_ERROR, HAL_NOR_STATUS_TIMEOUT } HAL_NOR_StatusTypeDef; /** * @brief FMC NOR ID typedef */ typedef struct { uint16_t Manufacturer_Code; /*!< Defines the device's manufacturer code used to identify the memory */ uint16_t Device_Code1; uint16_t Device_Code2; uint16_t Device_Code3; /*!< Defines the device's codes used to identify the memory. These codes can be accessed by performing read operations with specific control signals and addresses set.They can also be accessed by issuing an Auto Select command */ } NOR_IDTypeDef; /** * @brief FMC NOR CFI typedef */ typedef struct { /*!< Defines the information stored in the memory's Common flash interface which contains a description of various electrical and timing parameters, density information and functions supported by the memory */ uint16_t CFI_1; uint16_t CFI_2; uint16_t CFI_3; uint16_t CFI_4; } NOR_CFITypeDef; /** * @brief NOR handle Structure definition */ #if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) typedef struct __NOR_HandleTypeDef #else typedef struct #endif /* USE_HAL_NOR_REGISTER_CALLBACKS */ { FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ FMC_NORSRAM_InitTypeDef Init; /*!< NOR device control configuration parameters */ HAL_LockTypeDef Lock; /*!< NOR locking object */ __IO HAL_NOR_StateTypeDef State; /*!< NOR device access state */ uint32_t CommandSet; /*!< NOR algorithm command set and control */ #if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) void (* MspInitCallback)(struct __NOR_HandleTypeDef *hnor); /*!< NOR Msp Init callback */ void (* MspDeInitCallback)(struct __NOR_HandleTypeDef *hnor); /*!< NOR Msp DeInit callback */ #endif /* USE_HAL_NOR_REGISTER_CALLBACKS */ } NOR_HandleTypeDef; #if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) /** * @brief HAL NOR Callback ID enumeration definition */ typedef enum { HAL_NOR_MSP_INIT_CB_ID = 0x00U, /*!< NOR MspInit Callback ID */ HAL_NOR_MSP_DEINIT_CB_ID = 0x01U /*!< NOR MspDeInit Callback ID */ } HAL_NOR_CallbackIDTypeDef; /** * @brief HAL NOR Callback pointer definition */ typedef void (*pNOR_CallbackTypeDef)(NOR_HandleTypeDef *hnor); #endif /* USE_HAL_NOR_REGISTER_CALLBACKS */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup NOR_Exported_Macros NOR Exported Macros * @{ */ /** @brief Reset NOR handle state * @param __HANDLE__ specifies the NOR handle. * @retval None */ #if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) #define __HAL_NOR_RESET_HANDLE_STATE(__HANDLE__) do { \ (__HANDLE__)->State = HAL_NOR_STATE_RESET; \ (__HANDLE__)->MspInitCallback = NULL; \ (__HANDLE__)->MspDeInitCallback = NULL; \ } while(0) #else #define __HAL_NOR_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_NOR_STATE_RESET) #endif /* USE_HAL_NOR_REGISTER_CALLBACKS */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NOR_Exported_Functions NOR Exported Functions * @{ */ /** @addtogroup NOR_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group2 Input and Output functions * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID); HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI); #if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) /* NOR callback registering/unregistering */ HAL_StatusTypeDef HAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId, pNOR_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId); #endif /* USE_HAL_NOR_REGISTER_CALLBACKS */ /** * @} */ /** @addtogroup NOR_Exported_Functions_Group3 NOR Control functions * @{ */ /* NOR Control functions *****************************************************/ HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group4 NOR State functions * @{ */ /* NOR State functions ********************************************************/ HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor); HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup NOR_Private_Constants NOR Private Constants * @{ */ /* NOR device IDs addresses */ #define MC_ADDRESS ((uint16_t)0x0000) #define DEVICE_CODE1_ADDR ((uint16_t)0x0001) #define DEVICE_CODE2_ADDR ((uint16_t)0x000E) #define DEVICE_CODE3_ADDR ((uint16_t)0x000F) /* NOR CFI IDs addresses */ #define CFI1_ADDRESS ((uint16_t)0x0061) #define CFI2_ADDRESS ((uint16_t)0x0062) #define CFI3_ADDRESS ((uint16_t)0x0063) #define CFI4_ADDRESS ((uint16_t)0x0064) /* NOR operation wait timeout */ #define NOR_TMEOUT ((uint16_t)0xFFFF) /* NOR memory data width */ #define NOR_MEMORY_8B ((uint8_t)0x00) #define NOR_MEMORY_16B ((uint8_t)0x01) /* NOR memory device read/write start address */ #define NOR_MEMORY_ADRESS1 (0x60000000U) #define NOR_MEMORY_ADRESS2 (0x64000000U) #define NOR_MEMORY_ADRESS3 (0x68000000U) #define NOR_MEMORY_ADRESS4 (0x6C000000U) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup NOR_Private_Macros NOR Private Macros * @{ */ /** * @brief NOR memory address shifting. * @param __NOR_ADDRESS NOR base address * @param __NOR_MEMORY_WIDTH_ NOR memory width * @param __ADDRESS__ NOR memory address * @retval NOR shifted address value */ #define NOR_ADDR_SHIFT(__NOR_ADDRESS, __NOR_MEMORY_WIDTH_, __ADDRESS__) \ ((uint32_t)(((__NOR_MEMORY_WIDTH_) == NOR_MEMORY_16B)? \ ((uint32_t)((__NOR_ADDRESS) + (2U * (__ADDRESS__)))): \ ((uint32_t)((__NOR_ADDRESS) + (__ADDRESS__))))) /** * @brief NOR memory write data to specified address. * @param __ADDRESS__ NOR memory address * @param __DATA__ Data to write * @retval None */ #define NOR_WRITE(__ADDRESS__, __DATA__) do{ \ (*(__IO uint16_t *)((uint32_t)(__ADDRESS__)) = (__DATA__)); \ __DSB(); \ } while(0) /** * @} */ /** * @} */ /** * @} */ #endif /* FMC_BANK1 */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_NOR_H */
11,268
C
33.461774
118
0.54109
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_uart.h
/** ****************************************************************************** * @file stm32g4xx_hal_uart.h * @author MCD Application Team * @brief Header file of UART HAL 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_UART_H #define STM32G4xx_HAL_UART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal_def.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup UART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ */ /** * @brief UART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. The baud rate register is computed using the following formula: LPUART: ======= Baud Rate Register = ((256 * lpuart_ker_ckpres) / ((huart->Init.BaudRate))) where lpuart_ker_ck_pres is the UART input clock divided by a prescaler UART: ===== - If oversampling is 16 or in LIN mode, Baud Rate Register = ((uart_ker_ckpres) / ((huart->Init.BaudRate))) - If oversampling is 8, Baud Rate Register[15:4] = ((2 * uart_ker_ckpres) / ((huart->Init.BaudRate)))[15:4] Baud Rate Register[3] = 0 Baud Rate Register[2:0] = (((2 * uart_ker_ckpres) / ((huart->Init.BaudRate)))[3:0]) >> 1 where uart_ker_ck_pres is the UART input clock divided by a prescaler */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref UARTEx_Word_Length. */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref UART_Stop_Bits. */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref UART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode. */ uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control. */ uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to f_PCLK/8). This parameter can be a value of @ref UART_Over_Sampling. */ uint32_t OneBitSampling; /*!< Specifies whether a single sample or three samples' majority vote is selected. Selecting the single sample method increases the receiver tolerance to clock deviations. This parameter can be a value of @ref UART_OneBit_Sampling. */ uint32_t ClockPrescaler; /*!< Specifies the prescaler value used to divide the UART clock source. This parameter can be a value of @ref UART_ClockPrescaler. */ } UART_InitTypeDef; /** * @brief UART Advanced Features initialization structure definition */ typedef struct { uint32_t AdvFeatureInit; /*!< Specifies which advanced UART features is initialized. Several Advanced Features may be initialized at the same time . This parameter can be a value of @ref UART_Advanced_Features_Initialization_Type. */ uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. This parameter can be a value of @ref UART_Tx_Inv. */ uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. This parameter can be a value of @ref UART_Rx_Inv. */ uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic vs negative/inverted logic). This parameter can be a value of @ref UART_Data_Inv. */ uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. This parameter can be a value of @ref UART_Rx_Tx_Swap. */ uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. This parameter can be a value of @ref UART_Overrun_Disable. */ uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. This parameter can be a value of @ref UART_DMA_Disable_on_Rx_Error. */ uint32_t AutoBaudRateEnable; /*!< Specifies whether auto Baud rate detection is enabled. This parameter can be a value of @ref UART_AutoBaudRate_Enable. */ uint32_t AutoBaudRateMode; /*!< If auto Baud rate detection is enabled, specifies how the rate detection is carried out. This parameter can be a value of @ref UART_AutoBaud_Rate_Mode. */ uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. This parameter can be a value of @ref UART_MSB_First. */ } UART_AdvFeatureInitTypeDef; /** * @brief HAL UART State definition * @note HAL UART State value is a combination of 2 different substates: * gState and RxState (see @ref UART_State_Definition). * - gState contains UART state information related to global Handle management * and also information related to Tx operations. * gState value coding follow below described bitmap : * b7-b6 Error information * 00 : No Error * 01 : (Not Used) * 10 : Timeout * 11 : Error * b5 Peripheral initialization status * 0 : Reset (Peripheral not initialized) * 1 : Init done (Peripheral initialized. HAL UART Init function already called) * b4-b3 (not used) * xx : Should be set to 00 * b2 Intrinsic process state * 0 : Ready * 1 : Busy (Peripheral busy with some configuration or internal operations) * b1 (not used) * x : Should be set to 0 * b0 Tx state * 0 : Ready (no Tx operation ongoing) * 1 : Busy (Tx operation ongoing) * - RxState contains information related to Rx operations. * RxState value coding follow below described bitmap : * b7-b6 (not used) * xx : Should be set to 00 * b5 Peripheral initialization status * 0 : Reset (Peripheral not initialized) * 1 : Init done (Peripheral initialized) * b4-b2 (not used) * xxx : Should be set to 000 * b1 Rx state * 0 : Ready (no Rx operation ongoing) * 1 : Busy (Rx operation ongoing) * b0 (not used) * x : Should be set to 0. */ typedef uint32_t HAL_UART_StateTypeDef; /** * @brief UART clock sources definition */ typedef enum { UART_CLOCKSOURCE_PCLK1 = 0x00U, /*!< PCLK1 clock source */ UART_CLOCKSOURCE_PCLK2 = 0x01U, /*!< PCLK2 clock source */ UART_CLOCKSOURCE_HSI = 0x02U, /*!< HSI clock source */ UART_CLOCKSOURCE_SYSCLK = 0x04U, /*!< SYSCLK clock source */ UART_CLOCKSOURCE_LSE = 0x08U, /*!< LSE clock source */ UART_CLOCKSOURCE_UNDEFINED = 0x10U /*!< Undefined clock source */ } UART_ClockSourceTypeDef; /** * @brief HAL UART Reception type definition * @note HAL UART Reception type value aims to identify which type of Reception is ongoing. * It is expected to admit following values : * HAL_UART_RECEPTION_STANDARD = 0x00U, * HAL_UART_RECEPTION_TOIDLE = 0x01U, * HAL_UART_RECEPTION_TORTO = 0x02U, * HAL_UART_RECEPTION_TOCHARMATCH = 0x03U, */ typedef uint32_t HAL_UART_RxTypeTypeDef; /** * @brief UART handle Structure definition */ typedef struct __UART_HandleTypeDef { USART_TypeDef *Instance; /*!< UART registers base address */ UART_InitTypeDef Init; /*!< UART communication parameters */ UART_AdvFeatureInitTypeDef AdvancedInit; /*!< UART Advanced Features initialization parameters */ const uint8_t *pTxBuffPtr; /*!< Pointer to UART Tx transfer Buffer */ uint16_t TxXferSize; /*!< UART Tx Transfer size */ __IO uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /*!< UART Rx Transfer size */ __IO uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ uint16_t Mask; /*!< UART Rx RDR register mask */ uint32_t FifoMode; /*!< Specifies if the FIFO mode is being used. This parameter can be a value of @ref UARTEx_FIFO_mode. */ uint16_t NbRxDataToProcess; /*!< Number of data to process during RX ISR execution */ uint16_t NbTxDataToProcess; /*!< Number of data to process during TX ISR execution */ __IO HAL_UART_RxTypeTypeDef ReceptionType; /*!< Type of ongoing reception */ void (*RxISR)(struct __UART_HandleTypeDef *huart); /*!< Function pointer on Rx IRQ handler */ void (*TxISR)(struct __UART_HandleTypeDef *huart); /*!< Function pointer on Tx IRQ handler */ DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< UART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_UART_StateTypeDef gState; /*!< UART state information related to global Handle management and also related to Tx operations. This parameter can be a value of @ref HAL_UART_StateTypeDef */ __IO HAL_UART_StateTypeDef RxState; /*!< UART state information related to Rx operations. This parameter can be a value of @ref HAL_UART_StateTypeDef */ __IO uint32_t ErrorCode; /*!< UART Error code */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) void (* TxHalfCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Tx Half Complete Callback */ void (* TxCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Tx Complete Callback */ void (* RxHalfCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Rx Half Complete Callback */ void (* RxCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Rx Complete Callback */ void (* ErrorCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Error Callback */ void (* AbortCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Complete Callback */ void (* AbortTransmitCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Transmit Complete Callback */ void (* AbortReceiveCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Receive Complete Callback */ void (* WakeupCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Wakeup Callback */ void (* RxFifoFullCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Rx Fifo Full Callback */ void (* TxFifoEmptyCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Tx Fifo Empty Callback */ void (* RxEventCallback)(struct __UART_HandleTypeDef *huart, uint16_t Pos); /*!< UART Reception Event Callback */ void (* MspInitCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Msp Init callback */ void (* MspDeInitCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Msp DeInit callback */ #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } UART_HandleTypeDef; #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /** * @brief HAL UART Callback ID enumeration definition */ typedef enum { HAL_UART_TX_HALFCOMPLETE_CB_ID = 0x00U, /*!< UART Tx Half Complete Callback ID */ HAL_UART_TX_COMPLETE_CB_ID = 0x01U, /*!< UART Tx Complete Callback ID */ HAL_UART_RX_HALFCOMPLETE_CB_ID = 0x02U, /*!< UART Rx Half Complete Callback ID */ HAL_UART_RX_COMPLETE_CB_ID = 0x03U, /*!< UART Rx Complete Callback ID */ HAL_UART_ERROR_CB_ID = 0x04U, /*!< UART Error Callback ID */ HAL_UART_ABORT_COMPLETE_CB_ID = 0x05U, /*!< UART Abort Complete Callback ID */ HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID = 0x06U, /*!< UART Abort Transmit Complete Callback ID */ HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID = 0x07U, /*!< UART Abort Receive Complete Callback ID */ HAL_UART_WAKEUP_CB_ID = 0x08U, /*!< UART Wakeup Callback ID */ HAL_UART_RX_FIFO_FULL_CB_ID = 0x09U, /*!< UART Rx Fifo Full Callback ID */ HAL_UART_TX_FIFO_EMPTY_CB_ID = 0x0AU, /*!< UART Tx Fifo Empty Callback ID */ HAL_UART_MSPINIT_CB_ID = 0x0BU, /*!< UART MspInit callback ID */ HAL_UART_MSPDEINIT_CB_ID = 0x0CU /*!< UART MspDeInit callback ID */ } HAL_UART_CallbackIDTypeDef; /** * @brief HAL UART Callback pointer definition */ typedef void (*pUART_CallbackTypeDef)(UART_HandleTypeDef *huart); /*!< pointer to an UART callback function */ typedef void (*pUART_RxEventCallbackTypeDef) (struct __UART_HandleTypeDef *huart, uint16_t Pos); /*!< pointer to a UART Rx Event specific callback function */ #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UART_Exported_Constants UART Exported Constants * @{ */ /** @defgroup UART_State_Definition UART State Code Definition * @{ */ #define HAL_UART_STATE_RESET 0x00000000U /*!< Peripheral is not initialized Value is allowed for gState and RxState */ #define HAL_UART_STATE_READY 0x00000020U /*!< Peripheral Initialized and ready for use Value is allowed for gState and RxState */ #define HAL_UART_STATE_BUSY 0x00000024U /*!< an internal process is ongoing Value is allowed for gState only */ #define HAL_UART_STATE_BUSY_TX 0x00000021U /*!< Data Transmission process is ongoing Value is allowed for gState only */ #define HAL_UART_STATE_BUSY_RX 0x00000022U /*!< Data Reception process is ongoing Value is allowed for RxState only */ #define HAL_UART_STATE_BUSY_TX_RX 0x00000023U /*!< Data Transmission and Reception process is ongoing Not to be used for neither gState nor RxState.Value is result of combination (Or) between gState and RxState values */ #define HAL_UART_STATE_TIMEOUT 0x000000A0U /*!< Timeout state Value is allowed for gState only */ #define HAL_UART_STATE_ERROR 0x000000E0U /*!< Error Value is allowed for gState only */ /** * @} */ /** @defgroup UART_Error_Definition UART Error Definition * @{ */ #define HAL_UART_ERROR_NONE (0x00000000U) /*!< No error */ #define HAL_UART_ERROR_PE (0x00000001U) /*!< Parity error */ #define HAL_UART_ERROR_NE (0x00000002U) /*!< Noise error */ #define HAL_UART_ERROR_FE (0x00000004U) /*!< Frame error */ #define HAL_UART_ERROR_ORE (0x00000008U) /*!< Overrun error */ #define HAL_UART_ERROR_DMA (0x00000010U) /*!< DMA transfer error */ #define HAL_UART_ERROR_RTO (0x00000020U) /*!< Receiver Timeout error */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) #define HAL_UART_ERROR_INVALID_CALLBACK (0x00000040U) /*!< Invalid Callback error */ #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ #define UART_STOPBITS_0_5 USART_CR2_STOP_0 /*!< UART frame with 0.5 stop bit */ #define UART_STOPBITS_1 0x00000000U /*!< UART frame with 1 stop bit */ #define UART_STOPBITS_1_5 (USART_CR2_STOP_0 | USART_CR2_STOP_1) /*!< UART frame with 1.5 stop bits */ #define UART_STOPBITS_2 USART_CR2_STOP_1 /*!< UART frame with 2 stop bits */ /** * @} */ /** @defgroup UART_Parity UART Parity * @{ */ #define UART_PARITY_NONE 0x00000000U /*!< No parity */ #define UART_PARITY_EVEN USART_CR1_PCE /*!< Even parity */ #define UART_PARITY_ODD (USART_CR1_PCE | USART_CR1_PS) /*!< Odd parity */ /** * @} */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ */ #define UART_HWCONTROL_NONE 0x00000000U /*!< No hardware control */ #define UART_HWCONTROL_RTS USART_CR3_RTSE /*!< Request To Send */ #define UART_HWCONTROL_CTS USART_CR3_CTSE /*!< Clear To Send */ #define UART_HWCONTROL_RTS_CTS (USART_CR3_RTSE | USART_CR3_CTSE) /*!< Request and Clear To Send */ /** * @} */ /** @defgroup UART_Mode UART Transfer Mode * @{ */ #define UART_MODE_RX USART_CR1_RE /*!< RX mode */ #define UART_MODE_TX USART_CR1_TE /*!< TX mode */ #define UART_MODE_TX_RX (USART_CR1_TE |USART_CR1_RE) /*!< RX and TX mode */ /** * @} */ /** @defgroup UART_State UART State * @{ */ #define UART_STATE_DISABLE 0x00000000U /*!< UART disabled */ #define UART_STATE_ENABLE USART_CR1_UE /*!< UART enabled */ /** * @} */ /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ #define UART_OVERSAMPLING_16 0x00000000U /*!< Oversampling by 16 */ #define UART_OVERSAMPLING_8 USART_CR1_OVER8 /*!< Oversampling by 8 */ /** * @} */ /** @defgroup UART_OneBit_Sampling UART One Bit Sampling Method * @{ */ #define UART_ONE_BIT_SAMPLE_DISABLE 0x00000000U /*!< One-bit sampling disable */ #define UART_ONE_BIT_SAMPLE_ENABLE USART_CR3_ONEBIT /*!< One-bit sampling enable */ /** * @} */ /** @defgroup UART_ClockPrescaler UART Clock Prescaler * @{ */ #define UART_PRESCALER_DIV1 0x00000000U /*!< fclk_pres = fclk */ #define UART_PRESCALER_DIV2 0x00000001U /*!< fclk_pres = fclk/2 */ #define UART_PRESCALER_DIV4 0x00000002U /*!< fclk_pres = fclk/4 */ #define UART_PRESCALER_DIV6 0x00000003U /*!< fclk_pres = fclk/6 */ #define UART_PRESCALER_DIV8 0x00000004U /*!< fclk_pres = fclk/8 */ #define UART_PRESCALER_DIV10 0x00000005U /*!< fclk_pres = fclk/10 */ #define UART_PRESCALER_DIV12 0x00000006U /*!< fclk_pres = fclk/12 */ #define UART_PRESCALER_DIV16 0x00000007U /*!< fclk_pres = fclk/16 */ #define UART_PRESCALER_DIV32 0x00000008U /*!< fclk_pres = fclk/32 */ #define UART_PRESCALER_DIV64 0x00000009U /*!< fclk_pres = fclk/64 */ #define UART_PRESCALER_DIV128 0x0000000AU /*!< fclk_pres = fclk/128 */ #define UART_PRESCALER_DIV256 0x0000000BU /*!< fclk_pres = fclk/256 */ /** * @} */ /** @defgroup UART_AutoBaud_Rate_Mode UART Advanced Feature AutoBaud Rate Mode * @{ */ #define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT 0x00000000U /*!< Auto Baud rate detection on start bit */ #define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE USART_CR2_ABRMODE_0 /*!< Auto Baud rate detection on falling edge */ #define UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME USART_CR2_ABRMODE_1 /*!< Auto Baud rate detection on 0x7F frame detection */ #define UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME USART_CR2_ABRMODE /*!< Auto Baud rate detection on 0x55 frame detection */ /** * @} */ /** @defgroup UART_Receiver_Timeout UART Receiver Timeout * @{ */ #define UART_RECEIVER_TIMEOUT_DISABLE 0x00000000U /*!< UART Receiver Timeout disable */ #define UART_RECEIVER_TIMEOUT_ENABLE USART_CR2_RTOEN /*!< UART Receiver Timeout enable */ /** * @} */ /** @defgroup UART_LIN UART Local Interconnection Network mode * @{ */ #define UART_LIN_DISABLE 0x00000000U /*!< Local Interconnect Network disable */ #define UART_LIN_ENABLE USART_CR2_LINEN /*!< Local Interconnect Network enable */ /** * @} */ /** @defgroup UART_LIN_Break_Detection UART LIN Break Detection * @{ */ #define UART_LINBREAKDETECTLENGTH_10B 0x00000000U /*!< LIN 10-bit break detection length */ #define UART_LINBREAKDETECTLENGTH_11B USART_CR2_LBDL /*!< LIN 11-bit break detection length */ /** * @} */ /** @defgroup UART_DMA_Tx UART DMA Tx * @{ */ #define UART_DMA_TX_DISABLE 0x00000000U /*!< UART DMA TX disabled */ #define UART_DMA_TX_ENABLE USART_CR3_DMAT /*!< UART DMA TX enabled */ /** * @} */ /** @defgroup UART_DMA_Rx UART DMA Rx * @{ */ #define UART_DMA_RX_DISABLE 0x00000000U /*!< UART DMA RX disabled */ #define UART_DMA_RX_ENABLE USART_CR3_DMAR /*!< UART DMA RX enabled */ /** * @} */ /** @defgroup UART_Half_Duplex_Selection UART Half Duplex Selection * @{ */ #define UART_HALF_DUPLEX_DISABLE 0x00000000U /*!< UART half-duplex disabled */ #define UART_HALF_DUPLEX_ENABLE USART_CR3_HDSEL /*!< UART half-duplex enabled */ /** * @} */ /** @defgroup UART_WakeUp_Methods UART WakeUp Methods * @{ */ #define UART_WAKEUPMETHOD_IDLELINE 0x00000000U /*!< UART wake-up on idle line */ #define UART_WAKEUPMETHOD_ADDRESSMARK USART_CR1_WAKE /*!< UART wake-up on address mark */ /** * @} */ /** @defgroup UART_Request_Parameters UART Request Parameters * @{ */ #define UART_AUTOBAUD_REQUEST USART_RQR_ABRRQ /*!< Auto-Baud Rate Request */ #define UART_SENDBREAK_REQUEST USART_RQR_SBKRQ /*!< Send Break Request */ #define UART_MUTE_MODE_REQUEST USART_RQR_MMRQ /*!< Mute Mode Request */ #define UART_RXDATA_FLUSH_REQUEST USART_RQR_RXFRQ /*!< Receive Data flush Request */ #define UART_TXDATA_FLUSH_REQUEST USART_RQR_TXFRQ /*!< Transmit data flush Request */ /** * @} */ /** @defgroup UART_Advanced_Features_Initialization_Type UART Advanced Feature Initialization Type * @{ */ #define UART_ADVFEATURE_NO_INIT 0x00000000U /*!< No advanced feature initialization */ #define UART_ADVFEATURE_TXINVERT_INIT 0x00000001U /*!< TX pin active level inversion */ #define UART_ADVFEATURE_RXINVERT_INIT 0x00000002U /*!< RX pin active level inversion */ #define UART_ADVFEATURE_DATAINVERT_INIT 0x00000004U /*!< Binary data inversion */ #define UART_ADVFEATURE_SWAP_INIT 0x00000008U /*!< TX/RX pins swap */ #define UART_ADVFEATURE_RXOVERRUNDISABLE_INIT 0x00000010U /*!< RX overrun disable */ #define UART_ADVFEATURE_DMADISABLEONERROR_INIT 0x00000020U /*!< DMA disable on Reception Error */ #define UART_ADVFEATURE_AUTOBAUDRATE_INIT 0x00000040U /*!< Auto Baud rate detection initialization */ #define UART_ADVFEATURE_MSBFIRST_INIT 0x00000080U /*!< Most significant bit sent/received first */ /** * @} */ /** @defgroup UART_Tx_Inv UART Advanced Feature TX Pin Active Level Inversion * @{ */ #define UART_ADVFEATURE_TXINV_DISABLE 0x00000000U /*!< TX pin active level inversion disable */ #define UART_ADVFEATURE_TXINV_ENABLE USART_CR2_TXINV /*!< TX pin active level inversion enable */ /** * @} */ /** @defgroup UART_Rx_Inv UART Advanced Feature RX Pin Active Level Inversion * @{ */ #define UART_ADVFEATURE_RXINV_DISABLE 0x00000000U /*!< RX pin active level inversion disable */ #define UART_ADVFEATURE_RXINV_ENABLE USART_CR2_RXINV /*!< RX pin active level inversion enable */ /** * @} */ /** @defgroup UART_Data_Inv UART Advanced Feature Binary Data Inversion * @{ */ #define UART_ADVFEATURE_DATAINV_DISABLE 0x00000000U /*!< Binary data inversion disable */ #define UART_ADVFEATURE_DATAINV_ENABLE USART_CR2_DATAINV /*!< Binary data inversion enable */ /** * @} */ /** @defgroup UART_Rx_Tx_Swap UART Advanced Feature RX TX Pins Swap * @{ */ #define UART_ADVFEATURE_SWAP_DISABLE 0x00000000U /*!< TX/RX pins swap disable */ #define UART_ADVFEATURE_SWAP_ENABLE USART_CR2_SWAP /*!< TX/RX pins swap enable */ /** * @} */ /** @defgroup UART_Overrun_Disable UART Advanced Feature Overrun Disable * @{ */ #define UART_ADVFEATURE_OVERRUN_ENABLE 0x00000000U /*!< RX overrun enable */ #define UART_ADVFEATURE_OVERRUN_DISABLE USART_CR3_OVRDIS /*!< RX overrun disable */ /** * @} */ /** @defgroup UART_AutoBaudRate_Enable UART Advanced Feature Auto BaudRate Enable * @{ */ #define UART_ADVFEATURE_AUTOBAUDRATE_DISABLE 0x00000000U /*!< RX Auto Baud rate detection enable */ #define UART_ADVFEATURE_AUTOBAUDRATE_ENABLE USART_CR2_ABREN /*!< RX Auto Baud rate detection disable */ /** * @} */ /** @defgroup UART_DMA_Disable_on_Rx_Error UART Advanced Feature DMA Disable On Rx Error * @{ */ #define UART_ADVFEATURE_DMA_ENABLEONRXERROR 0x00000000U /*!< DMA enable on Reception Error */ #define UART_ADVFEATURE_DMA_DISABLEONRXERROR USART_CR3_DDRE /*!< DMA disable on Reception Error */ /** * @} */ /** @defgroup UART_MSB_First UART Advanced Feature MSB First * @{ */ #define UART_ADVFEATURE_MSBFIRST_DISABLE 0x00000000U /*!< Most significant bit sent/received first disable */ #define UART_ADVFEATURE_MSBFIRST_ENABLE USART_CR2_MSBFIRST /*!< Most significant bit sent/received first enable */ /** * @} */ /** @defgroup UART_Stop_Mode_Enable UART Advanced Feature Stop Mode Enable * @{ */ #define UART_ADVFEATURE_STOPMODE_DISABLE 0x00000000U /*!< UART stop mode disable */ #define UART_ADVFEATURE_STOPMODE_ENABLE USART_CR1_UESM /*!< UART stop mode enable */ /** * @} */ /** @defgroup UART_Mute_Mode UART Advanced Feature Mute Mode Enable * @{ */ #define UART_ADVFEATURE_MUTEMODE_DISABLE 0x00000000U /*!< UART mute mode disable */ #define UART_ADVFEATURE_MUTEMODE_ENABLE USART_CR1_MME /*!< UART mute mode enable */ /** * @} */ /** @defgroup UART_CR2_ADDRESS_LSB_POS UART Address-matching LSB Position In CR2 Register * @{ */ #define UART_CR2_ADDRESS_LSB_POS 24U /*!< UART address-matching LSB position in CR2 register */ /** * @} */ /** @defgroup UART_WakeUp_from_Stop_Selection UART WakeUp From Stop Selection * @{ */ #define UART_WAKEUP_ON_ADDRESS 0x00000000U /*!< UART wake-up on address */ #define UART_WAKEUP_ON_STARTBIT USART_CR3_WUS_1 /*!< UART wake-up on start bit */ #define UART_WAKEUP_ON_READDATA_NONEMPTY USART_CR3_WUS /*!< UART wake-up on receive data register not empty or RXFIFO is not empty */ /** * @} */ /** @defgroup UART_DriverEnable_Polarity UART DriverEnable Polarity * @{ */ #define UART_DE_POLARITY_HIGH 0x00000000U /*!< Driver enable signal is active high */ #define UART_DE_POLARITY_LOW USART_CR3_DEP /*!< Driver enable signal is active low */ /** * @} */ /** @defgroup UART_CR1_DEAT_ADDRESS_LSB_POS UART Driver Enable Assertion Time LSB Position In CR1 Register * @{ */ #define UART_CR1_DEAT_ADDRESS_LSB_POS 21U /*!< UART Driver Enable assertion time LSB position in CR1 register */ /** * @} */ /** @defgroup UART_CR1_DEDT_ADDRESS_LSB_POS UART Driver Enable DeAssertion Time LSB Position In CR1 Register * @{ */ #define UART_CR1_DEDT_ADDRESS_LSB_POS 16U /*!< UART Driver Enable de-assertion time LSB position in CR1 register */ /** * @} */ /** @defgroup UART_Interruption_Mask UART Interruptions Flag Mask * @{ */ #define UART_IT_MASK 0x001FU /*!< UART interruptions flags mask */ /** * @} */ /** @defgroup UART_TimeOut_Value UART polling-based communications time-out value * @{ */ #define HAL_UART_TIMEOUT_VALUE 0x1FFFFFFU /*!< UART polling-based communications time-out value */ /** * @} */ /** @defgroup UART_Flags UART Status Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the ISR register * @{ */ #define UART_FLAG_TXFT USART_ISR_TXFT /*!< UART TXFIFO threshold flag */ #define UART_FLAG_RXFT USART_ISR_RXFT /*!< UART RXFIFO threshold flag */ #define UART_FLAG_RXFF USART_ISR_RXFF /*!< UART RXFIFO Full flag */ #define UART_FLAG_TXFE USART_ISR_TXFE /*!< UART TXFIFO Empty flag */ #define UART_FLAG_REACK USART_ISR_REACK /*!< UART receive enable acknowledge flag */ #define UART_FLAG_TEACK USART_ISR_TEACK /*!< UART transmit enable acknowledge flag */ #define UART_FLAG_WUF USART_ISR_WUF /*!< UART wake-up from stop mode flag */ #define UART_FLAG_RWU USART_ISR_RWU /*!< UART receiver wake-up from mute mode flag */ #define UART_FLAG_SBKF USART_ISR_SBKF /*!< UART send break flag */ #define UART_FLAG_CMF USART_ISR_CMF /*!< UART character match flag */ #define UART_FLAG_BUSY USART_ISR_BUSY /*!< UART busy flag */ #define UART_FLAG_ABRF USART_ISR_ABRF /*!< UART auto Baud rate flag */ #define UART_FLAG_ABRE USART_ISR_ABRE /*!< UART auto Baud rate error */ #define UART_FLAG_RTOF USART_ISR_RTOF /*!< UART receiver timeout flag */ #define UART_FLAG_CTS USART_ISR_CTS /*!< UART clear to send flag */ #define UART_FLAG_CTSIF USART_ISR_CTSIF /*!< UART clear to send interrupt flag */ #define UART_FLAG_LBDF USART_ISR_LBDF /*!< UART LIN break detection flag */ #define UART_FLAG_TXE USART_ISR_TXE_TXFNF /*!< UART transmit data register empty */ #define UART_FLAG_TXFNF USART_ISR_TXE_TXFNF /*!< UART TXFIFO not full */ #define UART_FLAG_TC USART_ISR_TC /*!< UART transmission complete */ #define UART_FLAG_RXNE USART_ISR_RXNE_RXFNE /*!< UART read data register not empty */ #define UART_FLAG_RXFNE USART_ISR_RXNE_RXFNE /*!< UART RXFIFO not empty */ #define UART_FLAG_IDLE USART_ISR_IDLE /*!< UART idle flag */ #define UART_FLAG_ORE USART_ISR_ORE /*!< UART overrun error */ #define UART_FLAG_NE USART_ISR_NE /*!< UART noise error */ #define UART_FLAG_FE USART_ISR_FE /*!< UART frame error */ #define UART_FLAG_PE USART_ISR_PE /*!< UART parity error */ /** * @} */ /** @defgroup UART_Interrupt_definition UART Interrupts Definition * Elements values convention: 000ZZZZZ0XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * - ZZZZZ : Flag position in the ISR register(5bits) * Elements values convention: 000000000XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * Elements values convention: 0000ZZZZ00000000b * - ZZZZ : Flag position in the ISR register(4bits) * @{ */ #define UART_IT_PE 0x0028U /*!< UART parity error interruption */ #define UART_IT_TXE 0x0727U /*!< UART transmit data register empty interruption */ #define UART_IT_TXFNF 0x0727U /*!< UART TX FIFO not full interruption */ #define UART_IT_TC 0x0626U /*!< UART transmission complete interruption */ #define UART_IT_RXNE 0x0525U /*!< UART read data register not empty interruption */ #define UART_IT_RXFNE 0x0525U /*!< UART RXFIFO not empty interruption */ #define UART_IT_IDLE 0x0424U /*!< UART idle interruption */ #define UART_IT_LBD 0x0846U /*!< UART LIN break detection interruption */ #define UART_IT_CTS 0x096AU /*!< UART CTS interruption */ #define UART_IT_CM 0x112EU /*!< UART character match interruption */ #define UART_IT_WUF 0x1476U /*!< UART wake-up from stop mode interruption */ #define UART_IT_RXFF 0x183FU /*!< UART RXFIFO full interruption */ #define UART_IT_TXFE 0x173EU /*!< UART TXFIFO empty interruption */ #define UART_IT_RXFT 0x1A7CU /*!< UART RXFIFO threshold reached interruption */ #define UART_IT_TXFT 0x1B77U /*!< UART TXFIFO threshold reached interruption */ #define UART_IT_RTO 0x0B3AU /*!< UART receiver timeout interruption */ #define UART_IT_ERR 0x0060U /*!< UART error interruption */ #define UART_IT_ORE 0x0300U /*!< UART overrun error interruption */ #define UART_IT_NE 0x0200U /*!< UART noise error interruption */ #define UART_IT_FE 0x0100U /*!< UART frame error interruption */ /** * @} */ /** @defgroup UART_IT_CLEAR_Flags UART Interruption Clear Flags * @{ */ #define UART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ #define UART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ #define UART_CLEAR_NEF USART_ICR_NECF /*!< Noise Error detected Clear Flag */ #define UART_CLEAR_OREF USART_ICR_ORECF /*!< Overrun Error Clear Flag */ #define UART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ #define UART_CLEAR_TXFECF USART_ICR_TXFECF /*!< TXFIFO empty clear flag */ #define UART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ #define UART_CLEAR_LBDF USART_ICR_LBDCF /*!< LIN Break Detection Clear Flag */ #define UART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ #define UART_CLEAR_CMF USART_ICR_CMCF /*!< Character Match Clear Flag */ #define UART_CLEAR_WUF USART_ICR_WUCF /*!< Wake Up from stop mode Clear Flag */ #define UART_CLEAR_RTOF USART_ICR_RTOCF /*!< UART receiver timeout clear flag */ /** * @} */ /** @defgroup UART_RECEPTION_TYPE_Values UART Reception type values * @{ */ #define HAL_UART_RECEPTION_STANDARD (0x00000000U) /*!< Standard reception */ #define HAL_UART_RECEPTION_TOIDLE (0x00000001U) /*!< Reception till completion or IDLE event */ #define HAL_UART_RECEPTION_TORTO (0x00000002U) /*!< Reception till completion or RTO event */ #define HAL_UART_RECEPTION_TOCHARMATCH (0x00000003U) /*!< Reception till completion or CM event */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ /** @brief Reset UART handle states. * @param __HANDLE__ UART handle. * @retval None */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) do{ \ (__HANDLE__)->gState = HAL_UART_STATE_RESET; \ (__HANDLE__)->RxState = HAL_UART_STATE_RESET; \ (__HANDLE__)->MspInitCallback = NULL; \ (__HANDLE__)->MspDeInitCallback = NULL; \ } while(0U) #else #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) do{ \ (__HANDLE__)->gState = HAL_UART_STATE_RESET; \ (__HANDLE__)->RxState = HAL_UART_STATE_RESET; \ } while(0U) #endif /*USE_HAL_UART_REGISTER_CALLBACKS */ /** @brief Flush the UART Data registers. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, UART_RXDATA_FLUSH_REQUEST); \ SET_BIT((__HANDLE__)->Instance->RQR, UART_TXDATA_FLUSH_REQUEST); \ } while(0U) /** @brief Clear the specified UART pending flag. * @param __HANDLE__ specifies the UART Handle. * @param __FLAG__ specifies the flag to check. * This parameter can be any combination of the following values: * @arg @ref UART_CLEAR_PEF Parity Error Clear Flag * @arg @ref UART_CLEAR_FEF Framing Error Clear Flag * @arg @ref UART_CLEAR_NEF Noise detected Clear Flag * @arg @ref UART_CLEAR_OREF Overrun Error Clear Flag * @arg @ref UART_CLEAR_IDLEF IDLE line detected Clear Flag * @arg @ref UART_CLEAR_TXFECF TXFIFO empty clear Flag * @arg @ref UART_CLEAR_TCF Transmission Complete Clear Flag * @arg @ref UART_CLEAR_RTOF Receiver Timeout clear flag * @arg @ref UART_CLEAR_LBDF LIN Break Detection Clear Flag * @arg @ref UART_CLEAR_CTSF CTS Interrupt Clear Flag * @arg @ref UART_CLEAR_CMF Character Match Clear Flag * @arg @ref UART_CLEAR_WUF Wake Up from stop mode Clear Flag * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Clear the UART PE pending flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_PEF) /** @brief Clear the UART FE pending flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_FEF) /** @brief Clear the UART NE pending flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_NEF) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_OREF) /** @brief Clear the UART IDLE pending flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_IDLEF) /** @brief Clear the UART TX FIFO empty clear flag. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_TXFECF(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_TXFECF) /** @brief Check whether the specified UART flag is set or not. * @param __HANDLE__ specifies the UART Handle. * @param __FLAG__ specifies the flag to check. * This parameter can be one of the following values: * @arg @ref UART_FLAG_TXFT TXFIFO threshold flag * @arg @ref UART_FLAG_RXFT RXFIFO threshold flag * @arg @ref UART_FLAG_RXFF RXFIFO Full flag * @arg @ref UART_FLAG_TXFE TXFIFO Empty flag * @arg @ref UART_FLAG_REACK Receive enable acknowledge flag * @arg @ref UART_FLAG_TEACK Transmit enable acknowledge flag * @arg @ref UART_FLAG_WUF Wake up from stop mode flag * @arg @ref UART_FLAG_RWU Receiver wake up flag (if the UART in mute mode) * @arg @ref UART_FLAG_SBKF Send Break flag * @arg @ref UART_FLAG_CMF Character match flag * @arg @ref UART_FLAG_BUSY Busy flag * @arg @ref UART_FLAG_ABRF Auto Baud rate detection flag * @arg @ref UART_FLAG_ABRE Auto Baud rate detection error flag * @arg @ref UART_FLAG_CTS CTS Change flag * @arg @ref UART_FLAG_LBDF LIN Break detection flag * @arg @ref UART_FLAG_TXE Transmit data register empty flag * @arg @ref UART_FLAG_TXFNF UART TXFIFO not full flag * @arg @ref UART_FLAG_TC Transmission Complete flag * @arg @ref UART_FLAG_RXNE Receive data register not empty flag * @arg @ref UART_FLAG_RXFNE UART RXFIFO not empty flag * @arg @ref UART_FLAG_RTOF Receiver Timeout flag * @arg @ref UART_FLAG_IDLE Idle Line detection flag * @arg @ref UART_FLAG_ORE Overrun Error flag * @arg @ref UART_FLAG_NE Noise Error flag * @arg @ref UART_FLAG_FE Framing Error flag * @arg @ref UART_FLAG_PE Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) /** @brief Enable the specified UART interrupt. * @param __HANDLE__ specifies the UART Handle. * @param __INTERRUPT__ specifies the UART interrupt source to enable. * This parameter can be one of the following values: * @arg @ref UART_IT_RXFF RXFIFO Full interrupt * @arg @ref UART_IT_TXFE TXFIFO Empty interrupt * @arg @ref UART_IT_RXFT RXFIFO threshold interrupt * @arg @ref UART_IT_TXFT TXFIFO threshold interrupt * @arg @ref UART_IT_WUF Wakeup from stop mode interrupt * @arg @ref UART_IT_CM Character match interrupt * @arg @ref UART_IT_CTS CTS change interrupt * @arg @ref UART_IT_LBD LIN Break detection interrupt * @arg @ref UART_IT_TXE Transmit Data Register empty interrupt * @arg @ref UART_IT_TXFNF TX FIFO not full interrupt * @arg @ref UART_IT_TC Transmission complete interrupt * @arg @ref UART_IT_RXNE Receive Data register not empty interrupt * @arg @ref UART_IT_RXFNE RXFIFO not empty interrupt * @arg @ref UART_IT_RTO Receive Timeout interrupt * @arg @ref UART_IT_IDLE Idle line detection interrupt * @arg @ref UART_IT_PE Parity Error interrupt * @arg @ref UART_IT_ERR Error interrupt (frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (\ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 1U)?\ ((__HANDLE__)->Instance->CR1 |= (1U <<\ ((__INTERRUPT__) & UART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2U)?\ ((__HANDLE__)->Instance->CR2 |= (1U <<\ ((__INTERRUPT__) & UART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 |= (1U <<\ ((__INTERRUPT__) & UART_IT_MASK)))) /** @brief Disable the specified UART interrupt. * @param __HANDLE__ specifies the UART Handle. * @param __INTERRUPT__ specifies the UART interrupt source to disable. * This parameter can be one of the following values: * @arg @ref UART_IT_RXFF RXFIFO Full interrupt * @arg @ref UART_IT_TXFE TXFIFO Empty interrupt * @arg @ref UART_IT_RXFT RXFIFO threshold interrupt * @arg @ref UART_IT_TXFT TXFIFO threshold interrupt * @arg @ref UART_IT_WUF Wakeup from stop mode interrupt * @arg @ref UART_IT_CM Character match interrupt * @arg @ref UART_IT_CTS CTS change interrupt * @arg @ref UART_IT_LBD LIN Break detection interrupt * @arg @ref UART_IT_TXE Transmit Data Register empty interrupt * @arg @ref UART_IT_TXFNF TX FIFO not full interrupt * @arg @ref UART_IT_TC Transmission complete interrupt * @arg @ref UART_IT_RXNE Receive Data register not empty interrupt * @arg @ref UART_IT_RXFNE RXFIFO not empty interrupt * @arg @ref UART_IT_RTO Receive Timeout interrupt * @arg @ref UART_IT_IDLE Idle line detection interrupt * @arg @ref UART_IT_PE Parity Error interrupt * @arg @ref UART_IT_ERR Error interrupt (Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (\ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 1U)?\ ((__HANDLE__)->Instance->CR1 &= ~ (1U <<\ ((__INTERRUPT__) & UART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2U)?\ ((__HANDLE__)->Instance->CR2 &= ~ (1U <<\ ((__INTERRUPT__) & UART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 &= ~ (1U <<\ ((__INTERRUPT__) & UART_IT_MASK)))) /** @brief Check whether the specified UART interrupt has occurred or not. * @param __HANDLE__ specifies the UART Handle. * @param __INTERRUPT__ specifies the UART interrupt to check. * This parameter can be one of the following values: * @arg @ref UART_IT_RXFF RXFIFO Full interrupt * @arg @ref UART_IT_TXFE TXFIFO Empty interrupt * @arg @ref UART_IT_RXFT RXFIFO threshold interrupt * @arg @ref UART_IT_TXFT TXFIFO threshold interrupt * @arg @ref UART_IT_WUF Wakeup from stop mode interrupt * @arg @ref UART_IT_CM Character match interrupt * @arg @ref UART_IT_CTS CTS change interrupt * @arg @ref UART_IT_LBD LIN Break detection interrupt * @arg @ref UART_IT_TXE Transmit Data Register empty interrupt * @arg @ref UART_IT_TXFNF TX FIFO not full interrupt * @arg @ref UART_IT_TC Transmission complete interrupt * @arg @ref UART_IT_RXNE Receive Data register not empty interrupt * @arg @ref UART_IT_RXFNE RXFIFO not empty interrupt * @arg @ref UART_IT_RTO Receive Timeout interrupt * @arg @ref UART_IT_IDLE Idle line detection interrupt * @arg @ref UART_IT_PE Parity Error interrupt * @arg @ref UART_IT_ERR Error interrupt (Frame error, noise error, overrun error) * @retval The new state of __INTERRUPT__ (SET or RESET). */ #define __HAL_UART_GET_IT(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISR\ & (1U << ((__INTERRUPT__)>> 8U))) != RESET) ? SET : RESET) /** @brief Check whether the specified UART interrupt source is enabled or not. * @param __HANDLE__ specifies the UART Handle. * @param __INTERRUPT__ specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg @ref UART_IT_RXFF RXFIFO Full interrupt * @arg @ref UART_IT_TXFE TXFIFO Empty interrupt * @arg @ref UART_IT_RXFT RXFIFO threshold interrupt * @arg @ref UART_IT_TXFT TXFIFO threshold interrupt * @arg @ref UART_IT_WUF Wakeup from stop mode interrupt * @arg @ref UART_IT_CM Character match interrupt * @arg @ref UART_IT_CTS CTS change interrupt * @arg @ref UART_IT_LBD LIN Break detection interrupt * @arg @ref UART_IT_TXE Transmit Data Register empty interrupt * @arg @ref UART_IT_TXFNF TX FIFO not full interrupt * @arg @ref UART_IT_TC Transmission complete interrupt * @arg @ref UART_IT_RXNE Receive Data register not empty interrupt * @arg @ref UART_IT_RXFNE RXFIFO not empty interrupt * @arg @ref UART_IT_RTO Receive Timeout interrupt * @arg @ref UART_IT_IDLE Idle line detection interrupt * @arg @ref UART_IT_PE Parity Error interrupt * @arg @ref UART_IT_ERR Error interrupt (Frame error, noise error, overrun error) * @retval The new state of __INTERRUPT__ (SET or RESET). */ #define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((((((uint8_t)(__INTERRUPT__)) >> 5U) == 1U) ?\ (__HANDLE__)->Instance->CR1 : \ (((((uint8_t)(__INTERRUPT__)) >> 5U) == 2U) ?\ (__HANDLE__)->Instance->CR2 : \ (__HANDLE__)->Instance->CR3)) & (1U <<\ (((uint16_t)(__INTERRUPT__)) &\ UART_IT_MASK))) != RESET) ? SET : RESET) /** @brief Clear the specified UART ISR flag, in setting the proper ICR register flag. * @param __HANDLE__ specifies the UART Handle. * @param __IT_CLEAR__ specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg @ref UART_CLEAR_PEF Parity Error Clear Flag * @arg @ref UART_CLEAR_FEF Framing Error Clear Flag * @arg @ref UART_CLEAR_NEF Noise detected Clear Flag * @arg @ref UART_CLEAR_OREF Overrun Error Clear Flag * @arg @ref UART_CLEAR_IDLEF IDLE line detected Clear Flag * @arg @ref UART_CLEAR_RTOF Receiver timeout clear flag * @arg @ref UART_CLEAR_TXFECF TXFIFO empty Clear Flag * @arg @ref UART_CLEAR_TCF Transmission Complete Clear Flag * @arg @ref UART_CLEAR_LBDF LIN Break Detection Clear Flag * @arg @ref UART_CLEAR_CTSF CTS Interrupt Clear Flag * @arg @ref UART_CLEAR_CMF Character Match Clear Flag * @arg @ref UART_CLEAR_WUF Wake Up from stop mode Clear Flag * @retval None */ #define __HAL_UART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR = (uint32_t)(__IT_CLEAR__)) /** @brief Set a specific UART request flag. * @param __HANDLE__ specifies the UART Handle. * @param __REQ__ specifies the request flag to set * This parameter can be one of the following values: * @arg @ref UART_AUTOBAUD_REQUEST Auto-Baud Rate Request * @arg @ref UART_SENDBREAK_REQUEST Send Break Request * @arg @ref UART_MUTE_MODE_REQUEST Mute Mode Request * @arg @ref UART_RXDATA_FLUSH_REQUEST Receive Data flush Request * @arg @ref UART_TXDATA_FLUSH_REQUEST Transmit data flush Request * @retval None */ #define __HAL_UART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) /** @brief Enable the UART one bit sample method. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Disable the UART one bit sample method. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= ~USART_CR3_ONEBIT) /** @brief Enable UART. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART. * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** @brief Enable CTS flow control. * @note This macro allows to enable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled * (i.e. __HAL_UART_DISABLE(__HANDLE__)) and should be followed by an Enable * macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ do{ \ ATOMIC_SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_CTSE; \ } while(0U) /** @brief Disable CTS flow control. * @note This macro allows to disable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled * (i.e. __HAL_UART_DISABLE(__HANDLE__)) and should be followed by an Enable * macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ do{ \ ATOMIC_CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_CTSE); \ } while(0U) /** @brief Enable RTS flow control. * @note This macro allows to enable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled * (i.e. __HAL_UART_DISABLE(__HANDLE__)) and should be followed by an Enable * macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ do{ \ ATOMIC_SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_RTSE; \ } while(0U) /** @brief Disable RTS flow control. * @note This macro allows to disable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled * (i.e. __HAL_UART_DISABLE(__HANDLE__)) and should be followed by an Enable * macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__ specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ do{ \ ATOMIC_CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE);\ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_RTSE); \ } while(0U) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup UART_Private_Macros UART Private Macros * @{ */ /** @brief Get UART clok division factor from clock prescaler value. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval UART clock division factor */ #define UART_GET_DIV_FACTOR(__CLOCKPRESCALER__) \ (((__CLOCKPRESCALER__) == UART_PRESCALER_DIV1) ? 1U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV2) ? 2U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV4) ? 4U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV6) ? 6U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV8) ? 8U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV10) ? 10U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV12) ? 12U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV64) ? 64U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV256) ? 256U : 1U) /** @brief BRR division operation to set BRR register with LPUART. * @param __PCLK__ LPUART clock. * @param __BAUD__ Baud rate set by the user. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval Division result */ #define UART_DIV_LPUART(__PCLK__, __BAUD__, __CLOCKPRESCALER__) \ ((uint32_t)((((((uint64_t)(__PCLK__))/(UARTPrescTable[(__CLOCKPRESCALER__)]))*256U)+ \ (uint32_t)((__BAUD__)/2U)) / (__BAUD__)) \ ) /** @brief BRR division operation to set BRR register in 8-bit oversampling mode. * @param __PCLK__ UART clock. * @param __BAUD__ Baud rate set by the user. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval Division result */ #define UART_DIV_SAMPLING8(__PCLK__, __BAUD__, __CLOCKPRESCALER__) \ (((((__PCLK__)/UARTPrescTable[(__CLOCKPRESCALER__)])*2U) + ((__BAUD__)/2U)) / (__BAUD__)) /** @brief BRR division operation to set BRR register in 16-bit oversampling mode. * @param __PCLK__ UART clock. * @param __BAUD__ Baud rate set by the user. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval Division result */ #define UART_DIV_SAMPLING16(__PCLK__, __BAUD__, __CLOCKPRESCALER__) \ ((((__PCLK__)/UARTPrescTable[(__CLOCKPRESCALER__)]) + ((__BAUD__)/2U)) / (__BAUD__)) /** @brief Check whether or not UART instance is Low Power UART. * @param __HANDLE__ specifies the UART Handle. * @retval SET (instance is LPUART) or RESET (instance isn't LPUART) */ #define UART_INSTANCE_LOWPOWER(__HANDLE__) (IS_LPUART_INSTANCE((__HANDLE__)->Instance)) /** @brief Check UART Baud rate. * @param __BAUDRATE__ Baudrate specified by the user. * The maximum Baud Rate is derived from the maximum clock on G4 (i.e. 150 MHz) * divided by the smallest oversampling used on the USART (i.e. 8) * @retval SET (__BAUDRATE__ is valid) or RESET (__BAUDRATE__ is invalid) */ #define IS_UART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 18750001U) /** @brief Check UART assertion time. * @param __TIME__ 5-bit value assertion time. * @retval Test result (TRUE or FALSE). */ #define IS_UART_ASSERTIONTIME(__TIME__) ((__TIME__) <= 0x1FU) /** @brief Check UART deassertion time. * @param __TIME__ 5-bit value deassertion time. * @retval Test result (TRUE or FALSE). */ #define IS_UART_DEASSERTIONTIME(__TIME__) ((__TIME__) <= 0x1FU) /** * @brief Ensure that UART frame number of stop bits is valid. * @param __STOPBITS__ UART frame number of stop bits. * @retval SET (__STOPBITS__ is valid) or RESET (__STOPBITS__ is invalid) */ #define IS_UART_STOPBITS(__STOPBITS__) (((__STOPBITS__) == UART_STOPBITS_0_5) || \ ((__STOPBITS__) == UART_STOPBITS_1) || \ ((__STOPBITS__) == UART_STOPBITS_1_5) || \ ((__STOPBITS__) == UART_STOPBITS_2)) /** * @brief Ensure that LPUART frame number of stop bits is valid. * @param __STOPBITS__ LPUART frame number of stop bits. * @retval SET (__STOPBITS__ is valid) or RESET (__STOPBITS__ is invalid) */ #define IS_LPUART_STOPBITS(__STOPBITS__) (((__STOPBITS__) == UART_STOPBITS_1) || \ ((__STOPBITS__) == UART_STOPBITS_2)) /** * @brief Ensure that UART frame parity is valid. * @param __PARITY__ UART frame parity. * @retval SET (__PARITY__ is valid) or RESET (__PARITY__ is invalid) */ #define IS_UART_PARITY(__PARITY__) (((__PARITY__) == UART_PARITY_NONE) || \ ((__PARITY__) == UART_PARITY_EVEN) || \ ((__PARITY__) == UART_PARITY_ODD)) /** * @brief Ensure that UART hardware flow control is valid. * @param __CONTROL__ UART hardware flow control. * @retval SET (__CONTROL__ is valid) or RESET (__CONTROL__ is invalid) */ #define IS_UART_HARDWARE_FLOW_CONTROL(__CONTROL__)\ (((__CONTROL__) == UART_HWCONTROL_NONE) || \ ((__CONTROL__) == UART_HWCONTROL_RTS) || \ ((__CONTROL__) == UART_HWCONTROL_CTS) || \ ((__CONTROL__) == UART_HWCONTROL_RTS_CTS)) /** * @brief Ensure that UART communication mode is valid. * @param __MODE__ UART communication mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_UART_MODE(__MODE__) ((((__MODE__) & (~((uint32_t)(UART_MODE_TX_RX)))) == 0x00U) && ((__MODE__) != 0x00U)) /** * @brief Ensure that UART state is valid. * @param __STATE__ UART state. * @retval SET (__STATE__ is valid) or RESET (__STATE__ is invalid) */ #define IS_UART_STATE(__STATE__) (((__STATE__) == UART_STATE_DISABLE) || \ ((__STATE__) == UART_STATE_ENABLE)) /** * @brief Ensure that UART oversampling is valid. * @param __SAMPLING__ UART oversampling. * @retval SET (__SAMPLING__ is valid) or RESET (__SAMPLING__ is invalid) */ #define IS_UART_OVERSAMPLING(__SAMPLING__) (((__SAMPLING__) == UART_OVERSAMPLING_16) || \ ((__SAMPLING__) == UART_OVERSAMPLING_8)) /** * @brief Ensure that UART frame sampling is valid. * @param __ONEBIT__ UART frame sampling. * @retval SET (__ONEBIT__ is valid) or RESET (__ONEBIT__ is invalid) */ #define IS_UART_ONE_BIT_SAMPLE(__ONEBIT__) (((__ONEBIT__) == UART_ONE_BIT_SAMPLE_DISABLE) || \ ((__ONEBIT__) == UART_ONE_BIT_SAMPLE_ENABLE)) /** * @brief Ensure that UART auto Baud rate detection mode is valid. * @param __MODE__ UART auto Baud rate detection mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(__MODE__) (((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME)) /** * @brief Ensure that UART receiver timeout setting is valid. * @param __TIMEOUT__ UART receiver timeout setting. * @retval SET (__TIMEOUT__ is valid) or RESET (__TIMEOUT__ is invalid) */ #define IS_UART_RECEIVER_TIMEOUT(__TIMEOUT__) (((__TIMEOUT__) == UART_RECEIVER_TIMEOUT_DISABLE) || \ ((__TIMEOUT__) == UART_RECEIVER_TIMEOUT_ENABLE)) /** @brief Check the receiver timeout value. * @note The maximum UART receiver timeout value is 0xFFFFFF. * @param __TIMEOUTVALUE__ receiver timeout value. * @retval Test result (TRUE or FALSE) */ #define IS_UART_RECEIVER_TIMEOUT_VALUE(__TIMEOUTVALUE__) ((__TIMEOUTVALUE__) <= 0xFFFFFFU) /** * @brief Ensure that UART LIN state is valid. * @param __LIN__ UART LIN state. * @retval SET (__LIN__ is valid) or RESET (__LIN__ is invalid) */ #define IS_UART_LIN(__LIN__) (((__LIN__) == UART_LIN_DISABLE) || \ ((__LIN__) == UART_LIN_ENABLE)) /** * @brief Ensure that UART LIN break detection length is valid. * @param __LENGTH__ UART LIN break detection length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #define IS_UART_LIN_BREAK_DETECT_LENGTH(__LENGTH__) (((__LENGTH__) == UART_LINBREAKDETECTLENGTH_10B) || \ ((__LENGTH__) == UART_LINBREAKDETECTLENGTH_11B)) /** * @brief Ensure that UART DMA TX state is valid. * @param __DMATX__ UART DMA TX state. * @retval SET (__DMATX__ is valid) or RESET (__DMATX__ is invalid) */ #define IS_UART_DMA_TX(__DMATX__) (((__DMATX__) == UART_DMA_TX_DISABLE) || \ ((__DMATX__) == UART_DMA_TX_ENABLE)) /** * @brief Ensure that UART DMA RX state is valid. * @param __DMARX__ UART DMA RX state. * @retval SET (__DMARX__ is valid) or RESET (__DMARX__ is invalid) */ #define IS_UART_DMA_RX(__DMARX__) (((__DMARX__) == UART_DMA_RX_DISABLE) || \ ((__DMARX__) == UART_DMA_RX_ENABLE)) /** * @brief Ensure that UART half-duplex state is valid. * @param __HDSEL__ UART half-duplex state. * @retval SET (__HDSEL__ is valid) or RESET (__HDSEL__ is invalid) */ #define IS_UART_HALF_DUPLEX(__HDSEL__) (((__HDSEL__) == UART_HALF_DUPLEX_DISABLE) || \ ((__HDSEL__) == UART_HALF_DUPLEX_ENABLE)) /** * @brief Ensure that UART wake-up method is valid. * @param __WAKEUP__ UART wake-up method . * @retval SET (__WAKEUP__ is valid) or RESET (__WAKEUP__ is invalid) */ #define IS_UART_WAKEUPMETHOD(__WAKEUP__) (((__WAKEUP__) == UART_WAKEUPMETHOD_IDLELINE) || \ ((__WAKEUP__) == UART_WAKEUPMETHOD_ADDRESSMARK)) /** * @brief Ensure that UART request parameter is valid. * @param __PARAM__ UART request parameter. * @retval SET (__PARAM__ is valid) or RESET (__PARAM__ is invalid) */ #define IS_UART_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == UART_AUTOBAUD_REQUEST) || \ ((__PARAM__) == UART_SENDBREAK_REQUEST) || \ ((__PARAM__) == UART_MUTE_MODE_REQUEST) || \ ((__PARAM__) == UART_RXDATA_FLUSH_REQUEST) || \ ((__PARAM__) == UART_TXDATA_FLUSH_REQUEST)) /** * @brief Ensure that UART advanced features initialization is valid. * @param __INIT__ UART advanced features initialization. * @retval SET (__INIT__ is valid) or RESET (__INIT__ is invalid) */ #define IS_UART_ADVFEATURE_INIT(__INIT__) ((__INIT__) <= (UART_ADVFEATURE_NO_INIT | \ UART_ADVFEATURE_TXINVERT_INIT | \ UART_ADVFEATURE_RXINVERT_INIT | \ UART_ADVFEATURE_DATAINVERT_INIT | \ UART_ADVFEATURE_SWAP_INIT | \ UART_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ UART_ADVFEATURE_DMADISABLEONERROR_INIT | \ UART_ADVFEATURE_AUTOBAUDRATE_INIT | \ UART_ADVFEATURE_MSBFIRST_INIT)) /** * @brief Ensure that UART frame TX inversion setting is valid. * @param __TXINV__ UART frame TX inversion setting. * @retval SET (__TXINV__ is valid) or RESET (__TXINV__ is invalid) */ #define IS_UART_ADVFEATURE_TXINV(__TXINV__) (((__TXINV__) == UART_ADVFEATURE_TXINV_DISABLE) || \ ((__TXINV__) == UART_ADVFEATURE_TXINV_ENABLE)) /** * @brief Ensure that UART frame RX inversion setting is valid. * @param __RXINV__ UART frame RX inversion setting. * @retval SET (__RXINV__ is valid) or RESET (__RXINV__ is invalid) */ #define IS_UART_ADVFEATURE_RXINV(__RXINV__) (((__RXINV__) == UART_ADVFEATURE_RXINV_DISABLE) || \ ((__RXINV__) == UART_ADVFEATURE_RXINV_ENABLE)) /** * @brief Ensure that UART frame data inversion setting is valid. * @param __DATAINV__ UART frame data inversion setting. * @retval SET (__DATAINV__ is valid) or RESET (__DATAINV__ is invalid) */ #define IS_UART_ADVFEATURE_DATAINV(__DATAINV__) (((__DATAINV__) == UART_ADVFEATURE_DATAINV_DISABLE) || \ ((__DATAINV__) == UART_ADVFEATURE_DATAINV_ENABLE)) /** * @brief Ensure that UART frame RX/TX pins swap setting is valid. * @param __SWAP__ UART frame RX/TX pins swap setting. * @retval SET (__SWAP__ is valid) or RESET (__SWAP__ is invalid) */ #define IS_UART_ADVFEATURE_SWAP(__SWAP__) (((__SWAP__) == UART_ADVFEATURE_SWAP_DISABLE) || \ ((__SWAP__) == UART_ADVFEATURE_SWAP_ENABLE)) /** * @brief Ensure that UART frame overrun setting is valid. * @param __OVERRUN__ UART frame overrun setting. * @retval SET (__OVERRUN__ is valid) or RESET (__OVERRUN__ is invalid) */ #define IS_UART_OVERRUN(__OVERRUN__) (((__OVERRUN__) == UART_ADVFEATURE_OVERRUN_ENABLE) || \ ((__OVERRUN__) == UART_ADVFEATURE_OVERRUN_DISABLE)) /** * @brief Ensure that UART auto Baud rate state is valid. * @param __AUTOBAUDRATE__ UART auto Baud rate state. * @retval SET (__AUTOBAUDRATE__ is valid) or RESET (__AUTOBAUDRATE__ is invalid) */ #define IS_UART_ADVFEATURE_AUTOBAUDRATE(__AUTOBAUDRATE__) (((__AUTOBAUDRATE__) == \ UART_ADVFEATURE_AUTOBAUDRATE_DISABLE) || \ ((__AUTOBAUDRATE__) == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE)) /** * @brief Ensure that UART DMA enabling or disabling on error setting is valid. * @param __DMA__ UART DMA enabling or disabling on error setting. * @retval SET (__DMA__ is valid) or RESET (__DMA__ is invalid) */ #define IS_UART_ADVFEATURE_DMAONRXERROR(__DMA__) (((__DMA__) == UART_ADVFEATURE_DMA_ENABLEONRXERROR) || \ ((__DMA__) == UART_ADVFEATURE_DMA_DISABLEONRXERROR)) /** * @brief Ensure that UART frame MSB first setting is valid. * @param __MSBFIRST__ UART frame MSB first setting. * @retval SET (__MSBFIRST__ is valid) or RESET (__MSBFIRST__ is invalid) */ #define IS_UART_ADVFEATURE_MSBFIRST(__MSBFIRST__) (((__MSBFIRST__) == UART_ADVFEATURE_MSBFIRST_DISABLE) || \ ((__MSBFIRST__) == UART_ADVFEATURE_MSBFIRST_ENABLE)) /** * @brief Ensure that UART stop mode state is valid. * @param __STOPMODE__ UART stop mode state. * @retval SET (__STOPMODE__ is valid) or RESET (__STOPMODE__ is invalid) */ #define IS_UART_ADVFEATURE_STOPMODE(__STOPMODE__) (((__STOPMODE__) == UART_ADVFEATURE_STOPMODE_DISABLE) || \ ((__STOPMODE__) == UART_ADVFEATURE_STOPMODE_ENABLE)) /** * @brief Ensure that UART mute mode state is valid. * @param __MUTE__ UART mute mode state. * @retval SET (__MUTE__ is valid) or RESET (__MUTE__ is invalid) */ #define IS_UART_MUTE_MODE(__MUTE__) (((__MUTE__) == UART_ADVFEATURE_MUTEMODE_DISABLE) || \ ((__MUTE__) == UART_ADVFEATURE_MUTEMODE_ENABLE)) /** * @brief Ensure that UART wake-up selection is valid. * @param __WAKE__ UART wake-up selection. * @retval SET (__WAKE__ is valid) or RESET (__WAKE__ is invalid) */ #define IS_UART_WAKEUP_SELECTION(__WAKE__) (((__WAKE__) == UART_WAKEUP_ON_ADDRESS) || \ ((__WAKE__) == UART_WAKEUP_ON_STARTBIT) || \ ((__WAKE__) == UART_WAKEUP_ON_READDATA_NONEMPTY)) /** * @brief Ensure that UART driver enable polarity is valid. * @param __POLARITY__ UART driver enable polarity. * @retval SET (__POLARITY__ is valid) or RESET (__POLARITY__ is invalid) */ #define IS_UART_DE_POLARITY(__POLARITY__) (((__POLARITY__) == UART_DE_POLARITY_HIGH) || \ ((__POLARITY__) == UART_DE_POLARITY_LOW)) /** * @brief Ensure that UART Prescaler is valid. * @param __CLOCKPRESCALER__ UART Prescaler value. * @retval SET (__CLOCKPRESCALER__ is valid) or RESET (__CLOCKPRESCALER__ is invalid) */ #define IS_UART_PRESCALER(__CLOCKPRESCALER__) (((__CLOCKPRESCALER__) == UART_PRESCALER_DIV1) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV2) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV4) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV6) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV8) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV10) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV12) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV16) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV32) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV64) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) || \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV256)) /** * @} */ /* Include UART HAL Extended module */ #include "stm32g4xx_hal_uart_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup UART_Exported_Functions UART Exported Functions * @{ */ /** @addtogroup UART_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); /* Callbacks Register/UnRegister functions ***********************************/ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) HAL_StatusTypeDef HAL_UART_RegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID, pUART_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID); HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback); HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ /** * @} */ /** @addtogroup UART_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); /* Transfer Abort functions */ HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart); void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); void HAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart); void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size); /** * @} */ /** @addtogroup UART_Exported_Functions_Group3 Peripheral Control functions * @{ */ /* Peripheral Control functions ************************************************/ void HAL_UART_ReceiverTimeout_Config(UART_HandleTypeDef *huart, uint32_t TimeoutValue); HAL_StatusTypeDef HAL_UART_EnableReceiverTimeout(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DisableReceiverTimeout(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart); void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group4 Peripheral State and Error functions * @{ */ /* Peripheral State and Errors functions **************************************************/ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ /** * @} */ /* Private functions -----------------------------------------------------------*/ /** @addtogroup UART_Private_Functions UART Private Functions * @{ */ #if (USE_HAL_UART_REGISTER_CALLBACKS == 1) void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); /** * @} */ /* Private variables -----------------------------------------------------------*/ /** @defgroup UART_Private_variables UART Private variables * @{ */ /* Prescaler Table used in BRR computation macros. Declared as extern here to allow use of private UART macros, outside of HAL UART functions */ extern const uint16_t UARTPrescTable[12]; /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_UART_H */
89,338
C
50.820766
119
0.541606
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/Drivers/STM32G4xx_HAL_Driver/Inc/stm32g4xx_hal_uart_ex.h
/** ****************************************************************************** * @file stm32g4xx_hal_uart_ex.h * @author MCD Application Team * @brief Header file of UART HAL Extended 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_UART_EX_H #define STM32G4xx_HAL_UART_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal_def.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup UARTEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UARTEx_Exported_Types UARTEx Exported Types * @{ */ /** * @brief UART wake up from stop mode parameters */ typedef struct { uint32_t WakeUpEvent; /*!< Specifies which event will activate the Wakeup from Stop mode flag (WUF). This parameter can be a value of @ref UART_WakeUp_from_Stop_Selection. If set to UART_WAKEUP_ON_ADDRESS, the two other fields below must be filled up. */ uint16_t AddressLength; /*!< Specifies whether the address is 4 or 7-bit long. This parameter can be a value of @ref UARTEx_WakeUp_Address_Length. */ uint8_t Address; /*!< UART/USART node address (7-bit long max). */ } UART_WakeUpTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UARTEx_Exported_Constants UARTEx Exported Constants * @{ */ /** @defgroup UARTEx_Word_Length UARTEx Word Length * @{ */ #define UART_WORDLENGTH_7B USART_CR1_M1 /*!< 7-bit long UART frame */ #define UART_WORDLENGTH_8B 0x00000000U /*!< 8-bit long UART frame */ #define UART_WORDLENGTH_9B USART_CR1_M0 /*!< 9-bit long UART frame */ /** * @} */ /** @defgroup UARTEx_WakeUp_Address_Length UARTEx WakeUp Address Length * @{ */ #define UART_ADDRESS_DETECT_4B 0x00000000U /*!< 4-bit long wake-up address */ #define UART_ADDRESS_DETECT_7B USART_CR2_ADDM7 /*!< 7-bit long wake-up address */ /** * @} */ /** @defgroup UARTEx_FIFO_mode UARTEx FIFO mode * @brief UART FIFO mode * @{ */ #define UART_FIFOMODE_DISABLE 0x00000000U /*!< FIFO mode disable */ #define UART_FIFOMODE_ENABLE USART_CR1_FIFOEN /*!< FIFO mode enable */ /** * @} */ /** @defgroup UARTEx_TXFIFO_threshold_level UARTEx TXFIFO threshold level * @brief UART TXFIFO threshold level * @{ */ #define UART_TXFIFO_THRESHOLD_1_8 0x00000000U /*!< TX FIFO reaches 1/8 of its depth */ #define UART_TXFIFO_THRESHOLD_1_4 USART_CR3_TXFTCFG_0 /*!< TX FIFO reaches 1/4 of its depth */ #define UART_TXFIFO_THRESHOLD_1_2 USART_CR3_TXFTCFG_1 /*!< TX FIFO reaches 1/2 of its depth */ #define UART_TXFIFO_THRESHOLD_3_4 (USART_CR3_TXFTCFG_0|USART_CR3_TXFTCFG_1) /*!< TX FIFO reaches 3/4 of its depth */ #define UART_TXFIFO_THRESHOLD_7_8 USART_CR3_TXFTCFG_2 /*!< TX FIFO reaches 7/8 of its depth */ #define UART_TXFIFO_THRESHOLD_8_8 (USART_CR3_TXFTCFG_2|USART_CR3_TXFTCFG_0) /*!< TX FIFO becomes empty */ /** * @} */ /** @defgroup UARTEx_RXFIFO_threshold_level UARTEx RXFIFO threshold level * @brief UART RXFIFO threshold level * @{ */ #define UART_RXFIFO_THRESHOLD_1_8 0x00000000U /*!< RX FIFO reaches 1/8 of its depth */ #define UART_RXFIFO_THRESHOLD_1_4 USART_CR3_RXFTCFG_0 /*!< RX FIFO reaches 1/4 of its depth */ #define UART_RXFIFO_THRESHOLD_1_2 USART_CR3_RXFTCFG_1 /*!< RX FIFO reaches 1/2 of its depth */ #define UART_RXFIFO_THRESHOLD_3_4 (USART_CR3_RXFTCFG_0|USART_CR3_RXFTCFG_1) /*!< RX FIFO reaches 3/4 of its depth */ #define UART_RXFIFO_THRESHOLD_7_8 USART_CR3_RXFTCFG_2 /*!< RX FIFO reaches 7/8 of its depth */ #define UART_RXFIFO_THRESHOLD_8_8 (USART_CR3_RXFTCFG_2|USART_CR3_RXFTCFG_0) /*!< RX FIFO becomes full */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UARTEx_Exported_Functions * @{ */ /** @addtogroup UARTEx_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, uint32_t DeassertionTime); /** * @} */ /** @addtogroup UARTEx_Exported_Functions_Group2 * @{ */ void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart); void HAL_UARTEx_RxFifoFullCallback(UART_HandleTypeDef *huart); void HAL_UARTEx_TxFifoEmptyCallback(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UARTEx_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions **********************************************/ HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength); HAL_StatusTypeDef HAL_UARTEx_EnableFifoMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UARTEx_SetTxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold); HAL_StatusTypeDef HAL_UARTEx_SetRxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold); HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, uint32_t Timeout); HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup UARTEx_Private_Macros UARTEx Private Macros * @{ */ /** @brief Report the UART clock source. * @param __HANDLE__ specifies the UART Handle. * @param __CLOCKSOURCE__ output variable. * @retval UART clocking source, written in __CLOCKSOURCE__. */ #if defined(UART5) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK2: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == UART4) \ { \ switch(__HAL_RCC_GET_UART4_SOURCE()) \ { \ case RCC_UART4CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_UART4CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_UART4CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_UART4CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == UART5) \ { \ switch(__HAL_RCC_GET_UART5_SOURCE()) \ { \ case RCC_UART5CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_UART5CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_UART5CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_UART5CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == LPUART1) \ { \ switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ { \ case RCC_LPUART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_LPUART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_LPUART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_LPUART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) #elif defined(UART4) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK2: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == UART4) \ { \ switch(__HAL_RCC_GET_UART4_SOURCE()) \ { \ case RCC_UART4CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_UART4CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_UART4CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_UART4CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == LPUART1) \ { \ switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ { \ case RCC_LPUART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_LPUART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_LPUART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_LPUART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) #else #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK2: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == LPUART1) \ { \ switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ { \ case RCC_LPUART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_LPUART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_LPUART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_LPUART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) #endif /* UART5 */ /** @brief Report the UART mask to apply to retrieve the received data * according to the word length and to the parity bits activation. * @note If PCE = 1, the parity bit is not included in the data extracted * by the reception API(). * This masking operation is not carried out in the case of * DMA transfers. * @param __HANDLE__ specifies the UART Handle. * @retval None, the mask to apply to UART RDR register is stored in (__HANDLE__)->Mask field. */ #define UART_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FFU ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FFU ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FFU ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007FU ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_7B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x007FU ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x003FU ; \ } \ } \ else \ { \ (__HANDLE__)->Mask = 0x0000U; \ } \ } while(0U) /** * @brief Ensure that UART frame length is valid. * @param __LENGTH__ UART frame length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #define IS_UART_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == UART_WORDLENGTH_7B) || \ ((__LENGTH__) == UART_WORDLENGTH_8B) || \ ((__LENGTH__) == UART_WORDLENGTH_9B)) /** * @brief Ensure that UART wake-up address length is valid. * @param __ADDRESS__ UART wake-up address length. * @retval SET (__ADDRESS__ is valid) or RESET (__ADDRESS__ is invalid) */ #define IS_UART_ADDRESSLENGTH_DETECT(__ADDRESS__) (((__ADDRESS__) == UART_ADDRESS_DETECT_4B) || \ ((__ADDRESS__) == UART_ADDRESS_DETECT_7B)) /** * @brief Ensure that UART TXFIFO threshold level is valid. * @param __THRESHOLD__ UART TXFIFO threshold level. * @retval SET (__THRESHOLD__ is valid) or RESET (__THRESHOLD__ is invalid) */ #define IS_UART_TXFIFO_THRESHOLD(__THRESHOLD__) (((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_1_8) || \ ((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_1_4) || \ ((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_1_2) || \ ((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_3_4) || \ ((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_7_8) || \ ((__THRESHOLD__) == UART_TXFIFO_THRESHOLD_8_8)) /** * @brief Ensure that UART RXFIFO threshold level is valid. * @param __THRESHOLD__ UART RXFIFO threshold level. * @retval SET (__THRESHOLD__ is valid) or RESET (__THRESHOLD__ is invalid) */ #define IS_UART_RXFIFO_THRESHOLD(__THRESHOLD__) (((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_1_8) || \ ((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_1_4) || \ ((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_1_2) || \ ((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_3_4) || \ ((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_7_8) || \ ((__THRESHOLD__) == UART_RXFIFO_THRESHOLD_8_8)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_UART_EX_H */
34,560
C
52.007669
119
0.334635