repo_id
stringlengths 27
162
| file_path
stringlengths 42
195
| content
stringlengths 4
5.16M
| __index_level_0__
int64 0
0
|
---|---|---|---|
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim.c | /**
******************************************************************************
* @file stm32f4xx_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
@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 and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an
Output Compare signal.
(++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a
PWM signal.
(++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an
external signal.
(++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer
in One Pulse Mode.
(++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface.
(#) Activate the TIM peripheral using one of the start functions depending from the feature used:
(++) Time Base : HAL_TIM_Base_Start(), HAL_TIM_Base_Start_DMA(), HAL_TIM_Base_Start_IT()
(++) Input Capture : HAL_TIM_IC_Start(), HAL_TIM_IC_Start_DMA(), HAL_TIM_IC_Start_IT()
(++) Output Compare : HAL_TIM_OC_Start(), HAL_TIM_OC_Start_DMA(), HAL_TIM_OC_Start_IT()
(++) PWM generation : HAL_TIM_PWM_Start(), HAL_TIM_PWM_Start_DMA(), HAL_TIM_PWM_Start_IT()
(++) One-pulse mode output : HAL_TIM_OnePulse_Start(), HAL_TIM_OnePulse_Start_IT()
(++) Encoder mode output : HAL_TIM_Encoder_Start(), HAL_TIM_Encoder_Start_DMA(), HAL_TIM_Encoder_Start_IT().
(#) The DMA Burst is managed with the two following functions:
HAL_TIM_DMABurst_WriteStart()
HAL_TIM_DMABurst_ReadStart()
*** 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 @ref HAL_TIM_RegisterCallback() to register a callback.
@ref HAL_TIM_RegisterCallback() takes as parameters the HAL peripheral handle,
the Callback ID and a pointer to the user callback function.
[..]
Use function @ref HAL_TIM_UnRegisterCallback() to reset a callback to the default
weak function.
@ref 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.
[..]
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 @ref HAL_TIM_TriggerCallback(), @ref 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 @ref 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
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup TIM TIM
* @brief TIM HAL module driver
* @{
*/
#ifdef HAL_TIM_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* 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_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_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 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 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));
/* Set the TIM state */
htim->State = HAL_TIM_STATE_BUSY;
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Change the TIM state*/
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Base generation.
* @param htim TIM Base handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim)
{
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
/* Set the TIM state */
htim->State = HAL_TIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Change the TIM state*/
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Base generation in interrupt mode.
* @param htim TIM 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));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* 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));
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
{
/* nothing to do */
}
/* 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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length) != HAL_OK)
{
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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* Change the htim 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 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 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
* @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));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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
* @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);
/* 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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Enable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Enable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Enable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
if (IS_TIM_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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Output Compare signal generation in interrupt mode.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @arg TIM_CHANNEL_4: TIM Channel 4 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Disable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Disable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Disable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Disable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
{
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Output Compare signal generation in DMA mode.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @arg TIM_CHANNEL_4: TIM Channel 4 selected
* @param pData The source Buffer address.
* @param Length The length of data to be transferred from memory to TIM peripheral
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((pData == NULL) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Capture/Compare 4 DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
break;
}
default:
break;
}
/* Enable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
if (IS_TIM_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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Output Compare signal generation in DMA mode.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @arg TIM_CHANNEL_4: TIM Channel 4 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 DMA request */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
(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:
break;
}
/* 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);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @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 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 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
* @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));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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
* @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);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the PWM signal generation in interrupt mode.
* @param htim TIM 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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Enable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Enable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
if (IS_TIM_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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Disable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Disable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Disable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Disable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
{
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM PWM signal generation in DMA mode.
* @param htim TIM 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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((pData == NULL) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Capture/Compare 4 DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
break;
}
default:
break;
}
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
if (IS_TIM_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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @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)
{
/* 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:
break;
}
/* 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);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @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 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 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;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Enable the Input Capture channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* 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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Enable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Enable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Enable the Input Capture channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Disable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Disable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
break;
}
case TIM_CHANNEL_4:
{
/* Disable the TIM Capture/Compare 4 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
break;
}
default:
break;
}
/* Disable the Input Capture channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Input Capture measurement 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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((pData == NULL) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Capture/Compare 4 DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
break;
}
default:
break;
}
/* Enable the Input Capture channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 DMA request */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
(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:
break;
}
/* Disable the Input Capture channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup TIM_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()
* @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 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 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.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
/* Enable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
No need to enable the counter, it's enabled automatically by hardware
(the counter starts in response to a stimulus and generate a pulse */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
if (IS_TIM_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.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channels to be disable
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* 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
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
{
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM One Pulse signal generation in interrupt mode.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
/* Enable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
No need to enable the counter, it's enabled automatically by hardware
(the counter starts in response to a stimulus and generate a pulse */
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
if (IS_TIM_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.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* 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
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
{
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* 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
* @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_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_CC2_INSTANCE(htim->Instance));
assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode));
assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection));
assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection));
assert_param(IS_TIM_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 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 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)
{
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
/* Enable the encoder interface channels */
switch (Channel)
{
case TIM_CHANNEL_1:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
break;
}
case TIM_CHANNEL_2:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
break;
}
default :
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
break;
}
}
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Encoder Interface.
* @param htim TIM Encoder Interface handle
* @param Channel TIM Channels to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @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_CC2_INSTANCE(htim->Instance));
/* Disable the Input Capture channels 1 and 2
(in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
switch (Channel)
{
case TIM_CHANNEL_1:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
break;
}
case TIM_CHANNEL_2:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
break;
}
default :
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
break;
}
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Encoder Interface in interrupt mode.
* @param htim TIM Encoder Interface handle
* @param Channel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
/* Enable the encoder interface channels */
/* Enable the capture compare Interrupts 1 and/or 2 */
switch (Channel)
{
case TIM_CHANNEL_1:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
default :
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
}
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Encoder Interface in interrupt mode.
* @param htim TIM Encoder Interface handle
* @param Channel TIM Channels to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @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_CC2_INSTANCE(htim->Instance));
/* Disable the Input Capture channels 1 and 2
(in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
if (Channel == TIM_CHANNEL_1)
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
/* Disable the capture compare Interrupts 1 */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
}
else if (Channel == TIM_CHANNEL_2)
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
/* Disable the capture compare Interrupts 2 */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
}
else
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
/* Disable the capture compare Interrupts 1 and 2 */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
}
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Encoder Interface in DMA mode.
* @param htim TIM Encoder Interface handle
* @param Channel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Input Capture DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
break;
}
case TIM_CHANNEL_2:
{
/* Set the DMA 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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Input Capture DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
break;
}
case TIM_CHANNEL_ALL:
{
/* Set the DMA 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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
/* Enable the TIM Input Capture DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
/* Enable the TIM Input Capture DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
break;
}
default:
break;
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Encoder Interface in DMA mode.
* @param htim TIM Encoder Interface handle
* @param Channel TIM Channels to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @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_DMA_CC_INSTANCE(htim->Instance));
/* Disable the Input Capture channels 1 and 2
(in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
if (Channel == TIM_CHANNEL_1)
{
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
/* Disable the capture compare DMA Request 1 */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
(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);
/* Change the htim state */
htim->State = HAL_TIM_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 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 */
}
}
}
/**
* @}
*/
/** @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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim,
TIM_OC_InitTypeDef *sConfig,
uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_CHANNELS(Channel));
assert_param(IS_TIM_OC_MODE(sConfig->OCMode));
assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity));
/* Process Locked */
__HAL_LOCK(htim);
htim->State = HAL_TIM_STATE_BUSY;
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;
}
default:
break;
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Initializes the TIM Input Capture Channels according to the specified
* parameters in the TIM_IC_InitTypeDef.
* @param htim TIM IC handle
* @param sConfig TIM Input Capture configuration structure
* @param Channel TIM 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)
{
/* 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);
htim->State = HAL_TIM_STATE_BUSY;
if (Channel == TIM_CHANNEL_1)
{
/* TI1 Configuration */
TIM_TI1_SetConfig(htim->Instance,
sConfig->ICPolarity,
sConfig->ICSelection,
sConfig->ICFilter);
/* Reset the IC1PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
/* Set the IC1PSC value */
htim->Instance->CCMR1 |= sConfig->ICPrescaler;
}
else if (Channel == TIM_CHANNEL_2)
{
/* TI2 Configuration */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
TIM_TI2_SetConfig(htim->Instance,
sConfig->ICPolarity,
sConfig->ICSelection,
sConfig->ICFilter);
/* Reset the IC2PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
/* Set the IC2PSC value */
htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 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
{
/* 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);
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Initializes the TIM PWM channels according to the specified
* parameters in the TIM_OC_InitTypeDef.
* @param htim TIM 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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim,
TIM_OC_InitTypeDef *sConfig,
uint32_t Channel)
{
/* 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);
htim->State = HAL_TIM_STATE_BUSY;
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;
}
default:
break;
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Initializes the TIM One Pulse Channels according to the specified
* parameters in the TIM_OnePulse_InitTypeDef.
* @param htim TIM One Pulse handle
* @param sConfig TIM One Pulse configuration structure
* @param OutputChannel TIM 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)
{
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:
break;
}
switch (InputChannel)
{
case TIM_CHANNEL_1:
{
assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity,
sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC1PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
/* Select the Trigger source */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= TIM_TS_TI1FP1;
/* Select the Slave Mode */
htim->Instance->SMCR &= ~TIM_SMCR_SMS;
htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
break;
}
case TIM_CHANNEL_2:
{
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity,
sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC2PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
/* Select the Trigger source */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= TIM_TS_TI2FP2;
/* Select the Slave Mode */
htim->Instance->SMCR &= ~TIM_SMCR_SMS;
htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
break;
}
default:
break;
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral
* @param htim TIM handle
* @param BurstBaseAddress TIM Base address from 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
* @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_18TRANSFERS.
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
assert_param(IS_TIM_DMA_LENGTH(BurstLength));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((BurstBuffer == NULL) && (BurstLength > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer,
(uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
return HAL_ERROR;
}
break;
}
default:
break;
}
/* configure the DMA Burst Mode */
htim->Instance->DCR = (BurstBaseAddress | BurstLength);
/* Enable the TIM DMA Request */
__HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM DMA Burst mode
* @param htim TIM handle
* @param BurstRequestSrc TIM DMA Request sources to disable
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
/* Abort the DMA transfer (at least disable the DMA stream) */
switch (BurstRequestSrc)
{
case TIM_DMA_UPDATE:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]);
break;
}
case TIM_DMA_CC1:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]);
break;
}
case TIM_DMA_CC2:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]);
break;
}
case TIM_DMA_CC3:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]);
break;
}
case TIM_DMA_CC4:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]);
break;
}
case TIM_DMA_COM:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]);
break;
}
case TIM_DMA_TRIGGER:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]);
break;
}
default:
break;
}
if (HAL_OK == status)
{
/* Disable the TIM Update DMA request */
__HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc);
}
/* 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
* @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_18TRANSFERS.
* @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)
{
/* Check the parameters */
assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
assert_param(IS_TIM_DMA_LENGTH(BurstLength));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if ((BurstBuffer == NULL) && (BurstLength > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
return HAL_ERROR;
}
break;
}
case TIM_DMA_CC2:
{
/* Set the DMA capture/compare 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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U) != HAL_OK)
{
return HAL_ERROR;
}
break;
}
default:
break;
}
/* configure the DMA Burst Mode */
htim->Instance->DCR = (BurstBaseAddress | BurstLength);
/* Enable the TIM DMA Request */
__HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Stop the DMA burst reading
* @param htim TIM handle
* @param BurstRequestSrc TIM DMA Request sources to disable.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
/* Abort the DMA transfer (at least disable the DMA stream) */
switch (BurstRequestSrc)
{
case TIM_DMA_UPDATE:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]);
break;
}
case TIM_DMA_CC1:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]);
break;
}
case TIM_DMA_CC2:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]);
break;
}
case TIM_DMA_CC3:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]);
break;
}
case TIM_DMA_CC4:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]);
break;
}
case TIM_DMA_COM:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]);
break;
}
case TIM_DMA_TRIGGER:
{
status = HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]);
break;
}
default:
break;
}
if (HAL_OK == status)
{
/* Disable the TIM Update DMA request */
__HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc);
}
/* 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
* @note Basic timers can only generate an update event.
* @note TIM_EVENTSOURCE_COM is relevant only with advanced timer instances.
* @note TIM_EVENTSOURCE_BREAK are relevant only for timer instances
* supporting a break input.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource)
{
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
assert_param(IS_TIM_EVENT_SOURCE(EventSource));
/* Process Locked */
__HAL_LOCK(htim);
/* Change the TIM state */
htim->State = HAL_TIM_STATE_BUSY;
/* Set the event sources */
htim->Instance->EGR = EventSource;
/* Change the TIM state */
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Configures the OCRef clear feature
* @param htim TIM handle
* @param sClearInputConfig pointer to a TIM_ClearInputConfigTypeDef structure that
* contains the OCREF clear feature and parameters for the TIM peripheral.
* @param Channel specifies the TIM Channel
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1
* @arg TIM_CHANNEL_2: TIM Channel 2
* @arg TIM_CHANNEL_3: TIM Channel 3
* @arg TIM_CHANNEL_4: TIM Channel 4
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim,
TIM_ClearInputConfigTypeDef *sClearInputConfig,
uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance));
assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource));
/* Process Locked */
__HAL_LOCK(htim);
htim->State = HAL_TIM_STATE_BUSY;
switch (sClearInputConfig->ClearInputSource)
{
case TIM_CLEARINPUTSOURCE_NONE:
{
/* Clear the OCREF clear selection bit and the the ETR Bits */
CLEAR_BIT(htim->Instance->SMCR, (TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP));
break;
}
case TIM_CLEARINPUTSOURCE_ETR:
{
/* Check the parameters */
assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity));
assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler));
assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter));
/* When OCRef clear feature is used with ETR source, ETR prescaler must be off */
if (sClearInputConfig->ClearInputPrescaler != TIM_CLEARINPUTPRESCALER_DIV1)
{
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_ERROR;
}
TIM_ETR_SetConfig(htim->Instance,
sClearInputConfig->ClearInputPrescaler,
sClearInputConfig->ClearInputPolarity,
sClearInputConfig->ClearInputFilter);
break;
}
default:
break;
}
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;
}
default:
break;
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Configures the clock source to be used
* @param htim TIM handle
* @param sClockSourceConfig pointer to a TIM_ClockConfigTypeDef structure that
* contains the clock source information for the TIM peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef *sClockSourceConfig)
{
uint32_t tmpsmcr;
/* 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:
{
/* Check whether or not the timer instance supports internal trigger input */
assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
TIM_ITRx_SetConfig(htim->Instance, sClockSourceConfig->ClockSource);
break;
}
default:
break;
}
htim->State = HAL_TIM_STATE_READY;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Selects the signal connected to the TI1 input: direct from CH1_input
* or a XOR combination between CH1_input, CH2_input & CH3_input
* @param htim TIM handle.
* @param TI1_Selection Indicate whether or not channel 1 is connected to the
* output of a XOR gate.
* This parameter can be one of the following values:
* @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input
* @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3
* pins are connected to the TI1 input (XOR combination)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection)
{
uint32_t tmpcr2;
/* 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).
* @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_SELECTION(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).
* @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_SELECTION(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
@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
* @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;
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
* @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 :
htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; /* Legacy weak Base MspInit Callback */
break;
case HAL_TIM_BASE_MSPDEINIT_CB_ID :
htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; /* Legacy weak Base Msp DeInit Callback */
break;
case HAL_TIM_IC_MSPINIT_CB_ID :
htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; /* Legacy weak IC Msp Init Callback */
break;
case HAL_TIM_IC_MSPDEINIT_CB_ID :
htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; /* Legacy weak IC Msp DeInit Callback */
break;
case HAL_TIM_OC_MSPINIT_CB_ID :
htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; /* Legacy weak OC Msp Init Callback */
break;
case HAL_TIM_OC_MSPDEINIT_CB_ID :
htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; /* Legacy weak OC Msp DeInit Callback */
break;
case HAL_TIM_PWM_MSPINIT_CB_ID :
htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; /* Legacy weak PWM Msp Init Callback */
break;
case HAL_TIM_PWM_MSPDEINIT_CB_ID :
htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; /* Legacy weak PWM Msp DeInit Callback */
break;
case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID :
htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; /* Legacy weak One Pulse Msp Init Callback */
break;
case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID :
htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; /* Legacy weak One Pulse Msp DeInit Callback */
break;
case HAL_TIM_ENCODER_MSPINIT_CB_ID :
htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; /* Legacy weak Encoder Msp Init Callback */
break;
case HAL_TIM_ENCODER_MSPDEINIT_CB_ID :
htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; /* Legacy weak Encoder Msp DeInit Callback */
break;
case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID :
htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; /* Legacy weak Hall Sensor Msp Init Callback */
break;
case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID :
htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; /* Legacy weak Hall Sensor Msp DeInit Callback */
break;
case HAL_TIM_PERIOD_ELAPSED_CB_ID :
htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; /* Legacy weak Period Elapsed Callback */
break;
case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID :
htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; /* Legacy weak Period Elapsed half complete Callback */
break;
case HAL_TIM_TRIGGER_CB_ID :
htim->TriggerCallback = HAL_TIM_TriggerCallback; /* Legacy weak Trigger Callback */
break;
case HAL_TIM_TRIGGER_HALF_CB_ID :
htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; /* Legacy weak Trigger half complete Callback */
break;
case HAL_TIM_IC_CAPTURE_CB_ID :
htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; /* Legacy weak IC Capture Callback */
break;
case HAL_TIM_IC_CAPTURE_HALF_CB_ID :
htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; /* Legacy weak IC Capture half complete Callback */
break;
case HAL_TIM_OC_DELAY_ELAPSED_CB_ID :
htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; /* Legacy weak OC Delay Elapsed Callback */
break;
case HAL_TIM_PWM_PULSE_FINISHED_CB_ID :
htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; /* Legacy weak PWM Pulse Finished Callback */
break;
case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID :
htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; /* Legacy weak PWM Pulse Finished half complete Callback */
break;
case HAL_TIM_ERROR_CB_ID :
htim->ErrorCallback = HAL_TIM_ErrorCallback; /* Legacy weak Error Callback */
break;
case HAL_TIM_COMMUTATION_CB_ID :
htim->CommutationCallback = HAL_TIMEx_CommutCallback; /* Legacy weak Commutation Callback */
break;
case HAL_TIM_COMMUTATION_HALF_CB_ID :
htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; /* Legacy weak Commutation half complete Callback */
break;
case HAL_TIM_BREAK_CB_ID :
htim->BreakCallback = HAL_TIMEx_BreakCallback; /* Legacy weak Break Callback */
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 = HAL_TIM_Base_MspInit; /* Legacy weak Base MspInit Callback */
break;
case HAL_TIM_BASE_MSPDEINIT_CB_ID :
htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; /* Legacy weak Base Msp DeInit Callback */
break;
case HAL_TIM_IC_MSPINIT_CB_ID :
htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; /* Legacy weak IC Msp Init Callback */
break;
case HAL_TIM_IC_MSPDEINIT_CB_ID :
htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; /* Legacy weak IC Msp DeInit Callback */
break;
case HAL_TIM_OC_MSPINIT_CB_ID :
htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; /* Legacy weak OC Msp Init Callback */
break;
case HAL_TIM_OC_MSPDEINIT_CB_ID :
htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; /* Legacy weak OC Msp DeInit Callback */
break;
case HAL_TIM_PWM_MSPINIT_CB_ID :
htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; /* Legacy weak PWM Msp Init Callback */
break;
case HAL_TIM_PWM_MSPDEINIT_CB_ID :
htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; /* Legacy weak PWM Msp DeInit Callback */
break;
case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID :
htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; /* Legacy weak One Pulse Msp Init Callback */
break;
case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID :
htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; /* Legacy weak One Pulse Msp DeInit Callback */
break;
case HAL_TIM_ENCODER_MSPINIT_CB_ID :
htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; /* Legacy weak Encoder Msp Init Callback */
break;
case HAL_TIM_ENCODER_MSPDEINIT_CB_ID :
htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; /* Legacy weak Encoder Msp DeInit Callback */
break;
case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID :
htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; /* Legacy weak Hall Sensor Msp Init Callback */
break;
case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID :
htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; /* Legacy weak Hall Sensor Msp DeInit Callback */
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;
}
/**
* @}
*/
/**
* @}
*/
/** @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;
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 */
}
/**
* @brief TIM DMA Delay Pulse complete callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma)
{
TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
htim->State = HAL_TIM_STATE_READY;
if (hdma == htim->hdma[TIM_DMA_ID_CC1])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC2])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC3])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC4])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
}
else
{
/* nothing to do */
}
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->PWM_PulseFinishedCallback(htim);
#else
HAL_TIM_PWM_PulseFinishedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
/**
* @brief TIM DMA Delay Pulse half complete callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void TIM_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma)
{
TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
htim->State = HAL_TIM_STATE_READY;
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;
htim->State = HAL_TIM_STATE_READY;
if (hdma == htim->hdma[TIM_DMA_ID_CC1])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC2])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC3])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
}
else if (hdma == htim->hdma[TIM_DMA_ID_CC4])
{
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
}
else
{
/* nothing to do */
}
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->IC_CaptureCallback(htim);
#else
HAL_TIM_IC_CaptureCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
/**
* @brief TIM DMA Capture half complete callback.
* @param hdma pointer to DMA handle.
* @retval None
*/
void TIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma)
{
TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
htim->State = HAL_TIM_STATE_READY;
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;
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;
htim->State = HAL_TIM_STATE_READY;
#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;
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;
htim->State = HAL_TIM_STATE_READY;
#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 ouput 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 ouput 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 ouput 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 ouput 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_BREAK_INSTANCE(TIMx))
{
/* Check parameters */
assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
/* Reset the Output Compare IDLE State */
tmpcr2 &= ~TIM_CR2_OIS4;
/* Set the Output Idle state */
tmpcr2 |= (OC_Config->OCIdleState << 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 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)
{
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)
{
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:
{
/* Check the parameter */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
break;
}
default:
break;
}
return HAL_OK;
}
/**
* @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
* @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
* @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; /* Legacy weak PeriodElapsedCallback */
htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; /* Legacy weak PeriodElapsedHalfCpltCallback */
htim->TriggerCallback = HAL_TIM_TriggerCallback; /* Legacy weak TriggerCallback */
htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; /* Legacy weak TriggerHalfCpltCallback */
htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; /* Legacy weak IC_CaptureCallback */
htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; /* Legacy weak IC_CaptureHalfCpltCallback */
htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; /* Legacy weak OC_DelayElapsedCallback */
htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; /* Legacy weak PWM_PulseFinishedCallback */
htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; /* Legacy weak PWM_PulseFinishedHalfCpltCallback */
htim->ErrorCallback = HAL_TIM_ErrorCallback; /* Legacy weak ErrorCallback */
htim->CommutationCallback = HAL_TIMEx_CommutCallback; /* Legacy weak CommutationCallback */
htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; /* Legacy weak CommutationHalfCpltCallback */
htim->BreakCallback = HAL_TIMEx_BreakCallback; /* Legacy weak BreakCallback */
}
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
/**
* @}
*/
#endif /* HAL_TIM_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim_ex.c | /**
******************************************************************************
* @file stm32f4xx_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
* + Timer remapping capabilities configuration
@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
##### 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).
(#) Activate the TIM peripheral using one of the start functions:
(++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), HAL_TIMEx_OC_Start_IT()
(++) Complementary PWM generation : HAL_TIMEx_PWMN_Start(), HAL_TIMEx_PWMN_Start_DMA(), HAL_TIMEx_PWMN_Start_IT()
(++) Complementary One-pulse mode output : HAL_TIMEx_OnePulseN_Start(), HAL_TIMEx_OnePulseN_Start_IT()
(++) Hall Sensor output : HAL_TIMEx_HallSensor_Start(), HAL_TIMEx_HallSensor_Start_DMA(), HAL_TIMEx_HallSensor_Start_IT().
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup TIMEx TIMEx
* @brief TIM Extended HAL module driver
* @{
*/
#ifdef HAL_TIM_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState);
/* 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.
* @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 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 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;
/* Check the parameters */
assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* 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;
/* Check the parameters */
assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* 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;
/* Check the parameters */
assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if (((uint32_t)pData == 0U) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
/* 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 stream 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 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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);
/* 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
* @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));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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
* @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);
/* 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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Enable the TIM Output Compare interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Enable the TIM Output Compare interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Enable the TIM Output Compare interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
break;
}
default:
break;
}
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Output Compare signal generation in interrupt mode
* on the complementary output.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
{
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;
}
default:
break;
}
/* 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)) == (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);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM Output Compare signal generation in DMA mode
* on the complementary output.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if (((uint32_t)pData == 0U) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK)
{
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_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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK)
{
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_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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Output Compare DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
break;
}
default:
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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM Output Compare signal generation in DMA mode
* on the complementary output.
* @param htim TIM Output Compare handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Output Compare DMA request */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
(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;
}
default:
break;
}
/* 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);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @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
* @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));
/* 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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__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
* @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);
/* 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
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
break;
}
case TIM_CHANNEL_2:
{
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
break;
}
case TIM_CHANNEL_3:
{
/* Enable the TIM Capture/Compare 3 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
break;
}
default:
break;
}
/* Enable the TIM Break interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK);
/* Enable the complementary PWM output */
TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE);
/* Enable the Main Output */
__HAL_TIM_MOE_ENABLE(htim);
/* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the PWM signal generation in interrupt mode on the
* complementary output.
* @param htim TIM handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
{
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;
}
default:
break;
}
/* 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)) == (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);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM PWM signal generation in DMA mode on the
* complementary output
* @param htim TIM handle
* @param Channel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @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)
{
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
if (htim->State == HAL_TIM_STATE_BUSY)
{
return HAL_BUSY;
}
else if (htim->State == HAL_TIM_STATE_READY)
{
if (((uint32_t)pData == 0U) && (Length > 0U))
{
return HAL_ERROR;
}
else
{
htim->State = HAL_TIM_STATE_BUSY;
}
}
else
{
/* nothing to do */
}
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length) != HAL_OK)
{
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 stream */
if (HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length) != HAL_OK)
{
return HAL_ERROR;
}
/* Enable the TIM Capture/Compare 3 DMA request */
__HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
break;
}
default:
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 */
tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
{
__HAL_TIM_ENABLE(htim);
}
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM PWM signal generation in DMA mode on the complementary
* output
* @param htim TIM handle
* @param Channel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @arg TIM_CHANNEL_3: TIM Channel 3 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
switch (Channel)
{
case TIM_CHANNEL_1:
{
/* Disable the TIM Capture/Compare 1 DMA request */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
(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;
}
default:
break;
}
/* 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);
/* Change the htim state */
htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @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.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
/* Enable the complementary One Pulse output */
TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE);
/* Enable the Main Output */
__HAL_TIM_MOE_ENABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the TIM One Pulse signal generation on the complementary
* output.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
/* Disable the complementary One Pulse output */
TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE);
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
* @brief Starts the TIM One Pulse signal generation in interrupt mode on the
* complementary channel.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channel to be enabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
/* Enable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
/* Enable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
/* Enable the complementary One Pulse output */
TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE);
/* Enable the Main 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.
* @param htim TIM One Pulse handle
* @param OutputChannel TIM Channel to be disabled
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1 selected
* @arg TIM_CHANNEL_2: TIM Channel 2 selected
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
{
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
/* Disable the TIM Capture/Compare 1 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
/* Disable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
/* Disable the complementary One Pulse output */
TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE);
/* Disable the Main Output */
__HAL_TIM_MOE_DISABLE(htim);
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* 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.
@endverbatim
* @{
*/
/**
* @brief Configure the TIM commutation event sequence.
* @note This function is mandatory to use the commutation event in order to
* update the configuration at each commutation detection on the TRGI input of the Timer,
* the typical use of this feature is with the use of another Timer(interface Timer)
* configured in Hall sensor interface, this interface Timer will generate the
* commutation at its TRGO output (connected to Timer used in this function) each time
* the TI1 of the Interface Timer detect a commutation at its input TI1.
* @param htim TIM handle
* @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
* This parameter can be one of the following values:
* @arg TIM_TS_ITR0: Internal trigger 0 selected
* @arg TIM_TS_ITR1: Internal trigger 1 selected
* @arg TIM_TS_ITR2: Internal trigger 2 selected
* @arg TIM_TS_ITR3: Internal trigger 3 selected
* @arg TIM_TS_NONE: No trigger is needed
* @param CommutationSource the Commutation Event source
* This parameter can be one of the following values:
* @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
* @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_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_SELECTION(InputTrigger));
__HAL_LOCK(htim);
if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
{
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
}
/* Select the Capture Compare preload feature */
htim->Instance->CR2 |= TIM_CR2_CCPC;
/* Select the Commutation event source */
htim->Instance->CR2 &= ~TIM_CR2_CCUS;
htim->Instance->CR2 |= CommutationSource;
/* 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_NONE: No trigger is needed
* @param CommutationSource the Commutation Event source
* This parameter can be one of the following values:
* @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
* @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger,
uint32_t CommutationSource)
{
/* Check the parameters */
assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance));
assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
__HAL_LOCK(htim);
if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
{
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
}
/* Select the Capture Compare preload feature */
htim->Instance->CR2 |= TIM_CR2_CCPC;
/* Select the Commutation event source */
htim->Instance->CR2 &= ~TIM_CR2_CCUS;
htim->Instance->CR2 |= CommutationSource;
/* 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_NONE: No trigger is needed
* @param CommutationSource the Commutation Event source
* This parameter can be one of the following values:
* @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
* @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger,
uint32_t CommutationSource)
{
/* Check the parameters */
assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance));
assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
__HAL_LOCK(htim);
if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
(InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
{
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
}
/* Select the Capture Compare preload feature */
htim->Instance->CR2 |= TIM_CR2_CCPC;
/* Select the Commutation event source */
htim->Instance->CR2 &= ~TIM_CR2_CCUS;
htim->Instance->CR2 |= CommutationSource;
/* Enable the Commutation DMA Request */
/* Set the DMA Commutation Callback */
htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = 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;
/* 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_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);
/* Set TIMx_BDTR */
htim->Instance->BDTR = tmpbdtr;
__HAL_UNLOCK(htim);
return HAL_OK;
}
/**
* @brief Configures the TIMx Remapping input capabilities.
* @param htim TIM handle.
* @param Remap specifies the TIM remapping source.
* For TIM1, the parameter can have the following values: (**)
* @arg TIM_TIM1_TIM3_TRGO: TIM1 ITR2 is connected to TIM3 TRGO
* @arg TIM_TIM1_LPTIM: TIM1 ITR2 is connected to LPTIM1 output
*
* For TIM2, the parameter can have the following values: (**)
* @arg TIM_TIM2_TIM8_TRGO: TIM2 ITR1 is connected to TIM8 TRGO (*)
* @arg TIM_TIM2_ETH_PTP: TIM2 ITR1 is connected to PTP trigger output (*)
* @arg TIM_TIM2_USBFS_SOF: TIM2 ITR1 is connected to OTG FS SOF
* @arg TIM_TIM2_USBHS_SOF: TIM2 ITR1 is connected to OTG FS SOF
*
* For TIM5, the parameter can have the following values:
* @arg TIM_TIM5_GPIO: TIM5 TI4 is connected to GPIO
* @arg TIM_TIM5_LSI: TIM5 TI4 is connected to LSI
* @arg TIM_TIM5_LSE: TIM5 TI4 is connected to LSE
* @arg TIM_TIM5_RTC: TIM5 TI4 is connected to the RTC wakeup interrupt
* @arg TIM_TIM5_TIM3_TRGO: TIM5 ITR1 is connected to TIM3 TRGO (*)
* @arg TIM_TIM5_LPTIM: TIM5 ITR1 is connected to LPTIM1 output (*)
*
* For TIM9, the parameter can have the following values: (**)
* @arg TIM_TIM9_TIM3_TRGO: TIM9 ITR1 is connected to TIM3 TRGO
* @arg TIM_TIM9_LPTIM: TIM9 ITR1 is connected to LPTIM1 output
*
* For TIM11, the parameter can have the following values:
* @arg TIM_TIM11_GPIO: TIM11 TI1 is connected to GPIO
* @arg TIM_TIM11_HSE: TIM11 TI1 is connected to HSE_RTC clock
* @arg TIM_TIM11_SPDIFRX: TIM11 TI1 is connected to SPDIFRX_FRAME_SYNC (*)
*
* (*) 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)
{
__HAL_LOCK(htim);
/* Check parameters */
assert_param(IS_TIM_REMAP(htim->Instance, Remap));
#if defined(LPTIM_OR_TIM1_ITR2_RMP) && defined(LPTIM_OR_TIM5_ITR1_RMP) && defined(LPTIM_OR_TIM5_ITR1_RMP)
if ((Remap & LPTIM_REMAP_MASK) == LPTIM_REMAP_MASK)
{
/* Connect TIMx internal trigger to LPTIM1 output */
__HAL_RCC_LPTIM1_CLK_ENABLE();
MODIFY_REG(LPTIM1->OR,
(LPTIM_OR_TIM1_ITR2_RMP | LPTIM_OR_TIM5_ITR1_RMP | LPTIM_OR_TIM9_ITR1_RMP),
Remap & ~(LPTIM_REMAP_MASK));
}
else
{
/* Set the Timer remapping configuration */
WRITE_REG(htim->Instance->OR, Remap);
}
#else
/* Set the Timer remapping configuration */
WRITE_REG(htim->Instance->OR, Remap);
#endif /* LPTIM_OR_TIM1_ITR2_RMP && LPTIM_OR_TIM5_ITR1_RMP && LPTIM_OR_TIM5_ITR1_RMP */
__HAL_UNLOCK(htim);
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
*/
}
/**
* @}
*/
/** @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;
}
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup TIMEx_Private_Functions TIMEx 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 Enables or disables the TIM Capture Compare Channel xN.
* @param TIMx to select the TIM peripheral
* @param Channel specifies the TIM Channel
* This parameter can be one of the following values:
* @arg TIM_CHANNEL_1: TIM Channel 1
* @arg TIM_CHANNEL_2: TIM Channel 2
* @arg TIM_CHANNEL_3: TIM Channel 3
* @param ChannelNState specifies the TIM Channel CCxNE bit new state.
* This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable.
* @retval None
*/
static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState)
{
uint32_t tmp;
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 */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_uart.c | /**
******************************************************************************
* @file stm32f4xx_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
* + Peripheral State and Errors functions
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The UART HAL driver can be used as follows:
(#) Declare a UART_HandleTypeDef handle structure (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 (TX as alternate function pull-up, RX as alternate function Input).
(##) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT()
and HAL_UART_Receive_IT() APIs):
(+++) Configure the USARTx interrupt priority.
(+++) Enable the NVIC USART IRQ handle.
(##) DMA Configuration if you need to use DMA process (HAL_UART_Transmit_DMA()
and HAL_UART_Receive_DMA() APIs):
(+++) Declare a DMA handle structure for the Tx/Rx stream.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure with the required
Tx/Rx parameters.
(+++) Configure the DMA Tx/Rx stream.
(+++) Associate the initialized DMA handle to the UART DMA Tx/Rx handle.
(+++) Configure the priority and enable the NVIC for the transfer complete
interrupt on the DMA Tx/Rx stream.
(+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle
(used for last byte sending completion detection in DMA non circular mode)
(#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware
flow control and Mode(Receiver/Transmitter) in the huart Init structure.
(#) For the UART asynchronous mode, initialize the UART registers by calling
the HAL_UART_Init() API.
(#) For the UART Half duplex mode, initialize the UART registers by calling
the HAL_HalfDuplex_Init() API.
(#) For the LIN mode, initialize the UART registers by calling the HAL_LIN_Init() API.
(#) For the Multi-Processor mode, initialize the UART registers by calling
the HAL_MultiProcessor_Init() API.
[..]
(@) The specific UART interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the transmit
and receive process.
[..]
(@) These APIs (HAL_UART_Init() and HAL_HalfDuplex_Init()) configure also 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 @ref HAL_UART_RegisterCallback() to register a user callback.
Function @ref 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.
(+) 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 @ref HAL_UART_UnRegisterCallback() to reset a callback to the default
weak (surcharged) function.
@ref 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.
(+) MspInitCallback : UART MspInit.
(+) MspDeInitCallback : UART MspDeInit.
[..]
By default, after the @ref HAL_UART_Init() and when the state is HAL_UART_STATE_RESET
all callbacks are set to the corresponding weak (surcharged) functions:
examples @ref HAL_UART_TxCpltCallback(), @ref HAL_UART_RxHalfCpltCallback().
Exception done for MspInit and MspDeInit functions that are respectively
reset to the legacy weak (surcharged) functions in the @ref HAL_UART_Init()
and @ref HAL_UART_DeInit() only when these callbacks are null (not registered beforehand).
If not, MspInit or MspDeInit are not null, the @ref HAL_UART_Init() and @ref 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 @ref HAL_UART_RegisterCallback() before calling @ref HAL_UART_DeInit()
or @ref 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.
[..]
Three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Send an amount of data in blocking mode using HAL_UART_Transmit()
(+) Receive an amount of data in blocking mode using HAL_UART_Receive()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Send an amount of data in non blocking mode using HAL_UART_Transmit_IT()
(+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_TxCpltCallback
(+) Receive an amount of data in non blocking mode using HAL_UART_Receive_IT()
(+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_RxCpltCallback
(+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_UART_ErrorCallback
*** DMA mode IO operation ***
==============================
[..]
(+) Send an amount of data in non blocking mode (DMA) using HAL_UART_Transmit_DMA()
(+) At transmission end of half transfer HAL_UART_TxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_TxHalfCpltCallback
(+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_TxCpltCallback
(+) Receive an amount of data in non blocking mode (DMA) using HAL_UART_Receive_DMA()
(+) At reception end of half transfer HAL_UART_RxHalfCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_RxHalfCpltCallback
(+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_UART_RxCpltCallback
(+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_UART_ErrorCallback
(+) Pause the DMA Transfer using HAL_UART_DMAPause()
(+) Resume the DMA Transfer using HAL_UART_DMAResume()
(+) Stop the DMA Transfer using HAL_UART_DMAStop()
*** UART HAL driver macros list ***
=============================================
[..]
Below the list of most used macros in UART HAL driver.
(+) __HAL_UART_ENABLE: Enable the UART peripheral
(+) __HAL_UART_DISABLE: Disable the UART peripheral
(+) __HAL_UART_GET_FLAG : Check whether the specified UART flag is set or not
(+) __HAL_UART_CLEAR_FLAG : Clear the specified UART pending flag
(+) __HAL_UART_ENABLE_IT: Enable the specified UART interrupt
(+) __HAL_UART_DISABLE_IT: Disable the specified UART interrupt
(+) __HAL_UART_GET_IT_SOURCE: Check whether the specified UART interrupt has occurred or not
[..]
(@) You can refer to the UART HAL driver header file for more useful macros
@endverbatim
[..]
(@) Additionnal remark: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
Depending on the frame length defined by the M bit (8-bits or 9-bits),
the possible UART frame formats are as listed in the following table:
+-------------------------------------------------------------+
| M bit | PCE bit | UART frame |
|---------------------|---------------------------------------|
| 0 | 0 | | SB | 8 bit data | STB | |
|---------|-----------|---------------------------------------|
| 0 | 1 | | SB | 7 bit data | PB | STB | |
|---------|-----------|---------------------------------------|
| 1 | 0 | | SB | 9 bit data | STB | |
|---------|-----------|---------------------------------------|
| 1 | 1 | | SB | 8 bit data | PB | STB | |
+-------------------------------------------------------------+
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup UART UART
* @brief HAL UART module driver
* @{
*/
#ifdef HAL_UART_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup UART_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @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 */
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_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
static void UART_DMARxHalfCplt(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 HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout);
static void UART_SetConfig(UART_HandleTypeDef *huart);
/**
* @}
*/
/* 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 only these parameters can be configured:
(++) Baud Rate
(++) Word Length
(++) Stop Bit
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
Depending on the frame length defined by the M bit (8-bits or 9-bits),
please refer to Reference manual for possible UART frame formats.
(++) Hardware flow control
(++) Receiver/transmitter modes
(++) Over Sampling Method
[..]
The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init() and HAL_MultiProcessor_Init() APIs
follow respectively the UART asynchronous, UART Half duplex, LIN and Multi-Processor configuration
procedures (details for the procedures are available in reference manual
(RM0430 for STM32F4X3xx MCUs and RM0402 for STM32F412xx MCUs
RM0383 for STM32F411xC/E MCUs and RM0401 for STM32F410xx MCUs
RM0090 for STM32F4X5xx/STM32F4X7xx/STM32F429xx/STM32F439xx MCUs
RM0390 for STM32F446xx MCUs and RM0386 for STM32F469xx/STM32F479xx MCUs)).
@endverbatim
* @{
*/
/**
* @brief Initializes the UART mode according to the specified parameters in
* the UART_InitTypeDef and create the associated handle.
* @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_Init(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if (huart == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
if (huart->Init.HwFlowCtl != UART_HWCONTROL_NONE)
{
/* The hardware flow control is available only for USART1, USART2, USART3 and USART6.
Except for STM32F446xx devices, that is available for USART1, USART2, USART3, USART6, UART4 and UART5.
*/
assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl));
}
else
{
assert_param(IS_UART_INSTANCE(huart->Instance));
}
assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling));
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;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In asynchronous mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL and IREN bits in the USART_CR3 register.*/
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));
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state */
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the half-duplex mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if (huart == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance));
assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling));
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;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In half-duplex mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN and IREN bits in the USART_CR3 register.*/
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);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state*/
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the LIN mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param BreakDetectLength Specifies the LIN break detection length.
* This parameter can be one of the following values:
* @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection
* @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength)
{
/* Check the UART handle allocation */
if (huart == NULL)
{
return HAL_ERROR;
}
/* Check the 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));
assert_param(IS_UART_LIN_WORD_LENGTH(huart->Init.WordLength));
assert_param(IS_UART_LIN_OVERSAMPLING(huart->Init.OverSampling));
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;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In LIN mode, the following bits must be kept cleared:
- CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL 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. */
CLEAR_BIT(huart->Instance->CR2, USART_CR2_LBDL);
SET_BIT(huart->Instance->CR2, BreakDetectLength);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state*/
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the Multi-Processor mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param Address USART address
* @param WakeUpMethod specifies the USART wake-up method.
* This parameter can be one of the following values:
* @arg UART_WAKEUPMETHOD_IDLELINE: Wake-up by an idle line detection
* @arg UART_WAKEUPMETHOD_ADDRESSMARK: Wake-up by an address mark
* @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 parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Check the Address & wake up method parameters */
assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod));
assert_param(IS_UART_ADDRESS(Address));
assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling));
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;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In Multi-Processor mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL and IREN bits in the USART_CR3 register */
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));
/* Set the USART address node */
CLEAR_BIT(huart->Instance->CR2, USART_CR2_ADD);
SET_BIT(huart->Instance->CR2, Address);
/* Set the wake up method by setting the WAKE bit in the CR1 register */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_WAKE);
SET_BIT(huart->Instance->CR1, WakeUpMethod);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state */
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the UART peripheral.
* @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_DeInit(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if (huart == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
huart->gState = HAL_UART_STATE_BUSY;
/* Disable the Peripheral */
__HAL_UART_DISABLE(huart);
#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;
/* Process Unlock */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief UART MSP Init.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
/**
* @brief UART MSP DeInit.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could 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_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)
{
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
/* Process locked */
__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_MSPINIT_CB_ID :
huart->MspInitCallback = pCallback;
break;
case HAL_UART_MSPDEINIT_CB_ID :
huart->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
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 :
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
/* Release Lock */
__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_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;
/* Process locked */
__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_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 :
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
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 :
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK;
/* Return error status */
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 and Receive functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
This subsection provides a set of functions allowing to manage the UART asynchronous
and Half duplex data transfers.
(#) There are two modes of transfer:
(+) Blocking mode: The communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(+) Non-Blocking mode: The communication is performed using Interrupts
or DMA, these 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()
(#) 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 Sends 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.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART 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 Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t *tmp;
uint32_t tickstart = 0U;
/* Check that a Tx process is not already ongoing */
if (huart->gState == HAL_UART_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_BUSY_TX;
/* Init tickstart for timeout managment */
tickstart = HAL_GetTick();
huart->TxXferSize = Size;
huart->TxXferCount = Size;
/* Process Unlocked */
__HAL_UNLOCK(huart);
while (huart->TxXferCount > 0U)
{
huart->TxXferCount--;
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t *) pData;
huart->Instance->DR = (*tmp & (uint16_t)0x01FF);
if (huart->Init.Parity == UART_PARITY_NONE)
{
pData += 2U;
}
else
{
pData += 1U;
}
}
else
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
huart->Instance->DR = (*pData++ & (uint8_t)0xFF);
}
}
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 Receives 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.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART 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 Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t *tmp;
uint32_t tickstart = 0U;
/* Check that a Rx process is not already ongoing */
if (huart->RxState == HAL_UART_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->RxState = HAL_UART_STATE_BUSY_RX;
/* Init tickstart for timeout managment */
tickstart = HAL_GetTick();
huart->RxXferSize = Size;
huart->RxXferCount = Size;
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Check the remain data to be received */
while (huart->RxXferCount > 0U)
{
huart->RxXferCount--;
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t *) pData;
if (huart->Init.Parity == UART_PARITY_NONE)
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
pData += 2U;
}
else
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
pData += 1U;
}
}
else
{
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (huart->Init.Parity == UART_PARITY_NONE)
{
*pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
}
else
{
*pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
}
}
}
/* At end of Rx process, restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in non 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.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART 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_UART_Transmit_IT(UART_HandleTypeDef *huart, 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;
}
/* Process Locked */
__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;
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Transmit data register empty Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_TXE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data in non 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.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART 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_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;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->RxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->RxState = HAL_UART_STATE_BUSY_RX;
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Parity Error Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_PE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
/* Enable the UART Data Register not empty Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in 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 Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART 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_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
/* Check that a Tx process is not already ongoing */
if (huart->gState == HAL_UART_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__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;
/* 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 stream */
tmp = (uint32_t *)&pData;
HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t *)tmp, (uint32_t)&huart->Instance->DR, Size);
/* Clear the TC flag in the SR register by writing 0 to it */
__HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
SET_BIT(huart->Instance->CR3, USART_CR3_DMAT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives 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 indicate the number
* of u16 available through pData.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData Pointer to data buffer (u8 or u16 data elements).
* @param Size Amount of data elements (u8 or u16) to be received.
* @note When the UART parity is enabled (PCE = 1) the received data contains the parity bit.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
/* Check that a Rx process is not already ongoing */
if (huart->RxState == HAL_UART_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->RxState = HAL_UART_STATE_BUSY_RX;
/* Set the UART DMA transfer complete callback */
huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt;
/* Set the UART DMA Half transfer complete callback */
huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt;
/* Set the DMA error callback */
huart->hdmarx->XferErrorCallback = UART_DMAError;
/* Set the DMA abort callback */
huart->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA stream */
tmp = (uint32_t *)&pData;
HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->DR, *(uint32_t *)tmp, Size);
/* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */
__HAL_UART_CLEAR_OREFLAG(huart);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Parity Error Interrupt */
SET_BIT(huart->Instance->CR1, USART_CR1_PEIE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
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 */
SET_BIT(huart->Instance->CR3, USART_CR3_DMAR);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pauses the DMA Transfer.
* @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_DMAPause(UART_HandleTypeDef *huart)
{
uint32_t dmarequest = 0x00U;
/* Process Locked */
__HAL_LOCK(huart);
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT);
if ((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest)
{
/* Disable the UART DMA Tx request */
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
}
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR);
if ((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Disable the UART DMA Rx request */
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Resumes the DMA Transfer.
* @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_DMAResume(UART_HandleTypeDef *huart)
{
/* Process Locked */
__HAL_LOCK(huart);
if (huart->gState == HAL_UART_STATE_BUSY_TX)
{
/* Enable the UART DMA Tx request */
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_OREFLAG(huart);
/* Reenable PE and ERR (Frame error, noise error, overrun error) interrupts */
SET_BIT(huart->Instance->CR1, USART_CR1_PEIE);
SET_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Enable the UART DMA Rx request */
SET_BIT(huart->Instance->CR3, USART_CR3_DMAR);
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Stops the DMA Transfer.
* @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_DMAStop(UART_HandleTypeDef *huart)
{
uint32_t dmarequest = 0x00U;
/* 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():
when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback()
*/
/* Stop UART DMA Tx request if ongoing */
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT);
if ((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest)
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Abort the UART DMA Tx stream */
if (huart->hdmatx != NULL)
{
HAL_DMA_Abort(huart->hdmatx);
}
UART_EndTxTransfer(huart);
}
/* Stop UART DMA Rx request if ongoing */
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR);
if ((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest)
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream */
if (huart->hdmarx != NULL)
{
HAL_DMA_Abort(huart->hdmarx);
}
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 TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Abort the UART DMA Tx stream: 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;
}
}
}
}
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream: 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 = 0x00U;
huart->RxXferCount = 0x00U;
/* Reset ErrorCode */
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Restore huart->RxState and huart->gState to Ready */
huart->RxState = HAL_UART_STATE_READY;
huart->gState = HAL_UART_STATE_READY;
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 TXEIE and TCIE interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Abort the UART DMA Tx stream : 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 = 0x00U;
/* 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 RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream : 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 = 0x00U;
/* Restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
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 = 0x01U;
/* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* 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;
}
}
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
/* Disable DMA Tx at UART level */
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Abort the UART DMA Tx stream : 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 = 0x00U;
}
}
}
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream : 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 = 0x01U;
}
else
{
AbortCplt = 0x00U;
}
}
}
/* if no DMA abort complete callback execution is required => call user Abort Complete callback */
if (AbortCplt == 0x01U)
{
/* Reset Tx and Rx transfer counters */
huart->TxXferCount = 0x00U;
huart->RxXferCount = 0x00U;
/* Reset ErrorCode */
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Restore huart->gState and huart->RxState to Ready */
huart->gState = HAL_UART_STATE_READY;
huart->RxState = 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 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 TXEIE and TCIE interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* Disable the UART DMA Tx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Abort the UART DMA Tx stream : use blocking DMA Abort API (no 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 = 0x00U;
/* 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 = 0x00U;
/* 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 */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream : use blocking DMA Abort API (no 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 = 0x00U;
/* Restore huart->RxState to Ready */
huart->RxState = 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 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 = 0x00U;
/* Restore huart->RxState to Ready */
huart->RxState = 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 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 This function handles UART interrupt request.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
uint32_t isrflags = READ_REG(huart->Instance->SR);
uint32_t cr1its = READ_REG(huart->Instance->CR1);
uint32_t cr3its = READ_REG(huart->Instance->CR3);
uint32_t errorflags = 0x00U;
uint32_t dmarequest = 0x00U;
/* If no error occurs */
errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE));
if (errorflags == RESET)
{
/* UART in mode Receiver -------------------------------------------------*/
if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
UART_Receive_IT(huart);
return;
}
}
/* If some errors occur */
if ((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET)))
{
/* UART parity error interrupt occurred ----------------------------------*/
if (((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET))
{
huart->ErrorCode |= HAL_UART_ERROR_PE;
}
/* UART noise error interrupt occurred -----------------------------------*/
if (((isrflags & USART_SR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
huart->ErrorCode |= HAL_UART_ERROR_NE;
}
/* UART frame error interrupt occurred -----------------------------------*/
if (((isrflags & USART_SR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
huart->ErrorCode |= HAL_UART_ERROR_FE;
}
/* UART Over-Run interrupt occurred --------------------------------------*/
if (((isrflags & USART_SR_ORE) != RESET) && (((cr1its & USART_CR1_RXNEIE) != RESET) || ((cr3its & USART_CR3_EIE) != RESET)))
{
huart->ErrorCode |= HAL_UART_ERROR_ORE;
}
/* Call UART Error Call back function if need be --------------------------*/
if (huart->ErrorCode != HAL_UART_ERROR_NONE)
{
/* UART in mode Receiver -----------------------------------------------*/
if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
UART_Receive_IT(huart);
}
/* If Overrun error occurs, or if any error occurs in DMA mode reception,
consider error as blocking */
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR);
if (((huart->ErrorCode & HAL_UART_ERROR_ORE) != RESET) || dmarequest)
{
/* 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);
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx stream */
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;
if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK)
{
/* Call Directly 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 */
/* UART in mode Transmitter ------------------------------------------------*/
if (((isrflags & USART_SR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET))
{
UART_Transmit_IT(huart);
return;
}
/* UART in mode Transmitter end --------------------------------------------*/
if (((isrflags & USART_SR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET))
{
UART_EndTransmit_IT(huart);
return;
}
}
/**
* @brief Tx Transfer completed callbacks.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
/**
* @brief Tx Half Transfer completed callbacks.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
/**
* @brief Rx Half Transfer completed callbacks.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
/**
* @brief UART error callbacks.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could 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.
*/
}
/**
* @}
*/
/** @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_LIN_SendBreak() API can be helpful to transmit the break character.
(+) HAL_MultiProcessor_EnterMuteMode() API can be helpful to enter the UART in mute mode.
(+) HAL_MultiProcessor_ExitMuteMode() API can be helpful to exit the UART mute mode by software.
(+) HAL_HalfDuplex_EnableTransmitter() API to enable the UART transmitter and disables the UART receiver in Half Duplex mode
(+) HAL_HalfDuplex_EnableReceiver() API to enable the UART receiver and disables the UART transmitter in Half Duplex mode
@endverbatim
* @{
*/
/**
* @brief Transmits break characters.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/* Send break characters */
SET_BIT(huart->Instance->CR1, USART_CR1_SBK);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enters the UART in mute mode.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/* Enable the USART mute mode by setting the RWU bit in the CR1 register */
SET_BIT(huart->Instance->CR1, USART_CR1_RWU);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Exits the UART mute mode: wake up software.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/* Disable the USART mute mode by clearing the RWU bit in the CR1 register */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_RWU);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enables the UART transmitter and disables the UART receiver.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00U;
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/*-------------------------- USART CR1 Configuration -----------------------*/
tmpreg = huart->Instance->CR1;
/* Clear TE and RE bits */
tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
/* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */
tmpreg |= (uint32_t)USART_CR1_TE;
/* Write to USART CR1 */
WRITE_REG(huart->Instance->CR1, (uint32_t)tmpreg);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enables the UART receiver and disables the UART transmitter.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00U;
/* Process Locked */
__HAL_LOCK(huart);
huart->gState = HAL_UART_STATE_BUSY;
/*-------------------------- USART CR1 Configuration -----------------------*/
tmpreg = huart->Instance->CR1;
/* Clear TE and RE bits */
tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
/* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */
tmpreg |= (uint32_t)USART_CR1_RE;
/* Write to USART CR1 */
WRITE_REG(huart->Instance->CR1, (uint32_t)tmpreg);
huart->gState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup UART_Exported_Functions_Group4 Peripheral State and Errors functions
* @brief UART State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Errors functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to return the State of
UART communication process, return Peripheral Errors occurred during communication
process
(+) HAL_UART_GetState() API can be helpful to check in run-time the state of the UART peripheral.
(+) HAL_UART_GetError() check in run-time errors that could be occurred during communication.
@endverbatim
* @{
*/
/**
* @brief Returns the UART state.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL state
*/
HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart)
{
uint32_t temp1 = 0x00U, temp2 = 0x00U;
temp1 = huart->gState;
temp2 = huart->RxState;
return (HAL_UART_StateTypeDef)(temp1 | temp2);
}
/**
* @brief Return the UART error code
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART.
* @retval UART Error Code
*/
uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart)
{
return huart->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @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 */
}
#endif /* USE_HAL_UART_REGISTER_CALLBACKS */
/**
* @brief DMA UART 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 UART_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* DMA Normal mode*/
if ((hdma->Instance->CR & DMA_SxCR_CIRC) == 0U)
{
huart->TxXferCount = 0x00U;
/* Disable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Enable the UART Transmit Complete Interrupt */
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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#if (USE_HAL_UART_REGISTER_CALLBACKS == 1)
/*Call registered Tx complete callback*/
huart->TxHalfCpltCallback(huart);
#else
/*Call legacy weak Tx complete callback*/
HAL_UART_TxHalfCpltCallback(huart);
#endif /* USE_HAL_UART_REGISTER_CALLBACKS */
}
/**
* @brief DMA UART 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 UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* DMA Normal mode*/
if ((hdma->Instance->CR & DMA_SxCR_CIRC) == 0U)
{
huart->RxXferCount = 0U;
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* Disable the DMA transfer for the receiver request by setting the DMAR bit
in the UART CR3 register */
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 (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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
#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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMAError(DMA_HandleTypeDef *hdma)
{
uint32_t dmarequest = 0x00U;
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Stop UART DMA Tx request if ongoing */
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT);
if ((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest)
{
huart->TxXferCount = 0x00U;
UART_EndTxTransfer(huart);
}
/* Stop UART DMA Rx request if ongoing */
dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR);
if ((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest)
{
huart->RxXferCount = 0x00U;
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 This function handles UART Communication Timeout.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param Flag specifies the UART flag to check.
* @param Status The new Flag status (SET or RESET).
* @param Tickstart Tick start value
* @param Timeout Timeout duration
* @retval HAL status
*/
static 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 ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_TIMEOUT;
}
}
}
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 and TCIE interrupts */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* 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 */
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
/* At end of Rx process, restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
}
/**
* @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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
huart->RxXferCount = 0x00U;
huart->TxXferCount = 0x00U;
#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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_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 = 0x00U;
huart->RxXferCount = 0x00U;
/* Reset ErrorCode */
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Restore huart->gState and huart->RxState to Ready */
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
/* 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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_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 = 0x00U;
huart->RxXferCount = 0x00U;
/* Reset ErrorCode */
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Restore huart->gState and huart->RxState to Ready */
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
/* 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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
huart->TxXferCount = 0x00U;
/* 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 Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
huart->RxXferCount = 0x00U;
/* Restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
/* 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 Sends an amount of data in non blocking mode.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart)
{
uint16_t *tmp;
/* Check that a Tx process is ongoing */
if (huart->gState == HAL_UART_STATE_BUSY_TX)
{
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
tmp = (uint16_t *) huart->pTxBuffPtr;
huart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
if (huart->Init.Parity == UART_PARITY_NONE)
{
huart->pTxBuffPtr += 2U;
}
else
{
huart->pTxBuffPtr += 1U;
}
}
else
{
huart->Instance->DR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0x00FF);
}
if (--huart->TxXferCount == 0U)
{
/* Disable the UART Transmit Complete Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
/* Enable the UART Transmit Complete Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_TC);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Wraps 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 HAL status
*/
static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart)
{
/* Disable the UART Transmit Complete Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_TC);
/* Tx process is ended, restore huart->gState to Ready */
huart->gState = HAL_UART_STATE_READY;
#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 */
return HAL_OK;
}
/**
* @brief Receives an amount of data in non blocking mode
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart)
{
uint16_t *tmp;
/* Check that a Rx process is ongoing */
if (huart->RxState == HAL_UART_STATE_BUSY_RX)
{
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
tmp = (uint16_t *) huart->pRxBuffPtr;
if (huart->Init.Parity == UART_PARITY_NONE)
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
huart->pRxBuffPtr += 2U;
}
else
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
huart->pRxBuffPtr += 1U;
}
}
else
{
if (huart->Init.Parity == UART_PARITY_NONE)
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
}
else
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
}
}
if (--huart->RxXferCount == 0U)
{
/* Disable the UART Data Register not empty Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
/* Disable the UART Parity Error Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
/* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
/* Rx process is completed, restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
#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 */
return HAL_OK;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Configures the UART peripheral.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
static void UART_SetConfig(UART_HandleTypeDef *huart)
{
uint32_t tmpreg;
uint32_t pclk;
/* Check the parameters */
assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate));
assert_param(IS_UART_STOPBITS(huart->Init.StopBits));
assert_param(IS_UART_PARITY(huart->Init.Parity));
assert_param(IS_UART_MODE(huart->Init.Mode));
/*-------------------------- 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 CR1 Configuration -----------------------*/
/* Configure the UART Word Length, Parity and mode:
Set the M bits according to huart->Init.WordLength value
Set PCE and PS bits according to huart->Init.Parity value
Set TE and RE bits according to huart->Init.Mode value
Set OVER8 bit according to huart->Init.OverSampling value */
tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling;
MODIFY_REG(huart->Instance->CR1,
(uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
tmpreg);
/*-------------------------- USART CR3 Configuration -----------------------*/
/* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */
MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE), huart->Init.HwFlowCtl);
/* Check the Over Sampling */
if (huart->Init.OverSampling == UART_OVERSAMPLING_8)
{
/*-------------------------- USART BRR Configuration ---------------------*/
#if defined(USART6) && defined(UART9) && defined(UART10)
if ((huart->Instance == USART1) || (huart->Instance == USART6) || (huart->Instance == UART9) || (huart->Instance == UART10))
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING8(pclk, huart->Init.BaudRate);
}
#elif defined(USART6)
if ((huart->Instance == USART1) || (huart->Instance == USART6))
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING8(pclk, huart->Init.BaudRate);
}
#else
if (huart->Instance == USART1)
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING8(pclk, huart->Init.BaudRate);
}
#endif /* USART6 */
else
{
pclk = HAL_RCC_GetPCLK1Freq();
huart->Instance->BRR = UART_BRR_SAMPLING8(pclk, huart->Init.BaudRate);
}
}
else
{
/*-------------------------- USART BRR Configuration ---------------------*/
#if defined(USART6) && defined(UART9) && defined(UART10)
if ((huart->Instance == USART1) || (huart->Instance == USART6) || (huart->Instance == UART9) || (huart->Instance == UART10))
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING16(pclk, huart->Init.BaudRate);
}
#elif defined(USART6)
if ((huart->Instance == USART1) || (huart->Instance == USART6))
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING16(pclk, huart->Init.BaudRate);
}
#else
if (huart->Instance == USART1)
{
pclk = HAL_RCC_GetPCLK2Freq();
huart->Instance->BRR = UART_BRR_SAMPLING16(pclk, huart->Init.BaudRate);
}
#endif /* USART6 */
else
{
pclk = HAL_RCC_GetPCLK1Freq();
huart->Instance->BRR = UART_BRR_SAMPLING16(pclk, huart->Init.BaudRate);
}
}
}
/**
* @}
*/
#endif /* HAL_UART_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Inc\arm_math.h | /* ----------------------------------------------------------------------
* Copyright (C) 2010-2015 ARM Limited. All rights reserved.
*
* $Date: 20. October 2015
* $Revision: V1.4.5 b
*
* Project: CMSIS DSP Library
* Title: arm_math.h
*
* Description: Public header file for CMSIS DSP Library
*
* Target Processor: Cortex-M7/Cortex-M4/Cortex-M3/Cortex-M0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER 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.
* -------------------------------------------------------------------- */
/**
\mainpage CMSIS DSP Software Library
*
* Introduction
* ------------
*
* This user manual describes the CMSIS DSP software library,
* a suite of common signal processing functions for use on Cortex-M processor based devices.
*
* The library is divided into a number of functions each covering a specific category:
* - Basic math functions
* - Fast math functions
* - Complex math functions
* - Filters
* - Matrix functions
* - Transforms
* - Motor control functions
* - Statistical functions
* - Support functions
* - Interpolation functions
*
* The library has separate functions for operating on 8-bit integers, 16-bit integers,
* 32-bit integer and 32-bit floating-point values.
*
* Using the Library
* ------------
*
* The library installer contains prebuilt versions of the libraries in the <code>Lib</code> folder.
* - arm_cortexM7lfdp_math.lib (Little endian and Double Precision Floating Point Unit on Cortex-M7)
* - arm_cortexM7bfdp_math.lib (Big endian and Double Precision Floating Point Unit on Cortex-M7)
* - arm_cortexM7lfsp_math.lib (Little endian and Single Precision Floating Point Unit on Cortex-M7)
* - arm_cortexM7bfsp_math.lib (Big endian and Single Precision Floating Point Unit on Cortex-M7)
* - arm_cortexM7l_math.lib (Little endian on Cortex-M7)
* - arm_cortexM7b_math.lib (Big endian on Cortex-M7)
* - arm_cortexM4lf_math.lib (Little endian and Floating Point Unit on Cortex-M4)
* - arm_cortexM4bf_math.lib (Big endian and Floating Point Unit on Cortex-M4)
* - arm_cortexM4l_math.lib (Little endian on Cortex-M4)
* - arm_cortexM4b_math.lib (Big endian on Cortex-M4)
* - arm_cortexM3l_math.lib (Little endian on Cortex-M3)
* - arm_cortexM3b_math.lib (Big endian on Cortex-M3)
* - arm_cortexM0l_math.lib (Little endian on Cortex-M0 / CortexM0+)
* - arm_cortexM0b_math.lib (Big endian on Cortex-M0 / CortexM0+)
*
* The library functions are declared in the public file <code>arm_math.h</code> which is placed in the <code>Include</code> folder.
* Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single
* public header file <code> arm_math.h</code> for Cortex-M7/M4/M3/M0/M0+ with little endian and big endian. Same header file will be used for floating point unit(FPU) variants.
* Define the appropriate pre processor MACRO ARM_MATH_CM7 or ARM_MATH_CM4 or ARM_MATH_CM3 or
* ARM_MATH_CM0 or ARM_MATH_CM0PLUS depending on the target processor in the application.
*
* Examples
* --------
*
* The library ships with a number of examples which demonstrate how to use the library functions.
*
* Toolchain Support
* ------------
*
* The library has been developed and tested with MDK-ARM version 5.14.0.0
* The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly.
*
* Building the Library
* ------------
*
* The library installer contains a project file to re build libraries on MDK-ARM Tool chain in the <code>CMSIS\\DSP_Lib\\Source\\ARM</code> folder.
* - arm_cortexM_math.uvprojx
*
*
* The libraries can be built by opening the arm_cortexM_math.uvprojx project in MDK-ARM, selecting a specific target, and defining the optional pre processor MACROs detailed above.
*
* Pre-processor Macros
* ------------
*
* Each library project have differant pre-processor macros.
*
* - UNALIGNED_SUPPORT_DISABLE:
*
* Define macro UNALIGNED_SUPPORT_DISABLE, If the silicon does not support unaligned memory access
*
* - ARM_MATH_BIG_ENDIAN:
*
* Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets.
*
* - ARM_MATH_MATRIX_CHECK:
*
* Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices
*
* - ARM_MATH_ROUNDING:
*
* Define macro ARM_MATH_ROUNDING for rounding on support functions
*
* - ARM_MATH_CMx:
*
* Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target
* and ARM_MATH_CM0 for building library on Cortex-M0 target, ARM_MATH_CM0PLUS for building library on Cortex-M0+ target, and
* ARM_MATH_CM7 for building the library on cortex-M7.
*
* - __FPU_PRESENT:
*
* Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for M4bf and M4lf libraries
*
* <hr>
* CMSIS-DSP in ARM::CMSIS Pack
* -----------------------------
*
* The following files relevant to CMSIS-DSP are present in the <b>ARM::CMSIS</b> Pack directories:
* |File/Folder |Content |
* |------------------------------|------------------------------------------------------------------------|
* |\b CMSIS\\Documentation\\DSP | This documentation |
* |\b CMSIS\\DSP_Lib | Software license agreement (license.txt) |
* |\b CMSIS\\DSP_Lib\\Examples | Example projects demonstrating the usage of the library functions |
* |\b CMSIS\\DSP_Lib\\Source | Source files for rebuilding the library |
*
* <hr>
* Revision History of CMSIS-DSP
* ------------
* Please refer to \ref ChangeLog_pg.
*
* Copyright Notice
* ------------
*
* Copyright (C) 2010-2015 ARM Limited. All rights reserved.
*/
/**
* @defgroup groupMath Basic Math Functions
*/
/**
* @defgroup groupFastMath Fast Math Functions
* This set of functions provides a fast approximation to sine, cosine, and square root.
* As compared to most of the other functions in the CMSIS math library, the fast math functions
* operate on individual values and not arrays.
* There are separate functions for Q15, Q31, and floating-point data.
*
*/
/**
* @defgroup groupCmplxMath Complex Math Functions
* This set of functions operates on complex data vectors.
* The data in the complex arrays is stored in an interleaved fashion
* (real, imag, real, imag, ...).
* In the API functions, the number of samples in a complex array refers
* to the number of complex values; the array contains twice this number of
* real values.
*/
/**
* @defgroup groupFilters Filtering Functions
*/
/**
* @defgroup groupMatrix Matrix Functions
*
* This set of functions provides basic matrix math operations.
* The functions operate on matrix data structures. For example,
* the type
* definition for the floating-point matrix structure is shown
* below:
* <pre>
* typedef struct
* {
* uint16_t numRows; // number of rows of the matrix.
* uint16_t numCols; // number of columns of the matrix.
* float32_t *pData; // points to the data of the matrix.
* } arm_matrix_instance_f32;
* </pre>
* There are similar definitions for Q15 and Q31 data types.
*
* The structure specifies the size of the matrix and then points to
* an array of data. The array is of size <code>numRows X numCols</code>
* and the values are arranged in row order. That is, the
* matrix element (i, j) is stored at:
* <pre>
* pData[i*numCols + j]
* </pre>
*
* \par Init Functions
* There is an associated initialization function for each type of matrix
* data structure.
* The initialization function sets the values of the internal structure fields.
* Refer to the function <code>arm_mat_init_f32()</code>, <code>arm_mat_init_q31()</code>
* and <code>arm_mat_init_q15()</code> for floating-point, Q31 and Q15 types, respectively.
*
* \par
* Use of the initialization function is optional. However, if initialization function is used
* then the instance structure cannot be placed into a const data section.
* To place the instance structure in a const data
* section, manually initialize the data structure. For example:
* <pre>
* <code>arm_matrix_instance_f32 S = {nRows, nColumns, pData};</code>
* <code>arm_matrix_instance_q31 S = {nRows, nColumns, pData};</code>
* <code>arm_matrix_instance_q15 S = {nRows, nColumns, pData};</code>
* </pre>
* where <code>nRows</code> specifies the number of rows, <code>nColumns</code>
* specifies the number of columns, and <code>pData</code> points to the
* data array.
*
* \par Size Checking
* By default all of the matrix functions perform size checking on the input and
* output matrices. For example, the matrix addition function verifies that the
* two input matrices and the output matrix all have the same number of rows and
* columns. If the size check fails the functions return:
* <pre>
* ARM_MATH_SIZE_MISMATCH
* </pre>
* Otherwise the functions return
* <pre>
* ARM_MATH_SUCCESS
* </pre>
* There is some overhead associated with this matrix size checking.
* The matrix size checking is enabled via the \#define
* <pre>
* ARM_MATH_MATRIX_CHECK
* </pre>
* within the library project settings. By default this macro is defined
* and size checking is enabled. By changing the project settings and
* undefining this macro size checking is eliminated and the functions
* run a bit faster. With size checking disabled the functions always
* return <code>ARM_MATH_SUCCESS</code>.
*/
/**
* @defgroup groupTransforms Transform Functions
*/
/**
* @defgroup groupController Controller Functions
*/
/**
* @defgroup groupStats Statistics Functions
*/
/**
* @defgroup groupSupport Support Functions
*/
/**
* @defgroup groupInterpolation Interpolation Functions
* These functions perform 1- and 2-dimensional interpolation of data.
* Linear interpolation is used for 1-dimensional data and
* bilinear interpolation is used for 2-dimensional data.
*/
/**
* @defgroup groupExamples Examples
*/
#ifndef _ARM_MATH_H
#define _ARM_MATH_H
/* ignore some GCC warnings */
#if defined ( __GNUC__ )
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#define __CMSIS_GENERIC /* disable NVIC and Systick functions */
#if defined(ARM_MATH_CM7)
#include "core_cm7.h"
#elif defined (ARM_MATH_CM4)
#include "core_cm4.h"
#elif defined (ARM_MATH_CM3)
#include "core_cm3.h"
#elif defined (ARM_MATH_CM0)
#include "core_cm0.h"
#define ARM_MATH_CM0_FAMILY
#elif defined (ARM_MATH_CM0PLUS)
#include "core_cm0plus.h"
#define ARM_MATH_CM0_FAMILY
#else
#error "Define according the used Cortex core ARM_MATH_CM7, ARM_MATH_CM4, ARM_MATH_CM3, ARM_MATH_CM0PLUS or ARM_MATH_CM0"
#endif
#undef __CMSIS_GENERIC /* enable NVIC and Systick functions */
#include "string.h"
#include "math.h"
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Macros required for reciprocal calculation in Normalized LMS
*/
#define DELTA_Q31 (0x100)
#define DELTA_Q15 0x5
#define INDEX_MASK 0x0000003F
#ifndef PI
#define PI 3.14159265358979f
#endif
/**
* @brief Macros required for SINE and COSINE Fast math approximations
*/
#define FAST_MATH_TABLE_SIZE 512
#define FAST_MATH_Q31_SHIFT (32 - 10)
#define FAST_MATH_Q15_SHIFT (16 - 10)
#define CONTROLLER_Q31_SHIFT (32 - 9)
#define TABLE_SIZE 256
#define TABLE_SPACING_Q31 0x400000
#define TABLE_SPACING_Q15 0x80
/**
* @brief Macros required for SINE and COSINE Controller functions
*/
/* 1.31(q31) Fixed value of 2/360 */
/* -1 to +1 is divided into 360 values so total spacing is (2/360) */
#define INPUT_SPACING 0xB60B61
/**
* @brief Macro for Unaligned Support
*/
#ifndef UNALIGNED_SUPPORT_DISABLE
#define ALIGN4
#else
#if defined (__GNUC__)
#define ALIGN4 __attribute__((aligned(4)))
#else
#define ALIGN4 __align(4)
#endif
#endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */
/**
* @brief Error status returned by some functions in the library.
*/
typedef enum
{
ARM_MATH_SUCCESS = 0, /**< No error */
ARM_MATH_ARGUMENT_ERROR = -1, /**< One or more arguments are incorrect */
ARM_MATH_LENGTH_ERROR = -2, /**< Length of data buffer is incorrect */
ARM_MATH_SIZE_MISMATCH = -3, /**< Size of matrices is not compatible with the operation. */
ARM_MATH_NANINF = -4, /**< Not-a-number (NaN) or infinity is generated */
ARM_MATH_SINGULAR = -5, /**< Generated by matrix inversion if the input matrix is singular and cannot be inverted. */
ARM_MATH_TEST_FAILURE = -6 /**< Test Failed */
} arm_status;
/**
* @brief 8-bit fractional data type in 1.7 format.
*/
typedef int8_t q7_t;
/**
* @brief 16-bit fractional data type in 1.15 format.
*/
typedef int16_t q15_t;
/**
* @brief 32-bit fractional data type in 1.31 format.
*/
typedef int32_t q31_t;
/**
* @brief 64-bit fractional data type in 1.63 format.
*/
typedef int64_t q63_t;
/**
* @brief 32-bit floating-point type definition.
*/
typedef float float32_t;
/**
* @brief 64-bit floating-point type definition.
*/
typedef double float64_t;
/**
* @brief definition to read/write two 16 bit values.
*/
#if defined __CC_ARM
#define __SIMD32_TYPE int32_t __packed
#define CMSIS_UNUSED __attribute__((unused))
#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define __SIMD32_TYPE int32_t
#define CMSIS_UNUSED __attribute__((unused))
#elif defined __GNUC__
#define __SIMD32_TYPE int32_t
#define CMSIS_UNUSED __attribute__((unused))
#elif defined __ICCARM__
#define __SIMD32_TYPE int32_t __packed
#define CMSIS_UNUSED
#elif defined __CSMC__
#define __SIMD32_TYPE int32_t
#define CMSIS_UNUSED
#elif defined __TASKING__
#define __SIMD32_TYPE __unaligned int32_t
#define CMSIS_UNUSED
#else
#error Unknown compiler
#endif
#define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr))
#define __SIMD32_CONST(addr) ((__SIMD32_TYPE *)(addr))
#define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE *) (addr))
#define __SIMD64(addr) (*(int64_t **) & (addr))
#if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY)
/**
* @brief definition to pack two 16 bit values.
*/
#define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \
(((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) )
#define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \
(((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) )
#endif
/**
* @brief definition to pack four 8 bit values.
*/
#ifndef ARM_MATH_BIG_ENDIAN
#define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \
(((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \
(((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \
(((int32_t)(v3) << 24) & (int32_t)0xFF000000) )
#else
#define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \
(((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \
(((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \
(((int32_t)(v0) << 24) & (int32_t)0xFF000000) )
#endif
/**
* @brief Clips Q63 to Q31 values.
*/
static __INLINE q31_t clip_q63_to_q31(
q63_t x)
{
return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x;
}
/**
* @brief Clips Q63 to Q15 values.
*/
static __INLINE q15_t clip_q63_to_q15(
q63_t x)
{
return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15);
}
/**
* @brief Clips Q31 to Q7 values.
*/
static __INLINE q7_t clip_q31_to_q7(
q31_t x)
{
return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ?
((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x;
}
/**
* @brief Clips Q31 to Q15 values.
*/
static __INLINE q15_t clip_q31_to_q15(
q31_t x)
{
return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ?
((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x;
}
/**
* @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format.
*/
static __INLINE q63_t mult32x64(
q63_t x,
q31_t y)
{
return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) +
(((q63_t) (x >> 32) * y)));
}
/*
#if defined (ARM_MATH_CM0_FAMILY) && defined ( __CC_ARM )
#define __CLZ __clz
#endif
*/
/* note: function can be removed when all toolchain support __CLZ for Cortex-M0 */
#if defined (ARM_MATH_CM0_FAMILY) && ((defined (__ICCARM__)) )
static __INLINE uint32_t __CLZ(
q31_t data);
static __INLINE uint32_t __CLZ(
q31_t data)
{
uint32_t count = 0;
uint32_t mask = 0x80000000;
while((data & mask) == 0)
{
count += 1u;
mask = mask >> 1u;
}
return (count);
}
#endif
/**
* @brief Function to Calculates 1/in (reciprocal) value of Q31 Data type.
*/
static __INLINE uint32_t arm_recip_q31(
q31_t in,
q31_t * dst,
q31_t * pRecipTable)
{
q31_t out;
uint32_t tempVal;
uint32_t index, i;
uint32_t signBits;
if(in > 0)
{
signBits = ((uint32_t) (__CLZ( in) - 1));
}
else
{
signBits = ((uint32_t) (__CLZ(-in) - 1));
}
/* Convert input sample to 1.31 format */
in = (in << signBits);
/* calculation of index for initial approximated Val */
index = (uint32_t)(in >> 24);
index = (index & INDEX_MASK);
/* 1.31 with exp 1 */
out = pRecipTable[index];
/* calculation of reciprocal value */
/* running approximation for two iterations */
for (i = 0u; i < 2u; i++)
{
tempVal = (uint32_t) (((q63_t) in * out) >> 31);
tempVal = 0x7FFFFFFFu - tempVal;
/* 1.31 with exp 1 */
/* out = (q31_t) (((q63_t) out * tempVal) >> 30); */
out = clip_q63_to_q31(((q63_t) out * tempVal) >> 30);
}
/* write output */
*dst = out;
/* return num of signbits of out = 1/in value */
return (signBits + 1u);
}
/**
* @brief Function to Calculates 1/in (reciprocal) value of Q15 Data type.
*/
static __INLINE uint32_t arm_recip_q15(
q15_t in,
q15_t * dst,
q15_t * pRecipTable)
{
q15_t out = 0;
uint32_t tempVal = 0;
uint32_t index = 0, i = 0;
uint32_t signBits = 0;
if(in > 0)
{
signBits = ((uint32_t)(__CLZ( in) - 17));
}
else
{
signBits = ((uint32_t)(__CLZ(-in) - 17));
}
/* Convert input sample to 1.15 format */
in = (in << signBits);
/* calculation of index for initial approximated Val */
index = (uint32_t)(in >> 8);
index = (index & INDEX_MASK);
/* 1.15 with exp 1 */
out = pRecipTable[index];
/* calculation of reciprocal value */
/* running approximation for two iterations */
for (i = 0u; i < 2u; i++)
{
tempVal = (uint32_t) (((q31_t) in * out) >> 15);
tempVal = 0x7FFFu - tempVal;
/* 1.15 with exp 1 */
out = (q15_t) (((q31_t) out * tempVal) >> 14);
/* out = clip_q31_to_q15(((q31_t) out * tempVal) >> 14); */
}
/* write output */
*dst = out;
/* return num of signbits of out = 1/in value */
return (signBits + 1);
}
/*
* @brief C custom defined intrinisic function for only M0 processors
*/
#if defined(ARM_MATH_CM0_FAMILY)
static __INLINE q31_t __SSAT(
q31_t x,
uint32_t y)
{
int32_t posMax, negMin;
uint32_t i;
posMax = 1;
for (i = 0; i < (y - 1); i++)
{
posMax = posMax * 2;
}
if(x > 0)
{
posMax = (posMax - 1);
if(x > posMax)
{
x = posMax;
}
}
else
{
negMin = -posMax;
if(x < negMin)
{
x = negMin;
}
}
return (x);
}
#endif /* end of ARM_MATH_CM0_FAMILY */
/*
* @brief C custom defined intrinsic function for M3 and M0 processors
*/
#if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY)
/*
* @brief C custom defined QADD8 for M3 and M0 processors
*/
static __INLINE uint32_t __QADD8(
uint32_t x,
uint32_t y)
{
q31_t r, s, t, u;
r = __SSAT(((((q31_t)x << 24) >> 24) + (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
s = __SSAT(((((q31_t)x << 16) >> 24) + (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
t = __SSAT(((((q31_t)x << 8) >> 24) + (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
u = __SSAT(((((q31_t)x ) >> 24) + (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
}
/*
* @brief C custom defined QSUB8 for M3 and M0 processors
*/
static __INLINE uint32_t __QSUB8(
uint32_t x,
uint32_t y)
{
q31_t r, s, t, u;
r = __SSAT(((((q31_t)x << 24) >> 24) - (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
s = __SSAT(((((q31_t)x << 16) >> 24) - (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
t = __SSAT(((((q31_t)x << 8) >> 24) - (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
u = __SSAT(((((q31_t)x ) >> 24) - (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
}
/*
* @brief C custom defined QADD16 for M3 and M0 processors
*/
static __INLINE uint32_t __QADD16(
uint32_t x,
uint32_t y)
{
/* q31_t r, s; without initialisation 'arm_offset_q15 test' fails but 'intrinsic' tests pass! for armCC */
q31_t r = 0, s = 0;
r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined SHADD16 for M3 and M0 processors
*/
static __INLINE uint32_t __SHADD16(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = (((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
s = (((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined QSUB16 for M3 and M0 processors
*/
static __INLINE uint32_t __QSUB16(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined SHSUB16 for M3 and M0 processors
*/
static __INLINE uint32_t __SHSUB16(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = (((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
s = (((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined QASX for M3 and M0 processors
*/
static __INLINE uint32_t __QASX(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined SHASX for M3 and M0 processors
*/
static __INLINE uint32_t __SHASX(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = (((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
s = (((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined QSAX for M3 and M0 processors
*/
static __INLINE uint32_t __QSAX(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined SHSAX for M3 and M0 processors
*/
static __INLINE uint32_t __SHSAX(
uint32_t x,
uint32_t y)
{
q31_t r, s;
r = (((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
s = (((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
return ((uint32_t)((s << 16) | (r )));
}
/*
* @brief C custom defined SMUSDX for M3 and M0 processors
*/
static __INLINE uint32_t __SMUSDX(
uint32_t x,
uint32_t y)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
}
/*
* @brief C custom defined SMUADX for M3 and M0 processors
*/
static __INLINE uint32_t __SMUADX(
uint32_t x,
uint32_t y)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
}
/*
* @brief C custom defined QADD for M3 and M0 processors
*/
static __INLINE int32_t __QADD(
int32_t x,
int32_t y)
{
return ((int32_t)(clip_q63_to_q31((q63_t)x + (q31_t)y)));
}
/*
* @brief C custom defined QSUB for M3 and M0 processors
*/
static __INLINE int32_t __QSUB(
int32_t x,
int32_t y)
{
return ((int32_t)(clip_q63_to_q31((q63_t)x - (q31_t)y)));
}
/*
* @brief C custom defined SMLAD for M3 and M0 processors
*/
static __INLINE uint32_t __SMLAD(
uint32_t x,
uint32_t y,
uint32_t sum)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
( ((q31_t)sum ) ) ));
}
/*
* @brief C custom defined SMLADX for M3 and M0 processors
*/
static __INLINE uint32_t __SMLADX(
uint32_t x,
uint32_t y,
uint32_t sum)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
( ((q31_t)sum ) ) ));
}
/*
* @brief C custom defined SMLSDX for M3 and M0 processors
*/
static __INLINE uint32_t __SMLSDX(
uint32_t x,
uint32_t y,
uint32_t sum)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
( ((q31_t)sum ) ) ));
}
/*
* @brief C custom defined SMLALD for M3 and M0 processors
*/
static __INLINE uint64_t __SMLALD(
uint32_t x,
uint32_t y,
uint64_t sum)
{
/* return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); */
return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
( ((q63_t)sum ) ) ));
}
/*
* @brief C custom defined SMLALDX for M3 and M0 processors
*/
static __INLINE uint64_t __SMLALDX(
uint32_t x,
uint32_t y,
uint64_t sum)
{
/* return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); */
return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
( ((q63_t)sum ) ) ));
}
/*
* @brief C custom defined SMUAD for M3 and M0 processors
*/
static __INLINE uint32_t __SMUAD(
uint32_t x,
uint32_t y)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
}
/*
* @brief C custom defined SMUSD for M3 and M0 processors
*/
static __INLINE uint32_t __SMUSD(
uint32_t x,
uint32_t y)
{
return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) -
((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
}
/*
* @brief C custom defined SXTB16 for M3 and M0 processors
*/
static __INLINE uint32_t __SXTB16(
uint32_t x)
{
return ((uint32_t)(((((q31_t)x << 24) >> 24) & (q31_t)0x0000FFFF) |
((((q31_t)x << 8) >> 8) & (q31_t)0xFFFF0000) ));
}
#endif /* defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) */
/**
* @brief Instance structure for the Q7 FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of filter coefficients in the filter. */
q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
} arm_fir_instance_q7;
/**
* @brief Instance structure for the Q15 FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of filter coefficients in the filter. */
q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
} arm_fir_instance_q15;
/**
* @brief Instance structure for the Q31 FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of filter coefficients in the filter. */
q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
} arm_fir_instance_q31;
/**
* @brief Instance structure for the floating-point FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of filter coefficients in the filter. */
float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
} arm_fir_instance_f32;
/**
* @brief Processing function for the Q7 FIR filter.
* @param[in] S points to an instance of the Q7 FIR filter structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_q7(
const arm_fir_instance_q7 * S,
q7_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q7 FIR filter.
* @param[in,out] S points to an instance of the Q7 FIR structure.
* @param[in] numTaps Number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of samples that are processed.
*/
void arm_fir_init_q7(
arm_fir_instance_q7 * S,
uint16_t numTaps,
q7_t * pCoeffs,
q7_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q15 FIR filter.
* @param[in] S points to an instance of the Q15 FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_q15(
const arm_fir_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the fast Q15 FIR filter for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q15 FIR filter structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_fast_q15(
const arm_fir_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 FIR filter.
* @param[in,out] S points to an instance of the Q15 FIR filter structure.
* @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of samples that are processed at a time.
* @return The function returns ARM_MATH_SUCCESS if initialization was successful or ARM_MATH_ARGUMENT_ERROR if
* <code>numTaps</code> is not a supported value.
*/
arm_status arm_fir_init_q15(
arm_fir_instance_q15 * S,
uint16_t numTaps,
q15_t * pCoeffs,
q15_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 FIR filter.
* @param[in] S points to an instance of the Q31 FIR filter structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_q31(
const arm_fir_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the fast Q31 FIR filter for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q31 FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_fast_q31(
const arm_fir_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 FIR filter.
* @param[in,out] S points to an instance of the Q31 FIR structure.
* @param[in] numTaps Number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of samples that are processed at a time.
*/
void arm_fir_init_q31(
arm_fir_instance_q31 * S,
uint16_t numTaps,
q31_t * pCoeffs,
q31_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the floating-point FIR filter.
* @param[in] S points to an instance of the floating-point FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_f32(
const arm_fir_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point FIR filter.
* @param[in,out] S points to an instance of the floating-point FIR filter structure.
* @param[in] numTaps Number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of samples that are processed at a time.
*/
void arm_fir_init_f32(
arm_fir_instance_f32 * S,
uint16_t numTaps,
float32_t * pCoeffs,
float32_t * pState,
uint32_t blockSize);
/**
* @brief Instance structure for the Q15 Biquad cascade filter.
*/
typedef struct
{
int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
} arm_biquad_casd_df1_inst_q15;
/**
* @brief Instance structure for the Q31 Biquad cascade filter.
*/
typedef struct
{
uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
} arm_biquad_casd_df1_inst_q31;
/**
* @brief Instance structure for the floating-point Biquad cascade filter.
*/
typedef struct
{
uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
} arm_biquad_casd_df1_inst_f32;
/**
* @brief Processing function for the Q15 Biquad cascade filter.
* @param[in] S points to an instance of the Q15 Biquad cascade structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df1_q15(
const arm_biquad_casd_df1_inst_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 Biquad cascade filter.
* @param[in,out] S points to an instance of the Q15 Biquad cascade structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
*/
void arm_biquad_cascade_df1_init_q15(
arm_biquad_casd_df1_inst_q15 * S,
uint8_t numStages,
q15_t * pCoeffs,
q15_t * pState,
int8_t postShift);
/**
* @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q15 Biquad cascade structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df1_fast_q15(
const arm_biquad_casd_df1_inst_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 Biquad cascade filter
* @param[in] S points to an instance of the Q31 Biquad cascade structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df1_q31(
const arm_biquad_casd_df1_inst_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q31 Biquad cascade structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df1_fast_q31(
const arm_biquad_casd_df1_inst_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 Biquad cascade filter.
* @param[in,out] S points to an instance of the Q31 Biquad cascade structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
*/
void arm_biquad_cascade_df1_init_q31(
arm_biquad_casd_df1_inst_q31 * S,
uint8_t numStages,
q31_t * pCoeffs,
q31_t * pState,
int8_t postShift);
/**
* @brief Processing function for the floating-point Biquad cascade filter.
* @param[in] S points to an instance of the floating-point Biquad cascade structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df1_f32(
const arm_biquad_casd_df1_inst_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point Biquad cascade filter.
* @param[in,out] S points to an instance of the floating-point Biquad cascade structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
*/
void arm_biquad_cascade_df1_init_f32(
arm_biquad_casd_df1_inst_f32 * S,
uint8_t numStages,
float32_t * pCoeffs,
float32_t * pState);
/**
* @brief Instance structure for the floating-point matrix structure.
*/
typedef struct
{
uint16_t numRows; /**< number of rows of the matrix. */
uint16_t numCols; /**< number of columns of the matrix. */
float32_t *pData; /**< points to the data of the matrix. */
} arm_matrix_instance_f32;
/**
* @brief Instance structure for the floating-point matrix structure.
*/
typedef struct
{
uint16_t numRows; /**< number of rows of the matrix. */
uint16_t numCols; /**< number of columns of the matrix. */
float64_t *pData; /**< points to the data of the matrix. */
} arm_matrix_instance_f64;
/**
* @brief Instance structure for the Q15 matrix structure.
*/
typedef struct
{
uint16_t numRows; /**< number of rows of the matrix. */
uint16_t numCols; /**< number of columns of the matrix. */
q15_t *pData; /**< points to the data of the matrix. */
} arm_matrix_instance_q15;
/**
* @brief Instance structure for the Q31 matrix structure.
*/
typedef struct
{
uint16_t numRows; /**< number of rows of the matrix. */
uint16_t numCols; /**< number of columns of the matrix. */
q31_t *pData; /**< points to the data of the matrix. */
} arm_matrix_instance_q31;
/**
* @brief Floating-point matrix addition.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_add_f32(
const arm_matrix_instance_f32 * pSrcA,
const arm_matrix_instance_f32 * pSrcB,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15 matrix addition.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_add_q15(
const arm_matrix_instance_q15 * pSrcA,
const arm_matrix_instance_q15 * pSrcB,
arm_matrix_instance_q15 * pDst);
/**
* @brief Q31 matrix addition.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_add_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst);
/**
* @brief Floating-point, complex, matrix multiplication.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_cmplx_mult_f32(
const arm_matrix_instance_f32 * pSrcA,
const arm_matrix_instance_f32 * pSrcB,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15, complex, matrix multiplication.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_cmplx_mult_q15(
const arm_matrix_instance_q15 * pSrcA,
const arm_matrix_instance_q15 * pSrcB,
arm_matrix_instance_q15 * pDst,
q15_t * pScratch);
/**
* @brief Q31, complex, matrix multiplication.
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_cmplx_mult_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst);
/**
* @brief Floating-point matrix transpose.
* @param[in] pSrc points to the input matrix
* @param[out] pDst points to the output matrix
* @return The function returns either <code>ARM_MATH_SIZE_MISMATCH</code>
* or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_trans_f32(
const arm_matrix_instance_f32 * pSrc,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15 matrix transpose.
* @param[in] pSrc points to the input matrix
* @param[out] pDst points to the output matrix
* @return The function returns either <code>ARM_MATH_SIZE_MISMATCH</code>
* or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_trans_q15(
const arm_matrix_instance_q15 * pSrc,
arm_matrix_instance_q15 * pDst);
/**
* @brief Q31 matrix transpose.
* @param[in] pSrc points to the input matrix
* @param[out] pDst points to the output matrix
* @return The function returns either <code>ARM_MATH_SIZE_MISMATCH</code>
* or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_trans_q31(
const arm_matrix_instance_q31 * pSrc,
arm_matrix_instance_q31 * pDst);
/**
* @brief Floating-point matrix multiplication
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_mult_f32(
const arm_matrix_instance_f32 * pSrcA,
const arm_matrix_instance_f32 * pSrcB,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15 matrix multiplication
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @param[in] pState points to the array for storing intermediate results
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_mult_q15(
const arm_matrix_instance_q15 * pSrcA,
const arm_matrix_instance_q15 * pSrcB,
arm_matrix_instance_q15 * pDst,
q15_t * pState);
/**
* @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @param[in] pState points to the array for storing intermediate results
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_mult_fast_q15(
const arm_matrix_instance_q15 * pSrcA,
const arm_matrix_instance_q15 * pSrcB,
arm_matrix_instance_q15 * pDst,
q15_t * pState);
/**
* @brief Q31 matrix multiplication
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_mult_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst);
/**
* @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_mult_fast_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst);
/**
* @brief Floating-point matrix subtraction
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_sub_f32(
const arm_matrix_instance_f32 * pSrcA,
const arm_matrix_instance_f32 * pSrcB,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15 matrix subtraction
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_sub_q15(
const arm_matrix_instance_q15 * pSrcA,
const arm_matrix_instance_q15 * pSrcB,
arm_matrix_instance_q15 * pDst);
/**
* @brief Q31 matrix subtraction
* @param[in] pSrcA points to the first input matrix structure
* @param[in] pSrcB points to the second input matrix structure
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_sub_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst);
/**
* @brief Floating-point matrix scaling.
* @param[in] pSrc points to the input matrix
* @param[in] scale scale factor
* @param[out] pDst points to the output matrix
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_scale_f32(
const arm_matrix_instance_f32 * pSrc,
float32_t scale,
arm_matrix_instance_f32 * pDst);
/**
* @brief Q15 matrix scaling.
* @param[in] pSrc points to input matrix
* @param[in] scaleFract fractional portion of the scale factor
* @param[in] shift number of bits to shift the result by
* @param[out] pDst points to output matrix
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_scale_q15(
const arm_matrix_instance_q15 * pSrc,
q15_t scaleFract,
int32_t shift,
arm_matrix_instance_q15 * pDst);
/**
* @brief Q31 matrix scaling.
* @param[in] pSrc points to input matrix
* @param[in] scaleFract fractional portion of the scale factor
* @param[in] shift number of bits to shift the result by
* @param[out] pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*/
arm_status arm_mat_scale_q31(
const arm_matrix_instance_q31 * pSrc,
q31_t scaleFract,
int32_t shift,
arm_matrix_instance_q31 * pDst);
/**
* @brief Q31 matrix initialization.
* @param[in,out] S points to an instance of the floating-point matrix structure.
* @param[in] nRows number of rows in the matrix.
* @param[in] nColumns number of columns in the matrix.
* @param[in] pData points to the matrix data array.
*/
void arm_mat_init_q31(
arm_matrix_instance_q31 * S,
uint16_t nRows,
uint16_t nColumns,
q31_t * pData);
/**
* @brief Q15 matrix initialization.
* @param[in,out] S points to an instance of the floating-point matrix structure.
* @param[in] nRows number of rows in the matrix.
* @param[in] nColumns number of columns in the matrix.
* @param[in] pData points to the matrix data array.
*/
void arm_mat_init_q15(
arm_matrix_instance_q15 * S,
uint16_t nRows,
uint16_t nColumns,
q15_t * pData);
/**
* @brief Floating-point matrix initialization.
* @param[in,out] S points to an instance of the floating-point matrix structure.
* @param[in] nRows number of rows in the matrix.
* @param[in] nColumns number of columns in the matrix.
* @param[in] pData points to the matrix data array.
*/
void arm_mat_init_f32(
arm_matrix_instance_f32 * S,
uint16_t nRows,
uint16_t nColumns,
float32_t * pData);
/**
* @brief Instance structure for the Q15 PID Control.
*/
typedef struct
{
q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
#ifdef ARM_MATH_CM0_FAMILY
q15_t A1;
q15_t A2;
#else
q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/
#endif
q15_t state[3]; /**< The state array of length 3. */
q15_t Kp; /**< The proportional gain. */
q15_t Ki; /**< The integral gain. */
q15_t Kd; /**< The derivative gain. */
} arm_pid_instance_q15;
/**
* @brief Instance structure for the Q31 PID Control.
*/
typedef struct
{
q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */
q31_t A2; /**< The derived gain, A2 = Kd . */
q31_t state[3]; /**< The state array of length 3. */
q31_t Kp; /**< The proportional gain. */
q31_t Ki; /**< The integral gain. */
q31_t Kd; /**< The derivative gain. */
} arm_pid_instance_q31;
/**
* @brief Instance structure for the floating-point PID Control.
*/
typedef struct
{
float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */
float32_t A2; /**< The derived gain, A2 = Kd . */
float32_t state[3]; /**< The state array of length 3. */
float32_t Kp; /**< The proportional gain. */
float32_t Ki; /**< The integral gain. */
float32_t Kd; /**< The derivative gain. */
} arm_pid_instance_f32;
/**
* @brief Initialization function for the floating-point PID Control.
* @param[in,out] S points to an instance of the PID structure.
* @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
*/
void arm_pid_init_f32(
arm_pid_instance_f32 * S,
int32_t resetStateFlag);
/**
* @brief Reset function for the floating-point PID Control.
* @param[in,out] S is an instance of the floating-point PID Control structure
*/
void arm_pid_reset_f32(
arm_pid_instance_f32 * S);
/**
* @brief Initialization function for the Q31 PID Control.
* @param[in,out] S points to an instance of the Q15 PID structure.
* @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
*/
void arm_pid_init_q31(
arm_pid_instance_q31 * S,
int32_t resetStateFlag);
/**
* @brief Reset function for the Q31 PID Control.
* @param[in,out] S points to an instance of the Q31 PID Control structure
*/
void arm_pid_reset_q31(
arm_pid_instance_q31 * S);
/**
* @brief Initialization function for the Q15 PID Control.
* @param[in,out] S points to an instance of the Q15 PID structure.
* @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
*/
void arm_pid_init_q15(
arm_pid_instance_q15 * S,
int32_t resetStateFlag);
/**
* @brief Reset function for the Q15 PID Control.
* @param[in,out] S points to an instance of the q15 PID Control structure
*/
void arm_pid_reset_q15(
arm_pid_instance_q15 * S);
/**
* @brief Instance structure for the floating-point Linear Interpolate function.
*/
typedef struct
{
uint32_t nValues; /**< nValues */
float32_t x1; /**< x1 */
float32_t xSpacing; /**< xSpacing */
float32_t *pYData; /**< pointer to the table of Y values */
} arm_linear_interp_instance_f32;
/**
* @brief Instance structure for the floating-point bilinear interpolation function.
*/
typedef struct
{
uint16_t numRows; /**< number of rows in the data table. */
uint16_t numCols; /**< number of columns in the data table. */
float32_t *pData; /**< points to the data table. */
} arm_bilinear_interp_instance_f32;
/**
* @brief Instance structure for the Q31 bilinear interpolation function.
*/
typedef struct
{
uint16_t numRows; /**< number of rows in the data table. */
uint16_t numCols; /**< number of columns in the data table. */
q31_t *pData; /**< points to the data table. */
} arm_bilinear_interp_instance_q31;
/**
* @brief Instance structure for the Q15 bilinear interpolation function.
*/
typedef struct
{
uint16_t numRows; /**< number of rows in the data table. */
uint16_t numCols; /**< number of columns in the data table. */
q15_t *pData; /**< points to the data table. */
} arm_bilinear_interp_instance_q15;
/**
* @brief Instance structure for the Q15 bilinear interpolation function.
*/
typedef struct
{
uint16_t numRows; /**< number of rows in the data table. */
uint16_t numCols; /**< number of columns in the data table. */
q7_t *pData; /**< points to the data table. */
} arm_bilinear_interp_instance_q7;
/**
* @brief Q7 vector multiplication.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_mult_q7(
q7_t * pSrcA,
q7_t * pSrcB,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Q15 vector multiplication.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_mult_q15(
q15_t * pSrcA,
q15_t * pSrcB,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Q31 vector multiplication.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_mult_q31(
q31_t * pSrcA,
q31_t * pSrcB,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Floating-point vector multiplication.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_mult_f32(
float32_t * pSrcA,
float32_t * pSrcB,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Instance structure for the Q15 CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
} arm_cfft_radix2_instance_q15;
/* Deprecated */
arm_status arm_cfft_radix2_init_q15(
arm_cfft_radix2_instance_q15 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/* Deprecated */
void arm_cfft_radix2_q15(
const arm_cfft_radix2_instance_q15 * S,
q15_t * pSrc);
/**
* @brief Instance structure for the Q15 CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
q15_t *pTwiddle; /**< points to the twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
} arm_cfft_radix4_instance_q15;
/* Deprecated */
arm_status arm_cfft_radix4_init_q15(
arm_cfft_radix4_instance_q15 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/* Deprecated */
void arm_cfft_radix4_q15(
const arm_cfft_radix4_instance_q15 * S,
q15_t * pSrc);
/**
* @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
q31_t *pTwiddle; /**< points to the Twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
} arm_cfft_radix2_instance_q31;
/* Deprecated */
arm_status arm_cfft_radix2_init_q31(
arm_cfft_radix2_instance_q31 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/* Deprecated */
void arm_cfft_radix2_q31(
const arm_cfft_radix2_instance_q31 * S,
q31_t * pSrc);
/**
* @brief Instance structure for the Q31 CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
q31_t *pTwiddle; /**< points to the twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
} arm_cfft_radix4_instance_q31;
/* Deprecated */
void arm_cfft_radix4_q31(
const arm_cfft_radix4_instance_q31 * S,
q31_t * pSrc);
/* Deprecated */
arm_status arm_cfft_radix4_init_q31(
arm_cfft_radix4_instance_q31 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/**
* @brief Instance structure for the floating-point CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
float32_t *pTwiddle; /**< points to the Twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
float32_t onebyfftLen; /**< value of 1/fftLen. */
} arm_cfft_radix2_instance_f32;
/* Deprecated */
arm_status arm_cfft_radix2_init_f32(
arm_cfft_radix2_instance_f32 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/* Deprecated */
void arm_cfft_radix2_f32(
const arm_cfft_radix2_instance_f32 * S,
float32_t * pSrc);
/**
* @brief Instance structure for the floating-point CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
float32_t *pTwiddle; /**< points to the Twiddle factor table. */
uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
float32_t onebyfftLen; /**< value of 1/fftLen. */
} arm_cfft_radix4_instance_f32;
/* Deprecated */
arm_status arm_cfft_radix4_init_f32(
arm_cfft_radix4_instance_f32 * S,
uint16_t fftLen,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/* Deprecated */
void arm_cfft_radix4_f32(
const arm_cfft_radix4_instance_f32 * S,
float32_t * pSrc);
/**
* @brief Instance structure for the fixed-point CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
const q15_t *pTwiddle; /**< points to the Twiddle factor table. */
const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t bitRevLength; /**< bit reversal table length. */
} arm_cfft_instance_q15;
void arm_cfft_q15(
const arm_cfft_instance_q15 * S,
q15_t * p1,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/**
* @brief Instance structure for the fixed-point CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
const q31_t *pTwiddle; /**< points to the Twiddle factor table. */
const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t bitRevLength; /**< bit reversal table length. */
} arm_cfft_instance_q31;
void arm_cfft_q31(
const arm_cfft_instance_q31 * S,
q31_t * p1,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/**
* @brief Instance structure for the floating-point CFFT/CIFFT function.
*/
typedef struct
{
uint16_t fftLen; /**< length of the FFT. */
const float32_t *pTwiddle; /**< points to the Twiddle factor table. */
const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
uint16_t bitRevLength; /**< bit reversal table length. */
} arm_cfft_instance_f32;
void arm_cfft_f32(
const arm_cfft_instance_f32 * S,
float32_t * p1,
uint8_t ifftFlag,
uint8_t bitReverseFlag);
/**
* @brief Instance structure for the Q15 RFFT/RIFFT function.
*/
typedef struct
{
uint32_t fftLenReal; /**< length of the real FFT. */
uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */
} arm_rfft_instance_q15;
arm_status arm_rfft_init_q15(
arm_rfft_instance_q15 * S,
uint32_t fftLenReal,
uint32_t ifftFlagR,
uint32_t bitReverseFlag);
void arm_rfft_q15(
const arm_rfft_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst);
/**
* @brief Instance structure for the Q31 RFFT/RIFFT function.
*/
typedef struct
{
uint32_t fftLenReal; /**< length of the real FFT. */
uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */
} arm_rfft_instance_q31;
arm_status arm_rfft_init_q31(
arm_rfft_instance_q31 * S,
uint32_t fftLenReal,
uint32_t ifftFlagR,
uint32_t bitReverseFlag);
void arm_rfft_q31(
const arm_rfft_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst);
/**
* @brief Instance structure for the floating-point RFFT/RIFFT function.
*/
typedef struct
{
uint32_t fftLenReal; /**< length of the real FFT. */
uint16_t fftLenBy2; /**< length of the complex FFT. */
uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
} arm_rfft_instance_f32;
arm_status arm_rfft_init_f32(
arm_rfft_instance_f32 * S,
arm_cfft_radix4_instance_f32 * S_CFFT,
uint32_t fftLenReal,
uint32_t ifftFlagR,
uint32_t bitReverseFlag);
void arm_rfft_f32(
const arm_rfft_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst);
/**
* @brief Instance structure for the floating-point RFFT/RIFFT function.
*/
typedef struct
{
arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */
uint16_t fftLenRFFT; /**< length of the real sequence */
float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */
} arm_rfft_fast_instance_f32 ;
arm_status arm_rfft_fast_init_f32 (
arm_rfft_fast_instance_f32 * S,
uint16_t fftLen);
void arm_rfft_fast_f32(
arm_rfft_fast_instance_f32 * S,
float32_t * p, float32_t * pOut,
uint8_t ifftFlag);
/**
* @brief Instance structure for the floating-point DCT4/IDCT4 function.
*/
typedef struct
{
uint16_t N; /**< length of the DCT4. */
uint16_t Nby2; /**< half of the length of the DCT4. */
float32_t normalize; /**< normalizing factor. */
float32_t *pTwiddle; /**< points to the twiddle factor table. */
float32_t *pCosFactor; /**< points to the cosFactor table. */
arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */
arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
} arm_dct4_instance_f32;
/**
* @brief Initialization function for the floating-point DCT4/IDCT4.
* @param[in,out] S points to an instance of floating-point DCT4/IDCT4 structure.
* @param[in] S_RFFT points to an instance of floating-point RFFT/RIFFT structure.
* @param[in] S_CFFT points to an instance of floating-point CFFT/CIFFT structure.
* @param[in] N length of the DCT4.
* @param[in] Nby2 half of the length of the DCT4.
* @param[in] normalize normalizing factor.
* @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if <code>fftLenReal</code> is not a supported transform length.
*/
arm_status arm_dct4_init_f32(
arm_dct4_instance_f32 * S,
arm_rfft_instance_f32 * S_RFFT,
arm_cfft_radix4_instance_f32 * S_CFFT,
uint16_t N,
uint16_t Nby2,
float32_t normalize);
/**
* @brief Processing function for the floating-point DCT4/IDCT4.
* @param[in] S points to an instance of the floating-point DCT4/IDCT4 structure.
* @param[in] pState points to state buffer.
* @param[in,out] pInlineBuffer points to the in-place input and output buffer.
*/
void arm_dct4_f32(
const arm_dct4_instance_f32 * S,
float32_t * pState,
float32_t * pInlineBuffer);
/**
* @brief Instance structure for the Q31 DCT4/IDCT4 function.
*/
typedef struct
{
uint16_t N; /**< length of the DCT4. */
uint16_t Nby2; /**< half of the length of the DCT4. */
q31_t normalize; /**< normalizing factor. */
q31_t *pTwiddle; /**< points to the twiddle factor table. */
q31_t *pCosFactor; /**< points to the cosFactor table. */
arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */
arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */
} arm_dct4_instance_q31;
/**
* @brief Initialization function for the Q31 DCT4/IDCT4.
* @param[in,out] S points to an instance of Q31 DCT4/IDCT4 structure.
* @param[in] S_RFFT points to an instance of Q31 RFFT/RIFFT structure
* @param[in] S_CFFT points to an instance of Q31 CFFT/CIFFT structure
* @param[in] N length of the DCT4.
* @param[in] Nby2 half of the length of the DCT4.
* @param[in] normalize normalizing factor.
* @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if <code>N</code> is not a supported transform length.
*/
arm_status arm_dct4_init_q31(
arm_dct4_instance_q31 * S,
arm_rfft_instance_q31 * S_RFFT,
arm_cfft_radix4_instance_q31 * S_CFFT,
uint16_t N,
uint16_t Nby2,
q31_t normalize);
/**
* @brief Processing function for the Q31 DCT4/IDCT4.
* @param[in] S points to an instance of the Q31 DCT4 structure.
* @param[in] pState points to state buffer.
* @param[in,out] pInlineBuffer points to the in-place input and output buffer.
*/
void arm_dct4_q31(
const arm_dct4_instance_q31 * S,
q31_t * pState,
q31_t * pInlineBuffer);
/**
* @brief Instance structure for the Q15 DCT4/IDCT4 function.
*/
typedef struct
{
uint16_t N; /**< length of the DCT4. */
uint16_t Nby2; /**< half of the length of the DCT4. */
q15_t normalize; /**< normalizing factor. */
q15_t *pTwiddle; /**< points to the twiddle factor table. */
q15_t *pCosFactor; /**< points to the cosFactor table. */
arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */
arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */
} arm_dct4_instance_q15;
/**
* @brief Initialization function for the Q15 DCT4/IDCT4.
* @param[in,out] S points to an instance of Q15 DCT4/IDCT4 structure.
* @param[in] S_RFFT points to an instance of Q15 RFFT/RIFFT structure.
* @param[in] S_CFFT points to an instance of Q15 CFFT/CIFFT structure.
* @param[in] N length of the DCT4.
* @param[in] Nby2 half of the length of the DCT4.
* @param[in] normalize normalizing factor.
* @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if <code>N</code> is not a supported transform length.
*/
arm_status arm_dct4_init_q15(
arm_dct4_instance_q15 * S,
arm_rfft_instance_q15 * S_RFFT,
arm_cfft_radix4_instance_q15 * S_CFFT,
uint16_t N,
uint16_t Nby2,
q15_t normalize);
/**
* @brief Processing function for the Q15 DCT4/IDCT4.
* @param[in] S points to an instance of the Q15 DCT4 structure.
* @param[in] pState points to state buffer.
* @param[in,out] pInlineBuffer points to the in-place input and output buffer.
*/
void arm_dct4_q15(
const arm_dct4_instance_q15 * S,
q15_t * pState,
q15_t * pInlineBuffer);
/**
* @brief Floating-point vector addition.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_add_f32(
float32_t * pSrcA,
float32_t * pSrcB,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Q7 vector addition.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_add_q7(
q7_t * pSrcA,
q7_t * pSrcB,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Q15 vector addition.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_add_q15(
q15_t * pSrcA,
q15_t * pSrcB,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Q31 vector addition.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_add_q31(
q31_t * pSrcA,
q31_t * pSrcB,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Floating-point vector subtraction.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_sub_f32(
float32_t * pSrcA,
float32_t * pSrcB,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Q7 vector subtraction.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_sub_q7(
q7_t * pSrcA,
q7_t * pSrcB,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Q15 vector subtraction.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_sub_q15(
q15_t * pSrcA,
q15_t * pSrcB,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Q31 vector subtraction.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void arm_sub_q31(
q31_t * pSrcA,
q31_t * pSrcB,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Multiplies a floating-point vector by a scalar.
* @param[in] pSrc points to the input vector
* @param[in] scale scale factor to be applied
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_scale_f32(
float32_t * pSrc,
float32_t scale,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Multiplies a Q7 vector by a scalar.
* @param[in] pSrc points to the input vector
* @param[in] scaleFract fractional portion of the scale value
* @param[in] shift number of bits to shift the result by
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_scale_q7(
q7_t * pSrc,
q7_t scaleFract,
int8_t shift,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Multiplies a Q15 vector by a scalar.
* @param[in] pSrc points to the input vector
* @param[in] scaleFract fractional portion of the scale value
* @param[in] shift number of bits to shift the result by
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_scale_q15(
q15_t * pSrc,
q15_t scaleFract,
int8_t shift,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Multiplies a Q31 vector by a scalar.
* @param[in] pSrc points to the input vector
* @param[in] scaleFract fractional portion of the scale value
* @param[in] shift number of bits to shift the result by
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_scale_q31(
q31_t * pSrc,
q31_t scaleFract,
int8_t shift,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Q7 vector absolute value.
* @param[in] pSrc points to the input buffer
* @param[out] pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
*/
void arm_abs_q7(
q7_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Floating-point vector absolute value.
* @param[in] pSrc points to the input buffer
* @param[out] pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
*/
void arm_abs_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Q15 vector absolute value.
* @param[in] pSrc points to the input buffer
* @param[out] pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
*/
void arm_abs_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Q31 vector absolute value.
* @param[in] pSrc points to the input buffer
* @param[out] pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
*/
void arm_abs_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Dot product of floating-point vectors.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] blockSize number of samples in each vector
* @param[out] result output result returned here
*/
void arm_dot_prod_f32(
float32_t * pSrcA,
float32_t * pSrcB,
uint32_t blockSize,
float32_t * result);
/**
* @brief Dot product of Q7 vectors.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] blockSize number of samples in each vector
* @param[out] result output result returned here
*/
void arm_dot_prod_q7(
q7_t * pSrcA,
q7_t * pSrcB,
uint32_t blockSize,
q31_t * result);
/**
* @brief Dot product of Q15 vectors.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] blockSize number of samples in each vector
* @param[out] result output result returned here
*/
void arm_dot_prod_q15(
q15_t * pSrcA,
q15_t * pSrcB,
uint32_t blockSize,
q63_t * result);
/**
* @brief Dot product of Q31 vectors.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] blockSize number of samples in each vector
* @param[out] result output result returned here
*/
void arm_dot_prod_q31(
q31_t * pSrcA,
q31_t * pSrcB,
uint32_t blockSize,
q63_t * result);
/**
* @brief Shifts the elements of a Q7 vector a specified number of bits.
* @param[in] pSrc points to the input vector
* @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_shift_q7(
q7_t * pSrc,
int8_t shiftBits,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Shifts the elements of a Q15 vector a specified number of bits.
* @param[in] pSrc points to the input vector
* @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_shift_q15(
q15_t * pSrc,
int8_t shiftBits,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Shifts the elements of a Q31 vector a specified number of bits.
* @param[in] pSrc points to the input vector
* @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_shift_q31(
q31_t * pSrc,
int8_t shiftBits,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Adds a constant offset to a floating-point vector.
* @param[in] pSrc points to the input vector
* @param[in] offset is the offset to be added
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_offset_f32(
float32_t * pSrc,
float32_t offset,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Adds a constant offset to a Q7 vector.
* @param[in] pSrc points to the input vector
* @param[in] offset is the offset to be added
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_offset_q7(
q7_t * pSrc,
q7_t offset,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Adds a constant offset to a Q15 vector.
* @param[in] pSrc points to the input vector
* @param[in] offset is the offset to be added
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_offset_q15(
q15_t * pSrc,
q15_t offset,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Adds a constant offset to a Q31 vector.
* @param[in] pSrc points to the input vector
* @param[in] offset is the offset to be added
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_offset_q31(
q31_t * pSrc,
q31_t offset,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Negates the elements of a floating-point vector.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_negate_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Negates the elements of a Q7 vector.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_negate_q7(
q7_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Negates the elements of a Q15 vector.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_negate_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Negates the elements of a Q31 vector.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void arm_negate_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Copies the elements of a floating-point vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_copy_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Copies the elements of a Q7 vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_copy_q7(
q7_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Copies the elements of a Q15 vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_copy_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Copies the elements of a Q31 vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_copy_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Fills a constant value into a floating-point vector.
* @param[in] value input value to be filled
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_fill_f32(
float32_t value,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Fills a constant value into a Q7 vector.
* @param[in] value input value to be filled
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_fill_q7(
q7_t value,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Fills a constant value into a Q15 vector.
* @param[in] value input value to be filled
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_fill_q15(
q15_t value,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Fills a constant value into a Q31 vector.
* @param[in] value input value to be filled
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_fill_q31(
q31_t value,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Convolution of floating-point sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
*/
void arm_conv_f32(
float32_t * pSrcA,
uint32_t srcALen,
float32_t * pSrcB,
uint32_t srcBLen,
float32_t * pDst);
/**
* @brief Convolution of Q15 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
* @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
*/
void arm_conv_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Convolution of Q15 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
*/
void arm_conv_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst);
/**
* @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
*/
void arm_conv_fast_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst);
/**
* @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
* @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
*/
void arm_conv_fast_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Convolution of Q31 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
*/
void arm_conv_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst);
/**
* @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
*/
void arm_conv_fast_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst);
/**
* @brief Convolution of Q7 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
* @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
*/
void arm_conv_opt_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Convolution of Q7 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
*/
void arm_conv_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst);
/**
* @brief Partial convolution of floating-point sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_f32(
float32_t * pSrcA,
uint32_t srcALen,
float32_t * pSrcB,
uint32_t srcBLen,
float32_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Partial convolution of Q15 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
uint32_t firstIndex,
uint32_t numPoints,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Partial convolution of Q15 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_fast_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_fast_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
uint32_t firstIndex,
uint32_t numPoints,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Partial convolution of Q31 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_fast_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Partial convolution of Q7 sequences
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_opt_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst,
uint32_t firstIndex,
uint32_t numPoints,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Partial convolution of Q7 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data
* @param[in] firstIndex is the first output sample to start with.
* @param[in] numPoints is the number of output points to be computed.
* @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
*/
arm_status arm_conv_partial_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst,
uint32_t firstIndex,
uint32_t numPoints);
/**
* @brief Instance structure for the Q15 FIR decimator.
*/
typedef struct
{
uint8_t M; /**< decimation factor. */
uint16_t numTaps; /**< number of coefficients in the filter. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
} arm_fir_decimate_instance_q15;
/**
* @brief Instance structure for the Q31 FIR decimator.
*/
typedef struct
{
uint8_t M; /**< decimation factor. */
uint16_t numTaps; /**< number of coefficients in the filter. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
} arm_fir_decimate_instance_q31;
/**
* @brief Instance structure for the floating-point FIR decimator.
*/
typedef struct
{
uint8_t M; /**< decimation factor. */
uint16_t numTaps; /**< number of coefficients in the filter. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
} arm_fir_decimate_instance_f32;
/**
* @brief Processing function for the floating-point FIR decimator.
* @param[in] S points to an instance of the floating-point FIR decimator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_decimate_f32(
const arm_fir_decimate_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point FIR decimator.
* @param[in,out] S points to an instance of the floating-point FIR decimator structure.
* @param[in] numTaps number of coefficients in the filter.
* @param[in] M decimation factor.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* <code>blockSize</code> is not a multiple of <code>M</code>.
*/
arm_status arm_fir_decimate_init_f32(
arm_fir_decimate_instance_f32 * S,
uint16_t numTaps,
uint8_t M,
float32_t * pCoeffs,
float32_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q15 FIR decimator.
* @param[in] S points to an instance of the Q15 FIR decimator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_decimate_q15(
const arm_fir_decimate_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q15 FIR decimator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_decimate_fast_q15(
const arm_fir_decimate_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 FIR decimator.
* @param[in,out] S points to an instance of the Q15 FIR decimator structure.
* @param[in] numTaps number of coefficients in the filter.
* @param[in] M decimation factor.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* <code>blockSize</code> is not a multiple of <code>M</code>.
*/
arm_status arm_fir_decimate_init_q15(
arm_fir_decimate_instance_q15 * S,
uint16_t numTaps,
uint8_t M,
q15_t * pCoeffs,
q15_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 FIR decimator.
* @param[in] S points to an instance of the Q31 FIR decimator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_decimate_q31(
const arm_fir_decimate_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
* @param[in] S points to an instance of the Q31 FIR decimator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_decimate_fast_q31(
arm_fir_decimate_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 FIR decimator.
* @param[in,out] S points to an instance of the Q31 FIR decimator structure.
* @param[in] numTaps number of coefficients in the filter.
* @param[in] M decimation factor.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* <code>blockSize</code> is not a multiple of <code>M</code>.
*/
arm_status arm_fir_decimate_init_q31(
arm_fir_decimate_instance_q31 * S,
uint16_t numTaps,
uint8_t M,
q31_t * pCoeffs,
q31_t * pState,
uint32_t blockSize);
/**
* @brief Instance structure for the Q15 FIR interpolator.
*/
typedef struct
{
uint8_t L; /**< upsample factor. */
uint16_t phaseLength; /**< length of each polyphase filter component. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
} arm_fir_interpolate_instance_q15;
/**
* @brief Instance structure for the Q31 FIR interpolator.
*/
typedef struct
{
uint8_t L; /**< upsample factor. */
uint16_t phaseLength; /**< length of each polyphase filter component. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
} arm_fir_interpolate_instance_q31;
/**
* @brief Instance structure for the floating-point FIR interpolator.
*/
typedef struct
{
uint8_t L; /**< upsample factor. */
uint16_t phaseLength; /**< length of each polyphase filter component. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */
} arm_fir_interpolate_instance_f32;
/**
* @brief Processing function for the Q15 FIR interpolator.
* @param[in] S points to an instance of the Q15 FIR interpolator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_interpolate_q15(
const arm_fir_interpolate_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 FIR interpolator.
* @param[in,out] S points to an instance of the Q15 FIR interpolator structure.
* @param[in] L upsample factor.
* @param[in] numTaps number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficient buffer.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* the filter length <code>numTaps</code> is not a multiple of the interpolation factor <code>L</code>.
*/
arm_status arm_fir_interpolate_init_q15(
arm_fir_interpolate_instance_q15 * S,
uint8_t L,
uint16_t numTaps,
q15_t * pCoeffs,
q15_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 FIR interpolator.
* @param[in] S points to an instance of the Q15 FIR interpolator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_interpolate_q31(
const arm_fir_interpolate_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 FIR interpolator.
* @param[in,out] S points to an instance of the Q31 FIR interpolator structure.
* @param[in] L upsample factor.
* @param[in] numTaps number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficient buffer.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* the filter length <code>numTaps</code> is not a multiple of the interpolation factor <code>L</code>.
*/
arm_status arm_fir_interpolate_init_q31(
arm_fir_interpolate_instance_q31 * S,
uint8_t L,
uint16_t numTaps,
q31_t * pCoeffs,
q31_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the floating-point FIR interpolator.
* @param[in] S points to an instance of the floating-point FIR interpolator structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_interpolate_f32(
const arm_fir_interpolate_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point FIR interpolator.
* @param[in,out] S points to an instance of the floating-point FIR interpolator structure.
* @param[in] L upsample factor.
* @param[in] numTaps number of filter coefficients in the filter.
* @param[in] pCoeffs points to the filter coefficient buffer.
* @param[in] pState points to the state buffer.
* @param[in] blockSize number of input samples to process per call.
* @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
* the filter length <code>numTaps</code> is not a multiple of the interpolation factor <code>L</code>.
*/
arm_status arm_fir_interpolate_init_f32(
arm_fir_interpolate_instance_f32 * S,
uint8_t L,
uint16_t numTaps,
float32_t * pCoeffs,
float32_t * pState,
uint32_t blockSize);
/**
* @brief Instance structure for the high precision Q31 Biquad cascade filter.
*/
typedef struct
{
uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */
} arm_biquad_cas_df1_32x64_ins_q31;
/**
* @param[in] S points to an instance of the high precision Q31 Biquad cascade filter structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cas_df1_32x64_q31(
const arm_biquad_cas_df1_32x64_ins_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @param[in,out] S points to an instance of the high precision Q31 Biquad cascade filter structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] postShift shift to be applied to the output. Varies according to the coefficients format
*/
void arm_biquad_cas_df1_32x64_init_q31(
arm_biquad_cas_df1_32x64_ins_q31 * S,
uint8_t numStages,
q31_t * pCoeffs,
q63_t * pState,
uint8_t postShift);
/**
* @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
*/
typedef struct
{
uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
} arm_biquad_cascade_df2T_instance_f32;
/**
* @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
*/
typedef struct
{
uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
} arm_biquad_cascade_stereo_df2T_instance_f32;
/**
* @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
*/
typedef struct
{
uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
} arm_biquad_cascade_df2T_instance_f64;
/**
* @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
* @param[in] S points to an instance of the filter data structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df2T_f32(
const arm_biquad_cascade_df2T_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels
* @param[in] S points to an instance of the filter data structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_stereo_df2T_f32(
const arm_biquad_cascade_stereo_df2T_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
* @param[in] S points to an instance of the filter data structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_biquad_cascade_df2T_f64(
const arm_biquad_cascade_df2T_instance_f64 * S,
float64_t * pSrc,
float64_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
* @param[in,out] S points to an instance of the filter data structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
*/
void arm_biquad_cascade_df2T_init_f32(
arm_biquad_cascade_df2T_instance_f32 * S,
uint8_t numStages,
float32_t * pCoeffs,
float32_t * pState);
/**
* @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
* @param[in,out] S points to an instance of the filter data structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
*/
void arm_biquad_cascade_stereo_df2T_init_f32(
arm_biquad_cascade_stereo_df2T_instance_f32 * S,
uint8_t numStages,
float32_t * pCoeffs,
float32_t * pState);
/**
* @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
* @param[in,out] S points to an instance of the filter data structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] pCoeffs points to the filter coefficients.
* @param[in] pState points to the state buffer.
*/
void arm_biquad_cascade_df2T_init_f64(
arm_biquad_cascade_df2T_instance_f64 * S,
uint8_t numStages,
float64_t * pCoeffs,
float64_t * pState);
/**
* @brief Instance structure for the Q15 FIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of filter stages. */
q15_t *pState; /**< points to the state variable array. The array is of length numStages. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
} arm_fir_lattice_instance_q15;
/**
* @brief Instance structure for the Q31 FIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of filter stages. */
q31_t *pState; /**< points to the state variable array. The array is of length numStages. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
} arm_fir_lattice_instance_q31;
/**
* @brief Instance structure for the floating-point FIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of filter stages. */
float32_t *pState; /**< points to the state variable array. The array is of length numStages. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
} arm_fir_lattice_instance_f32;
/**
* @brief Initialization function for the Q15 FIR lattice filter.
* @param[in] S points to an instance of the Q15 FIR lattice structure.
* @param[in] numStages number of filter stages.
* @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
* @param[in] pState points to the state buffer. The array is of length numStages.
*/
void arm_fir_lattice_init_q15(
arm_fir_lattice_instance_q15 * S,
uint16_t numStages,
q15_t * pCoeffs,
q15_t * pState);
/**
* @brief Processing function for the Q15 FIR lattice filter.
* @param[in] S points to an instance of the Q15 FIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_fir_lattice_q15(
const arm_fir_lattice_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 FIR lattice filter.
* @param[in] S points to an instance of the Q31 FIR lattice structure.
* @param[in] numStages number of filter stages.
* @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
* @param[in] pState points to the state buffer. The array is of length numStages.
*/
void arm_fir_lattice_init_q31(
arm_fir_lattice_instance_q31 * S,
uint16_t numStages,
q31_t * pCoeffs,
q31_t * pState);
/**
* @brief Processing function for the Q31 FIR lattice filter.
* @param[in] S points to an instance of the Q31 FIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_fir_lattice_q31(
const arm_fir_lattice_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point FIR lattice filter.
* @param[in] S points to an instance of the floating-point FIR lattice structure.
* @param[in] numStages number of filter stages.
* @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
* @param[in] pState points to the state buffer. The array is of length numStages.
*/
void arm_fir_lattice_init_f32(
arm_fir_lattice_instance_f32 * S,
uint16_t numStages,
float32_t * pCoeffs,
float32_t * pState);
/**
* @brief Processing function for the floating-point FIR lattice filter.
* @param[in] S points to an instance of the floating-point FIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*/
void arm_fir_lattice_f32(
const arm_fir_lattice_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Instance structure for the Q15 IIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of stages in the filter. */
q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
} arm_iir_lattice_instance_q15;
/**
* @brief Instance structure for the Q31 IIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of stages in the filter. */
q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
} arm_iir_lattice_instance_q31;
/**
* @brief Instance structure for the floating-point IIR lattice filter.
*/
typedef struct
{
uint16_t numStages; /**< number of stages in the filter. */
float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
} arm_iir_lattice_instance_f32;
/**
* @brief Processing function for the floating-point IIR lattice filter.
* @param[in] S points to an instance of the floating-point IIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_iir_lattice_f32(
const arm_iir_lattice_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point IIR lattice filter.
* @param[in] S points to an instance of the floating-point IIR lattice structure.
* @param[in] numStages number of stages in the filter.
* @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
* @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
* @param[in] pState points to the state buffer. The array is of length numStages+blockSize-1.
* @param[in] blockSize number of samples to process.
*/
void arm_iir_lattice_init_f32(
arm_iir_lattice_instance_f32 * S,
uint16_t numStages,
float32_t * pkCoeffs,
float32_t * pvCoeffs,
float32_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 IIR lattice filter.
* @param[in] S points to an instance of the Q31 IIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_iir_lattice_q31(
const arm_iir_lattice_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 IIR lattice filter.
* @param[in] S points to an instance of the Q31 IIR lattice structure.
* @param[in] numStages number of stages in the filter.
* @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
* @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
* @param[in] pState points to the state buffer. The array is of length numStages+blockSize.
* @param[in] blockSize number of samples to process.
*/
void arm_iir_lattice_init_q31(
arm_iir_lattice_instance_q31 * S,
uint16_t numStages,
q31_t * pkCoeffs,
q31_t * pvCoeffs,
q31_t * pState,
uint32_t blockSize);
/**
* @brief Processing function for the Q15 IIR lattice filter.
* @param[in] S points to an instance of the Q15 IIR lattice structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data.
* @param[in] blockSize number of samples to process.
*/
void arm_iir_lattice_q15(
const arm_iir_lattice_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 IIR lattice filter.
* @param[in] S points to an instance of the fixed-point Q15 IIR lattice structure.
* @param[in] numStages number of stages in the filter.
* @param[in] pkCoeffs points to reflection coefficient buffer. The array is of length numStages.
* @param[in] pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1.
* @param[in] pState points to state buffer. The array is of length numStages+blockSize.
* @param[in] blockSize number of samples to process per call.
*/
void arm_iir_lattice_init_q15(
arm_iir_lattice_instance_q15 * S,
uint16_t numStages,
q15_t * pkCoeffs,
q15_t * pvCoeffs,
q15_t * pState,
uint32_t blockSize);
/**
* @brief Instance structure for the floating-point LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
float32_t mu; /**< step size that controls filter coefficient updates. */
} arm_lms_instance_f32;
/**
* @brief Processing function for floating-point LMS filter.
* @param[in] S points to an instance of the floating-point LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_f32(
const arm_lms_instance_f32 * S,
float32_t * pSrc,
float32_t * pRef,
float32_t * pOut,
float32_t * pErr,
uint32_t blockSize);
/**
* @brief Initialization function for floating-point LMS filter.
* @param[in] S points to an instance of the floating-point LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to the coefficient buffer.
* @param[in] pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_init_f32(
arm_lms_instance_f32 * S,
uint16_t numTaps,
float32_t * pCoeffs,
float32_t * pState,
float32_t mu,
uint32_t blockSize);
/**
* @brief Instance structure for the Q15 LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
q15_t mu; /**< step size that controls filter coefficient updates. */
uint32_t postShift; /**< bit shift applied to coefficients. */
} arm_lms_instance_q15;
/**
* @brief Initialization function for the Q15 LMS filter.
* @param[in] S points to an instance of the Q15 LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to the coefficient buffer.
* @param[in] pState points to the state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @param[in] postShift bit shift applied to coefficients.
*/
void arm_lms_init_q15(
arm_lms_instance_q15 * S,
uint16_t numTaps,
q15_t * pCoeffs,
q15_t * pState,
q15_t mu,
uint32_t blockSize,
uint32_t postShift);
/**
* @brief Processing function for Q15 LMS filter.
* @param[in] S points to an instance of the Q15 LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_q15(
const arm_lms_instance_q15 * S,
q15_t * pSrc,
q15_t * pRef,
q15_t * pOut,
q15_t * pErr,
uint32_t blockSize);
/**
* @brief Instance structure for the Q31 LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
q31_t mu; /**< step size that controls filter coefficient updates. */
uint32_t postShift; /**< bit shift applied to coefficients. */
} arm_lms_instance_q31;
/**
* @brief Processing function for Q31 LMS filter.
* @param[in] S points to an instance of the Q15 LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_q31(
const arm_lms_instance_q31 * S,
q31_t * pSrc,
q31_t * pRef,
q31_t * pOut,
q31_t * pErr,
uint32_t blockSize);
/**
* @brief Initialization function for Q31 LMS filter.
* @param[in] S points to an instance of the Q31 LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to coefficient buffer.
* @param[in] pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @param[in] postShift bit shift applied to coefficients.
*/
void arm_lms_init_q31(
arm_lms_instance_q31 * S,
uint16_t numTaps,
q31_t * pCoeffs,
q31_t * pState,
q31_t mu,
uint32_t blockSize,
uint32_t postShift);
/**
* @brief Instance structure for the floating-point normalized LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
float32_t mu; /**< step size that control filter coefficient updates. */
float32_t energy; /**< saves previous frame energy. */
float32_t x0; /**< saves previous input sample. */
} arm_lms_norm_instance_f32;
/**
* @brief Processing function for floating-point normalized LMS filter.
* @param[in] S points to an instance of the floating-point normalized LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_norm_f32(
arm_lms_norm_instance_f32 * S,
float32_t * pSrc,
float32_t * pRef,
float32_t * pOut,
float32_t * pErr,
uint32_t blockSize);
/**
* @brief Initialization function for floating-point normalized LMS filter.
* @param[in] S points to an instance of the floating-point LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to coefficient buffer.
* @param[in] pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_norm_init_f32(
arm_lms_norm_instance_f32 * S,
uint16_t numTaps,
float32_t * pCoeffs,
float32_t * pState,
float32_t mu,
uint32_t blockSize);
/**
* @brief Instance structure for the Q31 normalized LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
q31_t mu; /**< step size that controls filter coefficient updates. */
uint8_t postShift; /**< bit shift applied to coefficients. */
q31_t *recipTable; /**< points to the reciprocal initial value table. */
q31_t energy; /**< saves previous frame energy. */
q31_t x0; /**< saves previous input sample. */
} arm_lms_norm_instance_q31;
/**
* @brief Processing function for Q31 normalized LMS filter.
* @param[in] S points to an instance of the Q31 normalized LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_norm_q31(
arm_lms_norm_instance_q31 * S,
q31_t * pSrc,
q31_t * pRef,
q31_t * pOut,
q31_t * pErr,
uint32_t blockSize);
/**
* @brief Initialization function for Q31 normalized LMS filter.
* @param[in] S points to an instance of the Q31 normalized LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to coefficient buffer.
* @param[in] pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @param[in] postShift bit shift applied to coefficients.
*/
void arm_lms_norm_init_q31(
arm_lms_norm_instance_q31 * S,
uint16_t numTaps,
q31_t * pCoeffs,
q31_t * pState,
q31_t mu,
uint32_t blockSize,
uint8_t postShift);
/**
* @brief Instance structure for the Q15 normalized LMS filter.
*/
typedef struct
{
uint16_t numTaps; /**< Number of coefficients in the filter. */
q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
q15_t mu; /**< step size that controls filter coefficient updates. */
uint8_t postShift; /**< bit shift applied to coefficients. */
q15_t *recipTable; /**< Points to the reciprocal initial value table. */
q15_t energy; /**< saves previous frame energy. */
q15_t x0; /**< saves previous input sample. */
} arm_lms_norm_instance_q15;
/**
* @brief Processing function for Q15 normalized LMS filter.
* @param[in] S points to an instance of the Q15 normalized LMS filter structure.
* @param[in] pSrc points to the block of input data.
* @param[in] pRef points to the block of reference data.
* @param[out] pOut points to the block of output data.
* @param[out] pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
*/
void arm_lms_norm_q15(
arm_lms_norm_instance_q15 * S,
q15_t * pSrc,
q15_t * pRef,
q15_t * pOut,
q15_t * pErr,
uint32_t blockSize);
/**
* @brief Initialization function for Q15 normalized LMS filter.
* @param[in] S points to an instance of the Q15 normalized LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] pCoeffs points to coefficient buffer.
* @param[in] pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @param[in] postShift bit shift applied to coefficients.
*/
void arm_lms_norm_init_q15(
arm_lms_norm_instance_q15 * S,
uint16_t numTaps,
q15_t * pCoeffs,
q15_t * pState,
q15_t mu,
uint32_t blockSize,
uint8_t postShift);
/**
* @brief Correlation of floating-point sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_f32(
float32_t * pSrcA,
uint32_t srcALen,
float32_t * pSrcB,
uint32_t srcBLen,
float32_t * pDst);
/**
* @brief Correlation of Q15 sequences
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
* @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
*/
void arm_correlate_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
q15_t * pScratch);
/**
* @brief Correlation of Q15 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst);
/**
* @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_fast_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst);
/**
* @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
* @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
*/
void arm_correlate_fast_opt_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst,
q15_t * pScratch);
/**
* @brief Correlation of Q31 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst);
/**
* @brief Correlation of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_fast_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst);
/**
* @brief Correlation of Q7 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
* @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
* @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
*/
void arm_correlate_opt_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst,
q15_t * pScratch1,
q15_t * pScratch2);
/**
* @brief Correlation of Q7 sequences.
* @param[in] pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
*/
void arm_correlate_q7(
q7_t * pSrcA,
uint32_t srcALen,
q7_t * pSrcB,
uint32_t srcBLen,
q7_t * pDst);
/**
* @brief Instance structure for the floating-point sparse FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
} arm_fir_sparse_instance_f32;
/**
* @brief Instance structure for the Q31 sparse FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
} arm_fir_sparse_instance_q31;
/**
* @brief Instance structure for the Q15 sparse FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
} arm_fir_sparse_instance_q15;
/**
* @brief Instance structure for the Q7 sparse FIR filter.
*/
typedef struct
{
uint16_t numTaps; /**< number of coefficients in the filter. */
uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
} arm_fir_sparse_instance_q7;
/**
* @brief Processing function for the floating-point sparse FIR filter.
* @param[in] S points to an instance of the floating-point sparse FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] pScratchIn points to a temporary buffer of size blockSize.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_sparse_f32(
arm_fir_sparse_instance_f32 * S,
float32_t * pSrc,
float32_t * pDst,
float32_t * pScratchIn,
uint32_t blockSize);
/**
* @brief Initialization function for the floating-point sparse FIR filter.
* @param[in,out] S points to an instance of the floating-point sparse FIR structure.
* @param[in] numTaps number of nonzero coefficients in the filter.
* @param[in] pCoeffs points to the array of filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] pTapDelay points to the array of offset times.
* @param[in] maxDelay maximum offset time supported.
* @param[in] blockSize number of samples that will be processed per block.
*/
void arm_fir_sparse_init_f32(
arm_fir_sparse_instance_f32 * S,
uint16_t numTaps,
float32_t * pCoeffs,
float32_t * pState,
int32_t * pTapDelay,
uint16_t maxDelay,
uint32_t blockSize);
/**
* @brief Processing function for the Q31 sparse FIR filter.
* @param[in] S points to an instance of the Q31 sparse FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] pScratchIn points to a temporary buffer of size blockSize.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_sparse_q31(
arm_fir_sparse_instance_q31 * S,
q31_t * pSrc,
q31_t * pDst,
q31_t * pScratchIn,
uint32_t blockSize);
/**
* @brief Initialization function for the Q31 sparse FIR filter.
* @param[in,out] S points to an instance of the Q31 sparse FIR structure.
* @param[in] numTaps number of nonzero coefficients in the filter.
* @param[in] pCoeffs points to the array of filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] pTapDelay points to the array of offset times.
* @param[in] maxDelay maximum offset time supported.
* @param[in] blockSize number of samples that will be processed per block.
*/
void arm_fir_sparse_init_q31(
arm_fir_sparse_instance_q31 * S,
uint16_t numTaps,
q31_t * pCoeffs,
q31_t * pState,
int32_t * pTapDelay,
uint16_t maxDelay,
uint32_t blockSize);
/**
* @brief Processing function for the Q15 sparse FIR filter.
* @param[in] S points to an instance of the Q15 sparse FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] pScratchIn points to a temporary buffer of size blockSize.
* @param[in] pScratchOut points to a temporary buffer of size blockSize.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_sparse_q15(
arm_fir_sparse_instance_q15 * S,
q15_t * pSrc,
q15_t * pDst,
q15_t * pScratchIn,
q31_t * pScratchOut,
uint32_t blockSize);
/**
* @brief Initialization function for the Q15 sparse FIR filter.
* @param[in,out] S points to an instance of the Q15 sparse FIR structure.
* @param[in] numTaps number of nonzero coefficients in the filter.
* @param[in] pCoeffs points to the array of filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] pTapDelay points to the array of offset times.
* @param[in] maxDelay maximum offset time supported.
* @param[in] blockSize number of samples that will be processed per block.
*/
void arm_fir_sparse_init_q15(
arm_fir_sparse_instance_q15 * S,
uint16_t numTaps,
q15_t * pCoeffs,
q15_t * pState,
int32_t * pTapDelay,
uint16_t maxDelay,
uint32_t blockSize);
/**
* @brief Processing function for the Q7 sparse FIR filter.
* @param[in] S points to an instance of the Q7 sparse FIR structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] pScratchIn points to a temporary buffer of size blockSize.
* @param[in] pScratchOut points to a temporary buffer of size blockSize.
* @param[in] blockSize number of input samples to process per call.
*/
void arm_fir_sparse_q7(
arm_fir_sparse_instance_q7 * S,
q7_t * pSrc,
q7_t * pDst,
q7_t * pScratchIn,
q31_t * pScratchOut,
uint32_t blockSize);
/**
* @brief Initialization function for the Q7 sparse FIR filter.
* @param[in,out] S points to an instance of the Q7 sparse FIR structure.
* @param[in] numTaps number of nonzero coefficients in the filter.
* @param[in] pCoeffs points to the array of filter coefficients.
* @param[in] pState points to the state buffer.
* @param[in] pTapDelay points to the array of offset times.
* @param[in] maxDelay maximum offset time supported.
* @param[in] blockSize number of samples that will be processed per block.
*/
void arm_fir_sparse_init_q7(
arm_fir_sparse_instance_q7 * S,
uint16_t numTaps,
q7_t * pCoeffs,
q7_t * pState,
int32_t * pTapDelay,
uint16_t maxDelay,
uint32_t blockSize);
/**
* @brief Floating-point sin_cos function.
* @param[in] theta input value in degrees
* @param[out] pSinVal points to the processed sine output.
* @param[out] pCosVal points to the processed cos output.
*/
void arm_sin_cos_f32(
float32_t theta,
float32_t * pSinVal,
float32_t * pCosVal);
/**
* @brief Q31 sin_cos function.
* @param[in] theta scaled input value in degrees
* @param[out] pSinVal points to the processed sine output.
* @param[out] pCosVal points to the processed cosine output.
*/
void arm_sin_cos_q31(
q31_t theta,
q31_t * pSinVal,
q31_t * pCosVal);
/**
* @brief Floating-point complex conjugate.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_conj_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t numSamples);
/**
* @brief Q31 complex conjugate.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_conj_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t numSamples);
/**
* @brief Q15 complex conjugate.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_conj_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t numSamples);
/**
* @brief Floating-point complex magnitude squared
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_squared_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t numSamples);
/**
* @brief Q31 complex magnitude squared
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_squared_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t numSamples);
/**
* @brief Q15 complex magnitude squared
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_squared_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t numSamples);
/**
* @ingroup groupController
*/
/**
* @defgroup PID PID Motor Control
*
* A Proportional Integral Derivative (PID) controller is a generic feedback control
* loop mechanism widely used in industrial control systems.
* A PID controller is the most commonly used type of feedback controller.
*
* This set of functions implements (PID) controllers
* for Q15, Q31, and floating-point data types. The functions operate on a single sample
* of data and each call to the function returns a single processed value.
* <code>S</code> points to an instance of the PID control data structure. <code>in</code>
* is the input sample value. The functions return the output value.
*
* \par Algorithm:
* <pre>
* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2]
* A0 = Kp + Ki + Kd
* A1 = (-Kp ) - (2 * Kd )
* A2 = Kd </pre>
*
* \par
* where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant
*
* \par
* \image html PID.gif "Proportional Integral Derivative Controller"
*
* \par
* The PID controller calculates an "error" value as the difference between
* the measured output and the reference input.
* The controller attempts to minimize the error by adjusting the process control inputs.
* The proportional value determines the reaction to the current error,
* the integral value determines the reaction based on the sum of recent errors,
* and the derivative value determines the reaction based on the rate at which the error has been changing.
*
* \par Instance Structure
* The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure.
* A separate instance structure must be defined for each PID Controller.
* There are separate instance structure declarations for each of the 3 supported data types.
*
* \par Reset Functions
* There is also an associated reset function for each data type which clears the state array.
*
* \par Initialization Functions
* There is also an associated initialization function for each data type.
* The initialization function performs the following operations:
* - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains.
* - Zeros out the values in the state buffer.
*
* \par
* Instance structure cannot be placed into a const data section and it is recommended to use the initialization function.
*
* \par Fixed-Point Behavior
* Care must be taken when using the fixed-point versions of the PID Controller functions.
* In particular, the overflow and saturation behavior of the accumulator used in each function must be considered.
* Refer to the function specific documentation below for usage guidelines.
*/
/**
* @addtogroup PID
* @{
*/
/**
* @brief Process function for the floating-point PID Control.
* @param[in,out] S is an instance of the floating-point PID Control structure
* @param[in] in input sample to process
* @return out processed output sample.
*/
static __INLINE float32_t arm_pid_f32(
arm_pid_instance_f32 * S,
float32_t in)
{
float32_t out;
/* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */
out = (S->A0 * in) +
(S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]);
/* Update state */
S->state[1] = S->state[0];
S->state[0] = in;
S->state[2] = out;
/* return to application */
return (out);
}
/**
* @brief Process function for the Q31 PID Control.
* @param[in,out] S points to an instance of the Q31 PID Control structure
* @param[in] in input sample to process
* @return out processed output sample.
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using an internal 64-bit accumulator.
* The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit.
* Thus, if the accumulator result overflows it wraps around rather than clip.
* In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions.
* After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format.
*/
static __INLINE q31_t arm_pid_q31(
arm_pid_instance_q31 * S,
q31_t in)
{
q63_t acc;
q31_t out;
/* acc = A0 * x[n] */
acc = (q63_t) S->A0 * in;
/* acc += A1 * x[n-1] */
acc += (q63_t) S->A1 * S->state[0];
/* acc += A2 * x[n-2] */
acc += (q63_t) S->A2 * S->state[1];
/* convert output to 1.31 format to add y[n-1] */
out = (q31_t) (acc >> 31u);
/* out += y[n-1] */
out += S->state[2];
/* Update state */
S->state[1] = S->state[0];
S->state[0] = in;
S->state[2] = out;
/* return to application */
return (out);
}
/**
* @brief Process function for the Q15 PID Control.
* @param[in,out] S points to an instance of the Q15 PID Control structure
* @param[in] in input sample to process
* @return out processed output sample.
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using a 64-bit internal accumulator.
* Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result.
* The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format.
* There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved.
* After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits.
* Lastly, the accumulator is saturated to yield a result in 1.15 format.
*/
static __INLINE q15_t arm_pid_q15(
arm_pid_instance_q15 * S,
q15_t in)
{
q63_t acc;
q15_t out;
#ifndef ARM_MATH_CM0_FAMILY
__SIMD32_TYPE *vstate;
/* Implementation of PID controller */
/* acc = A0 * x[n] */
acc = (q31_t) __SMUAD((uint32_t)S->A0, (uint32_t)in);
/* acc += A1 * x[n-1] + A2 * x[n-2] */
vstate = __SIMD32_CONST(S->state);
acc = (q63_t)__SMLALD((uint32_t)S->A1, (uint32_t)*vstate, (uint64_t)acc);
#else
/* acc = A0 * x[n] */
acc = ((q31_t) S->A0) * in;
/* acc += A1 * x[n-1] + A2 * x[n-2] */
acc += (q31_t) S->A1 * S->state[0];
acc += (q31_t) S->A2 * S->state[1];
#endif
/* acc += y[n-1] */
acc += (q31_t) S->state[2] << 15;
/* saturate the output */
out = (q15_t) (__SSAT((acc >> 15), 16));
/* Update state */
S->state[1] = S->state[0];
S->state[0] = in;
S->state[2] = out;
/* return to application */
return (out);
}
/**
* @} end of PID group
*/
/**
* @brief Floating-point matrix inverse.
* @param[in] src points to the instance of the input floating-point matrix structure.
* @param[out] dst points to the instance of the output floating-point matrix structure.
* @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
* If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR.
*/
arm_status arm_mat_inverse_f32(
const arm_matrix_instance_f32 * src,
arm_matrix_instance_f32 * dst);
/**
* @brief Floating-point matrix inverse.
* @param[in] src points to the instance of the input floating-point matrix structure.
* @param[out] dst points to the instance of the output floating-point matrix structure.
* @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
* If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR.
*/
arm_status arm_mat_inverse_f64(
const arm_matrix_instance_f64 * src,
arm_matrix_instance_f64 * dst);
/**
* @ingroup groupController
*/
/**
* @defgroup clarke Vector Clarke Transform
* Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector.
* Generally the Clarke transform uses three-phase currents <code>Ia, Ib and Ic</code> to calculate currents
* in the two-phase orthogonal stator axis <code>Ialpha</code> and <code>Ibeta</code>.
* When <code>Ialpha</code> is superposed with <code>Ia</code> as shown in the figure below
* \image html clarke.gif Stator current space vector and its components in (a,b).
* and <code>Ia + Ib + Ic = 0</code>, in this condition <code>Ialpha</code> and <code>Ibeta</code>
* can be calculated using only <code>Ia</code> and <code>Ib</code>.
*
* The function operates on a single sample of data and each call to the function returns the processed output.
* The library provides separate functions for Q31 and floating-point data types.
* \par Algorithm
* \image html clarkeFormula.gif
* where <code>Ia</code> and <code>Ib</code> are the instantaneous stator phases and
* <code>pIalpha</code> and <code>pIbeta</code> are the two coordinates of time invariant vector.
* \par Fixed-Point Behavior
* Care must be taken when using the Q31 version of the Clarke transform.
* In particular, the overflow and saturation behavior of the accumulator used must be considered.
* Refer to the function specific documentation below for usage guidelines.
*/
/**
* @addtogroup clarke
* @{
*/
/**
*
* @brief Floating-point Clarke transform
* @param[in] Ia input three-phase coordinate <code>a</code>
* @param[in] Ib input three-phase coordinate <code>b</code>
* @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
* @param[out] pIbeta points to output two-phase orthogonal vector axis beta
*/
static __INLINE void arm_clarke_f32(
float32_t Ia,
float32_t Ib,
float32_t * pIalpha,
float32_t * pIbeta)
{
/* Calculate pIalpha using the equation, pIalpha = Ia */
*pIalpha = Ia;
/* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */
*pIbeta = ((float32_t) 0.57735026919 * Ia + (float32_t) 1.15470053838 * Ib);
}
/**
* @brief Clarke transform for Q31 version
* @param[in] Ia input three-phase coordinate <code>a</code>
* @param[in] Ib input three-phase coordinate <code>b</code>
* @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
* @param[out] pIbeta points to output two-phase orthogonal vector axis beta
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using an internal 32-bit accumulator.
* The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
* There is saturation on the addition, hence there is no risk of overflow.
*/
static __INLINE void arm_clarke_q31(
q31_t Ia,
q31_t Ib,
q31_t * pIalpha,
q31_t * pIbeta)
{
q31_t product1, product2; /* Temporary variables used to store intermediate results */
/* Calculating pIalpha from Ia by equation pIalpha = Ia */
*pIalpha = Ia;
/* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */
product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30);
/* Intermediate product is calculated by (2/sqrt(3) * Ib) */
product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30);
/* pIbeta is calculated by adding the intermediate products */
*pIbeta = __QADD(product1, product2);
}
/**
* @} end of clarke group
*/
/**
* @brief Converts the elements of the Q7 vector to Q31 vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_q7_to_q31(
q7_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @ingroup groupController
*/
/**
* @defgroup inv_clarke Vector Inverse Clarke Transform
* Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases.
*
* The function operates on a single sample of data and each call to the function returns the processed output.
* The library provides separate functions for Q31 and floating-point data types.
* \par Algorithm
* \image html clarkeInvFormula.gif
* where <code>pIa</code> and <code>pIb</code> are the instantaneous stator phases and
* <code>Ialpha</code> and <code>Ibeta</code> are the two coordinates of time invariant vector.
* \par Fixed-Point Behavior
* Care must be taken when using the Q31 version of the Clarke transform.
* In particular, the overflow and saturation behavior of the accumulator used must be considered.
* Refer to the function specific documentation below for usage guidelines.
*/
/**
* @addtogroup inv_clarke
* @{
*/
/**
* @brief Floating-point Inverse Clarke transform
* @param[in] Ialpha input two-phase orthogonal vector axis alpha
* @param[in] Ibeta input two-phase orthogonal vector axis beta
* @param[out] pIa points to output three-phase coordinate <code>a</code>
* @param[out] pIb points to output three-phase coordinate <code>b</code>
*/
static __INLINE void arm_inv_clarke_f32(
float32_t Ialpha,
float32_t Ibeta,
float32_t * pIa,
float32_t * pIb)
{
/* Calculating pIa from Ialpha by equation pIa = Ialpha */
*pIa = Ialpha;
/* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */
*pIb = -0.5f * Ialpha + 0.8660254039f * Ibeta;
}
/**
* @brief Inverse Clarke transform for Q31 version
* @param[in] Ialpha input two-phase orthogonal vector axis alpha
* @param[in] Ibeta input two-phase orthogonal vector axis beta
* @param[out] pIa points to output three-phase coordinate <code>a</code>
* @param[out] pIb points to output three-phase coordinate <code>b</code>
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using an internal 32-bit accumulator.
* The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
* There is saturation on the subtraction, hence there is no risk of overflow.
*/
static __INLINE void arm_inv_clarke_q31(
q31_t Ialpha,
q31_t Ibeta,
q31_t * pIa,
q31_t * pIb)
{
q31_t product1, product2; /* Temporary variables used to store intermediate results */
/* Calculating pIa from Ialpha by equation pIa = Ialpha */
*pIa = Ialpha;
/* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */
product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31);
/* Intermediate product is calculated by (1/sqrt(3) * pIb) */
product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31);
/* pIb is calculated by subtracting the products */
*pIb = __QSUB(product2, product1);
}
/**
* @} end of inv_clarke group
*/
/**
* @brief Converts the elements of the Q7 vector to Q15 vector.
* @param[in] pSrc input pointer
* @param[out] pDst output pointer
* @param[in] blockSize number of samples to process
*/
void arm_q7_to_q15(
q7_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @ingroup groupController
*/
/**
* @defgroup park Vector Park Transform
*
* Forward Park transform converts the input two-coordinate vector to flux and torque components.
* The Park transform can be used to realize the transformation of the <code>Ialpha</code> and the <code>Ibeta</code> currents
* from the stationary to the moving reference frame and control the spatial relationship between
* the stator vector current and rotor flux vector.
* If we consider the d axis aligned with the rotor flux, the diagram below shows the
* current vector and the relationship from the two reference frames:
* \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame"
*
* The function operates on a single sample of data and each call to the function returns the processed output.
* The library provides separate functions for Q31 and floating-point data types.
* \par Algorithm
* \image html parkFormula.gif
* where <code>Ialpha</code> and <code>Ibeta</code> are the stator vector components,
* <code>pId</code> and <code>pIq</code> are rotor vector components and <code>cosVal</code> and <code>sinVal</code> are the
* cosine and sine values of theta (rotor flux position).
* \par Fixed-Point Behavior
* Care must be taken when using the Q31 version of the Park transform.
* In particular, the overflow and saturation behavior of the accumulator used must be considered.
* Refer to the function specific documentation below for usage guidelines.
*/
/**
* @addtogroup park
* @{
*/
/**
* @brief Floating-point Park transform
* @param[in] Ialpha input two-phase vector coordinate alpha
* @param[in] Ibeta input two-phase vector coordinate beta
* @param[out] pId points to output rotor reference frame d
* @param[out] pIq points to output rotor reference frame q
* @param[in] sinVal sine value of rotation angle theta
* @param[in] cosVal cosine value of rotation angle theta
*
* The function implements the forward Park transform.
*
*/
static __INLINE void arm_park_f32(
float32_t Ialpha,
float32_t Ibeta,
float32_t * pId,
float32_t * pIq,
float32_t sinVal,
float32_t cosVal)
{
/* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */
*pId = Ialpha * cosVal + Ibeta * sinVal;
/* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */
*pIq = -Ialpha * sinVal + Ibeta * cosVal;
}
/**
* @brief Park transform for Q31 version
* @param[in] Ialpha input two-phase vector coordinate alpha
* @param[in] Ibeta input two-phase vector coordinate beta
* @param[out] pId points to output rotor reference frame d
* @param[out] pIq points to output rotor reference frame q
* @param[in] sinVal sine value of rotation angle theta
* @param[in] cosVal cosine value of rotation angle theta
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using an internal 32-bit accumulator.
* The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
* There is saturation on the addition and subtraction, hence there is no risk of overflow.
*/
static __INLINE void arm_park_q31(
q31_t Ialpha,
q31_t Ibeta,
q31_t * pId,
q31_t * pIq,
q31_t sinVal,
q31_t cosVal)
{
q31_t product1, product2; /* Temporary variables used to store intermediate results */
q31_t product3, product4; /* Temporary variables used to store intermediate results */
/* Intermediate product is calculated by (Ialpha * cosVal) */
product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31);
/* Intermediate product is calculated by (Ibeta * sinVal) */
product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31);
/* Intermediate product is calculated by (Ialpha * sinVal) */
product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31);
/* Intermediate product is calculated by (Ibeta * cosVal) */
product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31);
/* Calculate pId by adding the two intermediate products 1 and 2 */
*pId = __QADD(product1, product2);
/* Calculate pIq by subtracting the two intermediate products 3 from 4 */
*pIq = __QSUB(product4, product3);
}
/**
* @} end of park group
*/
/**
* @brief Converts the elements of the Q7 vector to floating-point vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q7_to_float(
q7_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @ingroup groupController
*/
/**
* @defgroup inv_park Vector Inverse Park transform
* Inverse Park transform converts the input flux and torque components to two-coordinate vector.
*
* The function operates on a single sample of data and each call to the function returns the processed output.
* The library provides separate functions for Q31 and floating-point data types.
* \par Algorithm
* \image html parkInvFormula.gif
* where <code>pIalpha</code> and <code>pIbeta</code> are the stator vector components,
* <code>Id</code> and <code>Iq</code> are rotor vector components and <code>cosVal</code> and <code>sinVal</code> are the
* cosine and sine values of theta (rotor flux position).
* \par Fixed-Point Behavior
* Care must be taken when using the Q31 version of the Park transform.
* In particular, the overflow and saturation behavior of the accumulator used must be considered.
* Refer to the function specific documentation below for usage guidelines.
*/
/**
* @addtogroup inv_park
* @{
*/
/**
* @brief Floating-point Inverse Park transform
* @param[in] Id input coordinate of rotor reference frame d
* @param[in] Iq input coordinate of rotor reference frame q
* @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
* @param[out] pIbeta points to output two-phase orthogonal vector axis beta
* @param[in] sinVal sine value of rotation angle theta
* @param[in] cosVal cosine value of rotation angle theta
*/
static __INLINE void arm_inv_park_f32(
float32_t Id,
float32_t Iq,
float32_t * pIalpha,
float32_t * pIbeta,
float32_t sinVal,
float32_t cosVal)
{
/* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */
*pIalpha = Id * cosVal - Iq * sinVal;
/* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */
*pIbeta = Id * sinVal + Iq * cosVal;
}
/**
* @brief Inverse Park transform for Q31 version
* @param[in] Id input coordinate of rotor reference frame d
* @param[in] Iq input coordinate of rotor reference frame q
* @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
* @param[out] pIbeta points to output two-phase orthogonal vector axis beta
* @param[in] sinVal sine value of rotation angle theta
* @param[in] cosVal cosine value of rotation angle theta
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function is implemented using an internal 32-bit accumulator.
* The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
* There is saturation on the addition, hence there is no risk of overflow.
*/
static __INLINE void arm_inv_park_q31(
q31_t Id,
q31_t Iq,
q31_t * pIalpha,
q31_t * pIbeta,
q31_t sinVal,
q31_t cosVal)
{
q31_t product1, product2; /* Temporary variables used to store intermediate results */
q31_t product3, product4; /* Temporary variables used to store intermediate results */
/* Intermediate product is calculated by (Id * cosVal) */
product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31);
/* Intermediate product is calculated by (Iq * sinVal) */
product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31);
/* Intermediate product is calculated by (Id * sinVal) */
product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31);
/* Intermediate product is calculated by (Iq * cosVal) */
product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31);
/* Calculate pIalpha by using the two intermediate products 1 and 2 */
*pIalpha = __QSUB(product1, product2);
/* Calculate pIbeta by using the two intermediate products 3 and 4 */
*pIbeta = __QADD(product4, product3);
}
/**
* @} end of Inverse park group
*/
/**
* @brief Converts the elements of the Q31 vector to floating-point vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q31_to_float(
q31_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @ingroup groupInterpolation
*/
/**
* @defgroup LinearInterpolate Linear Interpolation
*
* Linear interpolation is a method of curve fitting using linear polynomials.
* Linear interpolation works by effectively drawing a straight line between two neighboring samples and returning the appropriate point along that line
*
* \par
* \image html LinearInterp.gif "Linear interpolation"
*
* \par
* A Linear Interpolate function calculates an output value(y), for the input(x)
* using linear interpolation of the input values x0, x1( nearest input values) and the output values y0 and y1(nearest output values)
*
* \par Algorithm:
* <pre>
* y = y0 + (x - x0) * ((y1 - y0)/(x1-x0))
* where x0, x1 are nearest values of input x
* y0, y1 are nearest values to output y
* </pre>
*
* \par
* This set of functions implements Linear interpolation process
* for Q7, Q15, Q31, and floating-point data types. The functions operate on a single
* sample of data and each call to the function returns a single processed value.
* <code>S</code> points to an instance of the Linear Interpolate function data structure.
* <code>x</code> is the input sample value. The functions returns the output value.
*
* \par
* if x is outside of the table boundary, Linear interpolation returns first value of the table
* if x is below input range and returns last value of table if x is above range.
*/
/**
* @addtogroup LinearInterpolate
* @{
*/
/**
* @brief Process function for the floating-point Linear Interpolation Function.
* @param[in,out] S is an instance of the floating-point Linear Interpolation structure
* @param[in] x input sample to process
* @return y processed output sample.
*
*/
static __INLINE float32_t arm_linear_interp_f32(
arm_linear_interp_instance_f32 * S,
float32_t x)
{
float32_t y;
float32_t x0, x1; /* Nearest input values */
float32_t y0, y1; /* Nearest output values */
float32_t xSpacing = S->xSpacing; /* spacing between input values */
int32_t i; /* Index variable */
float32_t *pYData = S->pYData; /* pointer to output table */
/* Calculation of index */
i = (int32_t) ((x - S->x1) / xSpacing);
if(i < 0)
{
/* Iniatilize output for below specified range as least output value of table */
y = pYData[0];
}
else if((uint32_t)i >= S->nValues)
{
/* Iniatilize output for above specified range as last output value of table */
y = pYData[S->nValues - 1];
}
else
{
/* Calculation of nearest input values */
x0 = S->x1 + i * xSpacing;
x1 = S->x1 + (i + 1) * xSpacing;
/* Read of nearest output values */
y0 = pYData[i];
y1 = pYData[i + 1];
/* Calculation of output */
y = y0 + (x - x0) * ((y1 - y0) / (x1 - x0));
}
/* returns output value */
return (y);
}
/**
*
* @brief Process function for the Q31 Linear Interpolation Function.
* @param[in] pYData pointer to Q31 Linear Interpolation table
* @param[in] x input sample to process
* @param[in] nValues number of table values
* @return y processed output sample.
*
* \par
* Input sample <code>x</code> is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
* This function can support maximum of table size 2^12.
*
*/
static __INLINE q31_t arm_linear_interp_q31(
q31_t * pYData,
q31_t x,
uint32_t nValues)
{
q31_t y; /* output */
q31_t y0, y1; /* Nearest output values */
q31_t fract; /* fractional part */
int32_t index; /* Index to read nearest output values */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
index = ((x & (q31_t)0xFFF00000) >> 20);
if(index >= (int32_t)(nValues - 1))
{
return (pYData[nValues - 1]);
}
else if(index < 0)
{
return (pYData[0]);
}
else
{
/* 20 bits for the fractional part */
/* shift left by 11 to keep fract in 1.31 format */
fract = (x & 0x000FFFFF) << 11;
/* Read two nearest output values from the index in 1.31(q31) format */
y0 = pYData[index];
y1 = pYData[index + 1];
/* Calculation of y0 * (1-fract) and y is in 2.30 format */
y = ((q31_t) ((q63_t) y0 * (0x7FFFFFFF - fract) >> 32));
/* Calculation of y0 * (1-fract) + y1 *fract and y is in 2.30 format */
y += ((q31_t) (((q63_t) y1 * fract) >> 32));
/* Convert y to 1.31 format */
return (y << 1u);
}
}
/**
*
* @brief Process function for the Q15 Linear Interpolation Function.
* @param[in] pYData pointer to Q15 Linear Interpolation table
* @param[in] x input sample to process
* @param[in] nValues number of table values
* @return y processed output sample.
*
* \par
* Input sample <code>x</code> is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
* This function can support maximum of table size 2^12.
*
*/
static __INLINE q15_t arm_linear_interp_q15(
q15_t * pYData,
q31_t x,
uint32_t nValues)
{
q63_t y; /* output */
q15_t y0, y1; /* Nearest output values */
q31_t fract; /* fractional part */
int32_t index; /* Index to read nearest output values */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
index = ((x & (int32_t)0xFFF00000) >> 20);
if(index >= (int32_t)(nValues - 1))
{
return (pYData[nValues - 1]);
}
else if(index < 0)
{
return (pYData[0]);
}
else
{
/* 20 bits for the fractional part */
/* fract is in 12.20 format */
fract = (x & 0x000FFFFF);
/* Read two nearest output values from the index */
y0 = pYData[index];
y1 = pYData[index + 1];
/* Calculation of y0 * (1-fract) and y is in 13.35 format */
y = ((q63_t) y0 * (0xFFFFF - fract));
/* Calculation of (y0 * (1-fract) + y1 * fract) and y is in 13.35 format */
y += ((q63_t) y1 * (fract));
/* convert y to 1.15 format */
return (q15_t) (y >> 20);
}
}
/**
*
* @brief Process function for the Q7 Linear Interpolation Function.
* @param[in] pYData pointer to Q7 Linear Interpolation table
* @param[in] x input sample to process
* @param[in] nValues number of table values
* @return y processed output sample.
*
* \par
* Input sample <code>x</code> is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
* This function can support maximum of table size 2^12.
*/
static __INLINE q7_t arm_linear_interp_q7(
q7_t * pYData,
q31_t x,
uint32_t nValues)
{
q31_t y; /* output */
q7_t y0, y1; /* Nearest output values */
q31_t fract; /* fractional part */
uint32_t index; /* Index to read nearest output values */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
if (x < 0)
{
return (pYData[0]);
}
index = (x >> 20) & 0xfff;
if(index >= (nValues - 1))
{
return (pYData[nValues - 1]);
}
else
{
/* 20 bits for the fractional part */
/* fract is in 12.20 format */
fract = (x & 0x000FFFFF);
/* Read two nearest output values from the index and are in 1.7(q7) format */
y0 = pYData[index];
y1 = pYData[index + 1];
/* Calculation of y0 * (1-fract ) and y is in 13.27(q27) format */
y = ((y0 * (0xFFFFF - fract)));
/* Calculation of y1 * fract + y0 * (1-fract) and y is in 13.27(q27) format */
y += (y1 * fract);
/* convert y to 1.7(q7) format */
return (q7_t) (y >> 20);
}
}
/**
* @} end of LinearInterpolate group
*/
/**
* @brief Fast approximation to the trigonometric sine function for floating-point data.
* @param[in] x input value in radians.
* @return sin(x).
*/
float32_t arm_sin_f32(
float32_t x);
/**
* @brief Fast approximation to the trigonometric sine function for Q31 data.
* @param[in] x Scaled input value in radians.
* @return sin(x).
*/
q31_t arm_sin_q31(
q31_t x);
/**
* @brief Fast approximation to the trigonometric sine function for Q15 data.
* @param[in] x Scaled input value in radians.
* @return sin(x).
*/
q15_t arm_sin_q15(
q15_t x);
/**
* @brief Fast approximation to the trigonometric cosine function for floating-point data.
* @param[in] x input value in radians.
* @return cos(x).
*/
float32_t arm_cos_f32(
float32_t x);
/**
* @brief Fast approximation to the trigonometric cosine function for Q31 data.
* @param[in] x Scaled input value in radians.
* @return cos(x).
*/
q31_t arm_cos_q31(
q31_t x);
/**
* @brief Fast approximation to the trigonometric cosine function for Q15 data.
* @param[in] x Scaled input value in radians.
* @return cos(x).
*/
q15_t arm_cos_q15(
q15_t x);
/**
* @ingroup groupFastMath
*/
/**
* @defgroup SQRT Square Root
*
* Computes the square root of a number.
* There are separate functions for Q15, Q31, and floating-point data types.
* The square root function is computed using the Newton-Raphson algorithm.
* This is an iterative algorithm of the form:
* <pre>
* x1 = x0 - f(x0)/f'(x0)
* </pre>
* where <code>x1</code> is the current estimate,
* <code>x0</code> is the previous estimate, and
* <code>f'(x0)</code> is the derivative of <code>f()</code> evaluated at <code>x0</code>.
* For the square root function, the algorithm reduces to:
* <pre>
* x0 = in/2 [initial guess]
* x1 = 1/2 * ( x0 + in / x0) [each iteration]
* </pre>
*/
/**
* @addtogroup SQRT
* @{
*/
/**
* @brief Floating-point square root function.
* @param[in] in input value.
* @param[out] pOut square root of input value.
* @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if
* <code>in</code> is negative value and returns zero output for negative values.
*/
static __INLINE arm_status arm_sqrt_f32(
float32_t in,
float32_t * pOut)
{
if(in >= 0.0f)
{
#if (__FPU_USED == 1) && defined ( __CC_ARM )
*pOut = __sqrtf(in);
#elif (__FPU_USED == 1) && (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))
*pOut = __builtin_sqrtf(in);
#elif (__FPU_USED == 1) && defined(__GNUC__)
*pOut = __builtin_sqrtf(in);
#elif (__FPU_USED == 1) && defined ( __ICCARM__ ) && (__VER__ >= 6040000)
__ASM("VSQRT.F32 %0,%1" : "=t"(*pOut) : "t"(in));
#else
*pOut = sqrtf(in);
#endif
return (ARM_MATH_SUCCESS);
}
else
{
*pOut = 0.0f;
return (ARM_MATH_ARGUMENT_ERROR);
}
}
/**
* @brief Q31 square root function.
* @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF.
* @param[out] pOut square root of input value.
* @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if
* <code>in</code> is negative value and returns zero output for negative values.
*/
arm_status arm_sqrt_q31(
q31_t in,
q31_t * pOut);
/**
* @brief Q15 square root function.
* @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF.
* @param[out] pOut square root of input value.
* @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if
* <code>in</code> is negative value and returns zero output for negative values.
*/
arm_status arm_sqrt_q15(
q15_t in,
q15_t * pOut);
/**
* @} end of SQRT group
*/
/**
* @brief floating-point Circular write function.
*/
static __INLINE void arm_circularWrite_f32(
int32_t * circBuffer,
int32_t L,
uint16_t * writeOffset,
int32_t bufferInc,
const int32_t * src,
int32_t srcInc,
uint32_t blockSize)
{
uint32_t i = 0u;
int32_t wOffset;
/* Copy the value of Index pointer that points
* to the current location where the input samples to be copied */
wOffset = *writeOffset;
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the input sample to the circular buffer */
circBuffer[wOffset] = *src;
/* Update the input pointer */
src += srcInc;
/* Circularly update wOffset. Watch out for positive and negative value */
wOffset += bufferInc;
if(wOffset >= L)
wOffset -= L;
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*writeOffset = (uint16_t)wOffset;
}
/**
* @brief floating-point Circular Read function.
*/
static __INLINE void arm_circularRead_f32(
int32_t * circBuffer,
int32_t L,
int32_t * readOffset,
int32_t bufferInc,
int32_t * dst,
int32_t * dst_base,
int32_t dst_length,
int32_t dstInc,
uint32_t blockSize)
{
uint32_t i = 0u;
int32_t rOffset, dst_end;
/* Copy the value of Index pointer that points
* to the current location from where the input samples to be read */
rOffset = *readOffset;
dst_end = (int32_t) (dst_base + dst_length);
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the sample from the circular buffer to the destination buffer */
*dst = circBuffer[rOffset];
/* Update the input pointer */
dst += dstInc;
if(dst == (int32_t *) dst_end)
{
dst = dst_base;
}
/* Circularly update rOffset. Watch out for positive and negative value */
rOffset += bufferInc;
if(rOffset >= L)
{
rOffset -= L;
}
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*readOffset = rOffset;
}
/**
* @brief Q15 Circular write function.
*/
static __INLINE void arm_circularWrite_q15(
q15_t * circBuffer,
int32_t L,
uint16_t * writeOffset,
int32_t bufferInc,
const q15_t * src,
int32_t srcInc,
uint32_t blockSize)
{
uint32_t i = 0u;
int32_t wOffset;
/* Copy the value of Index pointer that points
* to the current location where the input samples to be copied */
wOffset = *writeOffset;
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the input sample to the circular buffer */
circBuffer[wOffset] = *src;
/* Update the input pointer */
src += srcInc;
/* Circularly update wOffset. Watch out for positive and negative value */
wOffset += bufferInc;
if(wOffset >= L)
wOffset -= L;
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*writeOffset = (uint16_t)wOffset;
}
/**
* @brief Q15 Circular Read function.
*/
static __INLINE void arm_circularRead_q15(
q15_t * circBuffer,
int32_t L,
int32_t * readOffset,
int32_t bufferInc,
q15_t * dst,
q15_t * dst_base,
int32_t dst_length,
int32_t dstInc,
uint32_t blockSize)
{
uint32_t i = 0;
int32_t rOffset, dst_end;
/* Copy the value of Index pointer that points
* to the current location from where the input samples to be read */
rOffset = *readOffset;
dst_end = (int32_t) (dst_base + dst_length);
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the sample from the circular buffer to the destination buffer */
*dst = circBuffer[rOffset];
/* Update the input pointer */
dst += dstInc;
if(dst == (q15_t *) dst_end)
{
dst = dst_base;
}
/* Circularly update wOffset. Watch out for positive and negative value */
rOffset += bufferInc;
if(rOffset >= L)
{
rOffset -= L;
}
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*readOffset = rOffset;
}
/**
* @brief Q7 Circular write function.
*/
static __INLINE void arm_circularWrite_q7(
q7_t * circBuffer,
int32_t L,
uint16_t * writeOffset,
int32_t bufferInc,
const q7_t * src,
int32_t srcInc,
uint32_t blockSize)
{
uint32_t i = 0u;
int32_t wOffset;
/* Copy the value of Index pointer that points
* to the current location where the input samples to be copied */
wOffset = *writeOffset;
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the input sample to the circular buffer */
circBuffer[wOffset] = *src;
/* Update the input pointer */
src += srcInc;
/* Circularly update wOffset. Watch out for positive and negative value */
wOffset += bufferInc;
if(wOffset >= L)
wOffset -= L;
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*writeOffset = (uint16_t)wOffset;
}
/**
* @brief Q7 Circular Read function.
*/
static __INLINE void arm_circularRead_q7(
q7_t * circBuffer,
int32_t L,
int32_t * readOffset,
int32_t bufferInc,
q7_t * dst,
q7_t * dst_base,
int32_t dst_length,
int32_t dstInc,
uint32_t blockSize)
{
uint32_t i = 0;
int32_t rOffset, dst_end;
/* Copy the value of Index pointer that points
* to the current location from where the input samples to be read */
rOffset = *readOffset;
dst_end = (int32_t) (dst_base + dst_length);
/* Loop over the blockSize */
i = blockSize;
while(i > 0u)
{
/* copy the sample from the circular buffer to the destination buffer */
*dst = circBuffer[rOffset];
/* Update the input pointer */
dst += dstInc;
if(dst == (q7_t *) dst_end)
{
dst = dst_base;
}
/* Circularly update rOffset. Watch out for positive and negative value */
rOffset += bufferInc;
if(rOffset >= L)
{
rOffset -= L;
}
/* Decrement the loop counter */
i--;
}
/* Update the index pointer */
*readOffset = rOffset;
}
/**
* @brief Sum of the squares of the elements of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_power_q31(
q31_t * pSrc,
uint32_t blockSize,
q63_t * pResult);
/**
* @brief Sum of the squares of the elements of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_power_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult);
/**
* @brief Sum of the squares of the elements of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_power_q15(
q15_t * pSrc,
uint32_t blockSize,
q63_t * pResult);
/**
* @brief Sum of the squares of the elements of a Q7 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_power_q7(
q7_t * pSrc,
uint32_t blockSize,
q31_t * pResult);
/**
* @brief Mean value of a Q7 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_mean_q7(
q7_t * pSrc,
uint32_t blockSize,
q7_t * pResult);
/**
* @brief Mean value of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_mean_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult);
/**
* @brief Mean value of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_mean_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult);
/**
* @brief Mean value of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_mean_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult);
/**
* @brief Variance of the elements of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_var_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult);
/**
* @brief Variance of the elements of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_var_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult);
/**
* @brief Variance of the elements of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_var_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult);
/**
* @brief Root Mean Square of the elements of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_rms_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult);
/**
* @brief Root Mean Square of the elements of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_rms_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult);
/**
* @brief Root Mean Square of the elements of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_rms_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult);
/**
* @brief Standard deviation of the elements of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_std_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult);
/**
* @brief Standard deviation of the elements of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_std_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult);
/**
* @brief Standard deviation of the elements of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output value.
*/
void arm_std_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult);
/**
* @brief Floating-point complex magnitude
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_f32(
float32_t * pSrc,
float32_t * pDst,
uint32_t numSamples);
/**
* @brief Q31 complex magnitude
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_q31(
q31_t * pSrc,
q31_t * pDst,
uint32_t numSamples);
/**
* @brief Q15 complex magnitude
* @param[in] pSrc points to the complex input vector
* @param[out] pDst points to the real output vector
* @param[in] numSamples number of complex samples in the input vector
*/
void arm_cmplx_mag_q15(
q15_t * pSrc,
q15_t * pDst,
uint32_t numSamples);
/**
* @brief Q15 complex dot product
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] numSamples number of complex samples in each vector
* @param[out] realResult real part of the result returned here
* @param[out] imagResult imaginary part of the result returned here
*/
void arm_cmplx_dot_prod_q15(
q15_t * pSrcA,
q15_t * pSrcB,
uint32_t numSamples,
q31_t * realResult,
q31_t * imagResult);
/**
* @brief Q31 complex dot product
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] numSamples number of complex samples in each vector
* @param[out] realResult real part of the result returned here
* @param[out] imagResult imaginary part of the result returned here
*/
void arm_cmplx_dot_prod_q31(
q31_t * pSrcA,
q31_t * pSrcB,
uint32_t numSamples,
q63_t * realResult,
q63_t * imagResult);
/**
* @brief Floating-point complex dot product
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] numSamples number of complex samples in each vector
* @param[out] realResult real part of the result returned here
* @param[out] imagResult imaginary part of the result returned here
*/
void arm_cmplx_dot_prod_f32(
float32_t * pSrcA,
float32_t * pSrcB,
uint32_t numSamples,
float32_t * realResult,
float32_t * imagResult);
/**
* @brief Q15 complex-by-real multiplication
* @param[in] pSrcCmplx points to the complex input vector
* @param[in] pSrcReal points to the real input vector
* @param[out] pCmplxDst points to the complex output vector
* @param[in] numSamples number of samples in each vector
*/
void arm_cmplx_mult_real_q15(
q15_t * pSrcCmplx,
q15_t * pSrcReal,
q15_t * pCmplxDst,
uint32_t numSamples);
/**
* @brief Q31 complex-by-real multiplication
* @param[in] pSrcCmplx points to the complex input vector
* @param[in] pSrcReal points to the real input vector
* @param[out] pCmplxDst points to the complex output vector
* @param[in] numSamples number of samples in each vector
*/
void arm_cmplx_mult_real_q31(
q31_t * pSrcCmplx,
q31_t * pSrcReal,
q31_t * pCmplxDst,
uint32_t numSamples);
/**
* @brief Floating-point complex-by-real multiplication
* @param[in] pSrcCmplx points to the complex input vector
* @param[in] pSrcReal points to the real input vector
* @param[out] pCmplxDst points to the complex output vector
* @param[in] numSamples number of samples in each vector
*/
void arm_cmplx_mult_real_f32(
float32_t * pSrcCmplx,
float32_t * pSrcReal,
float32_t * pCmplxDst,
uint32_t numSamples);
/**
* @brief Minimum value of a Q7 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] result is output pointer
* @param[in] index is the array index of the minimum value in the input buffer.
*/
void arm_min_q7(
q7_t * pSrc,
uint32_t blockSize,
q7_t * result,
uint32_t * index);
/**
* @brief Minimum value of a Q15 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output pointer
* @param[in] pIndex is the array index of the minimum value in the input buffer.
*/
void arm_min_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult,
uint32_t * pIndex);
/**
* @brief Minimum value of a Q31 vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output pointer
* @param[out] pIndex is the array index of the minimum value in the input buffer.
*/
void arm_min_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult,
uint32_t * pIndex);
/**
* @brief Minimum value of a floating-point vector.
* @param[in] pSrc is input pointer
* @param[in] blockSize is the number of samples to process
* @param[out] pResult is output pointer
* @param[out] pIndex is the array index of the minimum value in the input buffer.
*/
void arm_min_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult,
uint32_t * pIndex);
/**
* @brief Maximum value of a Q7 vector.
* @param[in] pSrc points to the input buffer
* @param[in] blockSize length of the input vector
* @param[out] pResult maximum value returned here
* @param[out] pIndex index of maximum value returned here
*/
void arm_max_q7(
q7_t * pSrc,
uint32_t blockSize,
q7_t * pResult,
uint32_t * pIndex);
/**
* @brief Maximum value of a Q15 vector.
* @param[in] pSrc points to the input buffer
* @param[in] blockSize length of the input vector
* @param[out] pResult maximum value returned here
* @param[out] pIndex index of maximum value returned here
*/
void arm_max_q15(
q15_t * pSrc,
uint32_t blockSize,
q15_t * pResult,
uint32_t * pIndex);
/**
* @brief Maximum value of a Q31 vector.
* @param[in] pSrc points to the input buffer
* @param[in] blockSize length of the input vector
* @param[out] pResult maximum value returned here
* @param[out] pIndex index of maximum value returned here
*/
void arm_max_q31(
q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult,
uint32_t * pIndex);
/**
* @brief Maximum value of a floating-point vector.
* @param[in] pSrc points to the input buffer
* @param[in] blockSize length of the input vector
* @param[out] pResult maximum value returned here
* @param[out] pIndex index of maximum value returned here
*/
void arm_max_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult,
uint32_t * pIndex);
/**
* @brief Q15 complex-by-complex multiplication
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_mult_cmplx_q15(
q15_t * pSrcA,
q15_t * pSrcB,
q15_t * pDst,
uint32_t numSamples);
/**
* @brief Q31 complex-by-complex multiplication
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_mult_cmplx_q31(
q31_t * pSrcA,
q31_t * pSrcB,
q31_t * pDst,
uint32_t numSamples);
/**
* @brief Floating-point complex-by-complex multiplication
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] numSamples number of complex samples in each vector
*/
void arm_cmplx_mult_cmplx_f32(
float32_t * pSrcA,
float32_t * pSrcB,
float32_t * pDst,
uint32_t numSamples);
/**
* @brief Converts the elements of the floating-point vector to Q31 vector.
* @param[in] pSrc points to the floating-point input vector
* @param[out] pDst points to the Q31 output vector
* @param[in] blockSize length of the input vector
*/
void arm_float_to_q31(
float32_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the floating-point vector to Q15 vector.
* @param[in] pSrc points to the floating-point input vector
* @param[out] pDst points to the Q15 output vector
* @param[in] blockSize length of the input vector
*/
void arm_float_to_q15(
float32_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the floating-point vector to Q7 vector.
* @param[in] pSrc points to the floating-point input vector
* @param[out] pDst points to the Q7 output vector
* @param[in] blockSize length of the input vector
*/
void arm_float_to_q7(
float32_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the Q31 vector to Q15 vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q31_to_q15(
q31_t * pSrc,
q15_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the Q31 vector to Q7 vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q31_to_q7(
q31_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the Q15 vector to floating-point vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q15_to_float(
q15_t * pSrc,
float32_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the Q15 vector to Q31 vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q15_to_q31(
q15_t * pSrc,
q31_t * pDst,
uint32_t blockSize);
/**
* @brief Converts the elements of the Q15 vector to Q7 vector.
* @param[in] pSrc is input pointer
* @param[out] pDst is output pointer
* @param[in] blockSize is the number of samples to process
*/
void arm_q15_to_q7(
q15_t * pSrc,
q7_t * pDst,
uint32_t blockSize);
/**
* @ingroup groupInterpolation
*/
/**
* @defgroup BilinearInterpolate Bilinear Interpolation
*
* Bilinear interpolation is an extension of linear interpolation applied to a two dimensional grid.
* The underlying function <code>f(x, y)</code> is sampled on a regular grid and the interpolation process
* determines values between the grid points.
* Bilinear interpolation is equivalent to two step linear interpolation, first in the x-dimension and then in the y-dimension.
* Bilinear interpolation is often used in image processing to rescale images.
* The CMSIS DSP library provides bilinear interpolation functions for Q7, Q15, Q31, and floating-point data types.
*
* <b>Algorithm</b>
* \par
* The instance structure used by the bilinear interpolation functions describes a two dimensional data table.
* For floating-point, the instance structure is defined as:
* <pre>
* typedef struct
* {
* uint16_t numRows;
* uint16_t numCols;
* float32_t *pData;
* } arm_bilinear_interp_instance_f32;
* </pre>
*
* \par
* where <code>numRows</code> specifies the number of rows in the table;
* <code>numCols</code> specifies the number of columns in the table;
* and <code>pData</code> points to an array of size <code>numRows*numCols</code> values.
* The data table <code>pTable</code> is organized in row order and the supplied data values fall on integer indexes.
* That is, table element (x,y) is located at <code>pTable[x + y*numCols]</code> where x and y are integers.
*
* \par
* Let <code>(x, y)</code> specify the desired interpolation point. Then define:
* <pre>
* XF = floor(x)
* YF = floor(y)
* </pre>
* \par
* The interpolated output point is computed as:
* <pre>
* f(x, y) = f(XF, YF) * (1-(x-XF)) * (1-(y-YF))
* + f(XF+1, YF) * (x-XF)*(1-(y-YF))
* + f(XF, YF+1) * (1-(x-XF))*(y-YF)
* + f(XF+1, YF+1) * (x-XF)*(y-YF)
* </pre>
* Note that the coordinates (x, y) contain integer and fractional components.
* The integer components specify which portion of the table to use while the
* fractional components control the interpolation processor.
*
* \par
* if (x,y) are outside of the table boundary, Bilinear interpolation returns zero output.
*/
/**
* @addtogroup BilinearInterpolate
* @{
*/
/**
*
* @brief Floating-point bilinear interpolation.
* @param[in,out] S points to an instance of the interpolation structure.
* @param[in] X interpolation coordinate.
* @param[in] Y interpolation coordinate.
* @return out interpolated value.
*/
static __INLINE float32_t arm_bilinear_interp_f32(
const arm_bilinear_interp_instance_f32 * S,
float32_t X,
float32_t Y)
{
float32_t out;
float32_t f00, f01, f10, f11;
float32_t *pData = S->pData;
int32_t xIndex, yIndex, index;
float32_t xdiff, ydiff;
float32_t b1, b2, b3, b4;
xIndex = (int32_t) X;
yIndex = (int32_t) Y;
/* Care taken for table outside boundary */
/* Returns zero output when values are outside table boundary */
if(xIndex < 0 || xIndex > (S->numRows - 1) || yIndex < 0 || yIndex > (S->numCols - 1))
{
return (0);
}
/* Calculation of index for two nearest points in X-direction */
index = (xIndex - 1) + (yIndex - 1) * S->numCols;
/* Read two nearest points in X-direction */
f00 = pData[index];
f01 = pData[index + 1];
/* Calculation of index for two nearest points in Y-direction */
index = (xIndex - 1) + (yIndex) * S->numCols;
/* Read two nearest points in Y-direction */
f10 = pData[index];
f11 = pData[index + 1];
/* Calculation of intermediate values */
b1 = f00;
b2 = f01 - f00;
b3 = f10 - f00;
b4 = f00 - f01 - f10 + f11;
/* Calculation of fractional part in X */
xdiff = X - xIndex;
/* Calculation of fractional part in Y */
ydiff = Y - yIndex;
/* Calculation of bi-linear interpolated output */
out = b1 + b2 * xdiff + b3 * ydiff + b4 * xdiff * ydiff;
/* return to application */
return (out);
}
/**
*
* @brief Q31 bilinear interpolation.
* @param[in,out] S points to an instance of the interpolation structure.
* @param[in] X interpolation coordinate in 12.20 format.
* @param[in] Y interpolation coordinate in 12.20 format.
* @return out interpolated value.
*/
static __INLINE q31_t arm_bilinear_interp_q31(
arm_bilinear_interp_instance_q31 * S,
q31_t X,
q31_t Y)
{
q31_t out; /* Temporary output */
q31_t acc = 0; /* output */
q31_t xfract, yfract; /* X, Y fractional parts */
q31_t x1, x2, y1, y2; /* Nearest output values */
int32_t rI, cI; /* Row and column indices */
q31_t *pYData = S->pData; /* pointer to output table values */
uint32_t nCols = S->numCols; /* num of rows */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
rI = ((X & (q31_t)0xFFF00000) >> 20);
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
cI = ((Y & (q31_t)0xFFF00000) >> 20);
/* Care taken for table outside boundary */
/* Returns zero output when values are outside table boundary */
if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1))
{
return (0);
}
/* 20 bits for the fractional part */
/* shift left xfract by 11 to keep 1.31 format */
xfract = (X & 0x000FFFFF) << 11u;
/* Read two nearest output values from the index */
x1 = pYData[(rI) + (int32_t)nCols * (cI) ];
x2 = pYData[(rI) + (int32_t)nCols * (cI) + 1];
/* 20 bits for the fractional part */
/* shift left yfract by 11 to keep 1.31 format */
yfract = (Y & 0x000FFFFF) << 11u;
/* Read two nearest output values from the index */
y1 = pYData[(rI) + (int32_t)nCols * (cI + 1) ];
y2 = pYData[(rI) + (int32_t)nCols * (cI + 1) + 1];
/* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 3.29(q29) format */
out = ((q31_t) (((q63_t) x1 * (0x7FFFFFFF - xfract)) >> 32));
acc = ((q31_t) (((q63_t) out * (0x7FFFFFFF - yfract)) >> 32));
/* x2 * (xfract) * (1-yfract) in 3.29(q29) and adding to acc */
out = ((q31_t) ((q63_t) x2 * (0x7FFFFFFF - yfract) >> 32));
acc += ((q31_t) ((q63_t) out * (xfract) >> 32));
/* y1 * (1 - xfract) * (yfract) in 3.29(q29) and adding to acc */
out = ((q31_t) ((q63_t) y1 * (0x7FFFFFFF - xfract) >> 32));
acc += ((q31_t) ((q63_t) out * (yfract) >> 32));
/* y2 * (xfract) * (yfract) in 3.29(q29) and adding to acc */
out = ((q31_t) ((q63_t) y2 * (xfract) >> 32));
acc += ((q31_t) ((q63_t) out * (yfract) >> 32));
/* Convert acc to 1.31(q31) format */
return ((q31_t)(acc << 2));
}
/**
* @brief Q15 bilinear interpolation.
* @param[in,out] S points to an instance of the interpolation structure.
* @param[in] X interpolation coordinate in 12.20 format.
* @param[in] Y interpolation coordinate in 12.20 format.
* @return out interpolated value.
*/
static __INLINE q15_t arm_bilinear_interp_q15(
arm_bilinear_interp_instance_q15 * S,
q31_t X,
q31_t Y)
{
q63_t acc = 0; /* output */
q31_t out; /* Temporary output */
q15_t x1, x2, y1, y2; /* Nearest output values */
q31_t xfract, yfract; /* X, Y fractional parts */
int32_t rI, cI; /* Row and column indices */
q15_t *pYData = S->pData; /* pointer to output table values */
uint32_t nCols = S->numCols; /* num of rows */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
rI = ((X & (q31_t)0xFFF00000) >> 20);
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
cI = ((Y & (q31_t)0xFFF00000) >> 20);
/* Care taken for table outside boundary */
/* Returns zero output when values are outside table boundary */
if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1))
{
return (0);
}
/* 20 bits for the fractional part */
/* xfract should be in 12.20 format */
xfract = (X & 0x000FFFFF);
/* Read two nearest output values from the index */
x1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) ];
x2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) + 1];
/* 20 bits for the fractional part */
/* yfract should be in 12.20 format */
yfract = (Y & 0x000FFFFF);
/* Read two nearest output values from the index */
y1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) ];
y2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) + 1];
/* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 13.51 format */
/* x1 is in 1.15(q15), xfract in 12.20 format and out is in 13.35 format */
/* convert 13.35 to 13.31 by right shifting and out is in 1.31 */
out = (q31_t) (((q63_t) x1 * (0xFFFFF - xfract)) >> 4u);
acc = ((q63_t) out * (0xFFFFF - yfract));
/* x2 * (xfract) * (1-yfract) in 1.51 and adding to acc */
out = (q31_t) (((q63_t) x2 * (0xFFFFF - yfract)) >> 4u);
acc += ((q63_t) out * (xfract));
/* y1 * (1 - xfract) * (yfract) in 1.51 and adding to acc */
out = (q31_t) (((q63_t) y1 * (0xFFFFF - xfract)) >> 4u);
acc += ((q63_t) out * (yfract));
/* y2 * (xfract) * (yfract) in 1.51 and adding to acc */
out = (q31_t) (((q63_t) y2 * (xfract)) >> 4u);
acc += ((q63_t) out * (yfract));
/* acc is in 13.51 format and down shift acc by 36 times */
/* Convert out to 1.15 format */
return ((q15_t)(acc >> 36));
}
/**
* @brief Q7 bilinear interpolation.
* @param[in,out] S points to an instance of the interpolation structure.
* @param[in] X interpolation coordinate in 12.20 format.
* @param[in] Y interpolation coordinate in 12.20 format.
* @return out interpolated value.
*/
static __INLINE q7_t arm_bilinear_interp_q7(
arm_bilinear_interp_instance_q7 * S,
q31_t X,
q31_t Y)
{
q63_t acc = 0; /* output */
q31_t out; /* Temporary output */
q31_t xfract, yfract; /* X, Y fractional parts */
q7_t x1, x2, y1, y2; /* Nearest output values */
int32_t rI, cI; /* Row and column indices */
q7_t *pYData = S->pData; /* pointer to output table values */
uint32_t nCols = S->numCols; /* num of rows */
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
rI = ((X & (q31_t)0xFFF00000) >> 20);
/* Input is in 12.20 format */
/* 12 bits for the table index */
/* Index value calculation */
cI = ((Y & (q31_t)0xFFF00000) >> 20);
/* Care taken for table outside boundary */
/* Returns zero output when values are outside table boundary */
if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1))
{
return (0);
}
/* 20 bits for the fractional part */
/* xfract should be in 12.20 format */
xfract = (X & (q31_t)0x000FFFFF);
/* Read two nearest output values from the index */
x1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) ];
x2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) + 1];
/* 20 bits for the fractional part */
/* yfract should be in 12.20 format */
yfract = (Y & (q31_t)0x000FFFFF);
/* Read two nearest output values from the index */
y1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) ];
y2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) + 1];
/* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 16.47 format */
out = ((x1 * (0xFFFFF - xfract)));
acc = (((q63_t) out * (0xFFFFF - yfract)));
/* x2 * (xfract) * (1-yfract) in 2.22 and adding to acc */
out = ((x2 * (0xFFFFF - yfract)));
acc += (((q63_t) out * (xfract)));
/* y1 * (1 - xfract) * (yfract) in 2.22 and adding to acc */
out = ((y1 * (0xFFFFF - xfract)));
acc += (((q63_t) out * (yfract)));
/* y2 * (xfract) * (yfract) in 2.22 and adding to acc */
out = ((y2 * (yfract)));
acc += (((q63_t) out * (xfract)));
/* acc in 16.47 format and down shift by 40 to convert to 1.7 format */
return ((q7_t)(acc >> 40));
}
/**
* @} end of BilinearInterpolate group
*/
/* SMMLAR */
#define multAcc_32x32_keep32_R(a, x, y) \
a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32)
/* SMMLSR */
#define multSub_32x32_keep32_R(a, x, y) \
a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32)
/* SMMULR */
#define mult_32x32_keep32_R(a, x, y) \
a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32)
/* SMMLA */
#define multAcc_32x32_keep32(a, x, y) \
a += (q31_t) (((q63_t) x * y) >> 32)
/* SMMLS */
#define multSub_32x32_keep32(a, x, y) \
a -= (q31_t) (((q63_t) x * y) >> 32)
/* SMMUL */
#define mult_32x32_keep32(a, x, y) \
a = (q31_t) (((q63_t) x * y ) >> 32)
#if defined ( __CC_ARM )
/* Enter low optimization region - place directly above function definition */
#if defined( ARM_MATH_CM4 ) || defined( ARM_MATH_CM7)
#define LOW_OPTIMIZATION_ENTER \
_Pragma ("push") \
_Pragma ("O1")
#else
#define LOW_OPTIMIZATION_ENTER
#endif
/* Exit low optimization region - place directly after end of function definition */
#if defined( ARM_MATH_CM4 ) || defined( ARM_MATH_CM7)
#define LOW_OPTIMIZATION_EXIT \
_Pragma ("pop")
#else
#define LOW_OPTIMIZATION_EXIT
#endif
/* Enter low optimization region - place directly above function definition */
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
/* Exit low optimization region - place directly after end of function definition */
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define LOW_OPTIMIZATION_ENTER
#define LOW_OPTIMIZATION_EXIT
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#elif defined(__GNUC__)
#define LOW_OPTIMIZATION_ENTER __attribute__(( optimize("-O1") ))
#define LOW_OPTIMIZATION_EXIT
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#elif defined(__ICCARM__)
/* Enter low optimization region - place directly above function definition */
#if defined( ARM_MATH_CM4 ) || defined( ARM_MATH_CM7)
#define LOW_OPTIMIZATION_ENTER \
_Pragma ("optimize=low")
#else
#define LOW_OPTIMIZATION_ENTER
#endif
/* Exit low optimization region - place directly after end of function definition */
#define LOW_OPTIMIZATION_EXIT
/* Enter low optimization region - place directly above function definition */
#if defined( ARM_MATH_CM4 ) || defined( ARM_MATH_CM7)
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER \
_Pragma ("optimize=low")
#else
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
#endif
/* Exit low optimization region - place directly after end of function definition */
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#elif defined(__CSMC__)
#define LOW_OPTIMIZATION_ENTER
#define LOW_OPTIMIZATION_EXIT
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#elif defined(__TASKING__)
#define LOW_OPTIMIZATION_ENTER
#define LOW_OPTIMIZATION_EXIT
#define IAR_ONLY_LOW_OPTIMIZATION_ENTER
#define IAR_ONLY_LOW_OPTIMIZATION_EXIT
#endif
#ifdef __cplusplus
}
#endif
#if defined ( __GNUC__ )
#pragma GCC diagnostic pop
#endif
#endif /* _ARM_MATH_H */
/**
*
* End of file.
*/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Inc\main.h | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 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
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Inc\stm32f4xx_hal_conf.h | /**
******************************************************************************
* @file stm32f4xx_hal_conf_template.h
* @author MCD Application Team
* @brief HAL configuration template file.
* This file should be copied to the application folder and renamed
* to stm32f4xx_hal_conf.h.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_CONF_H
#define __STM32F4xx_HAL_CONF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* ########################## Module Selection ############################## */
/**
* @brief This is the list of modules to be used in the HAL driver
*/
#define HAL_MODULE_ENABLED
/* #define HAL_ADC_MODULE_ENABLED */
/* #define HAL_CRYP_MODULE_ENABLED */
/* #define HAL_CAN_MODULE_ENABLED */
/* #define HAL_CRC_MODULE_ENABLED */
/* #define HAL_CRYP_MODULE_ENABLED */
/* #define HAL_DAC_MODULE_ENABLED */
/* #define HAL_DCMI_MODULE_ENABLED */
/* #define HAL_DMA2D_MODULE_ENABLED */
/* #define HAL_ETH_MODULE_ENABLED */
/* #define HAL_NAND_MODULE_ENABLED */
/* #define HAL_NOR_MODULE_ENABLED */
/* #define HAL_PCCARD_MODULE_ENABLED */
/* #define HAL_SRAM_MODULE_ENABLED */
/* #define HAL_SDRAM_MODULE_ENABLED */
/* #define HAL_HASH_MODULE_ENABLED */
/* #define HAL_I2C_MODULE_ENABLED */
#define HAL_I2S_MODULE_ENABLED
/* #define HAL_IWDG_MODULE_ENABLED */
/* #define HAL_LTDC_MODULE_ENABLED */
/* #define HAL_RNG_MODULE_ENABLED */
/* #define HAL_RTC_MODULE_ENABLED */
/* #define HAL_SAI_MODULE_ENABLED */
/* #define HAL_SD_MODULE_ENABLED */
/* #define HAL_MMC_MODULE_ENABLED */
/* #define HAL_SPI_MODULE_ENABLED */
/* #define HAL_TIM_MODULE_ENABLED */
#define HAL_UART_MODULE_ENABLED
/* #define HAL_USART_MODULE_ENABLED */
/* #define HAL_IRDA_MODULE_ENABLED */
/* #define HAL_SMARTCARD_MODULE_ENABLED */
/* #define HAL_SMBUS_MODULE_ENABLED */
/* #define HAL_WWDG_MODULE_ENABLED */
/* #define HAL_PCD_MODULE_ENABLED */
/* #define HAL_HCD_MODULE_ENABLED */
/* #define HAL_DSI_MODULE_ENABLED */
/* #define HAL_QSPI_MODULE_ENABLED */
/* #define HAL_QSPI_MODULE_ENABLED */
/* #define HAL_CEC_MODULE_ENABLED */
/* #define HAL_FMPI2C_MODULE_ENABLED */
/* #define HAL_SPDIFRX_MODULE_ENABLED */
/* #define HAL_DFSDM_MODULE_ENABLED */
/* #define HAL_LPTIM_MODULE_ENABLED */
#define HAL_GPIO_MODULE_ENABLED
#define HAL_EXTI_MODULE_ENABLED
#define HAL_DMA_MODULE_ENABLED
#define HAL_RCC_MODULE_ENABLED
#define HAL_FLASH_MODULE_ENABLED
#define HAL_PWR_MODULE_ENABLED
#define HAL_CORTEX_MODULE_ENABLED
/* ########################## HSE/HSI Values adaptation ##################### */
/**
* @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSE is used as system clock source, directly or through the PLL).
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE ((uint32_t)8000000U) /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSE_STARTUP_TIMEOUT)
#define HSE_STARTUP_TIMEOUT ((uint32_t)100U) /*!< Time out for HSE start up, in ms */
#endif /* HSE_STARTUP_TIMEOUT */
/**
* @brief Internal High Speed oscillator (HSI) value.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSI is used as system clock source, directly or through the PLL).
*/
#if !defined (HSI_VALUE)
#define HSI_VALUE ((uint32_t)16000000U) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
/**
* @brief Internal Low Speed oscillator (LSI) value.
*/
#if !defined (LSI_VALUE)
#define LSI_VALUE ((uint32_t)32000U) /*!< LSI Typical Value in Hz*/
#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz
The real value may vary depending on the variations
in voltage and temperature.*/
/**
* @brief External Low Speed oscillator (LSE) value.
*/
#if !defined (LSE_VALUE)
#define LSE_VALUE ((uint32_t)32768U) /*!< Value of the External Low Speed oscillator in Hz */
#endif /* LSE_VALUE */
#if !defined (LSE_STARTUP_TIMEOUT)
#define LSE_STARTUP_TIMEOUT ((uint32_t)5000U) /*!< Time out for LSE start up, in ms */
#endif /* LSE_STARTUP_TIMEOUT */
/**
* @brief External clock source for I2S peripheral
* This value is used by the I2S HAL module to compute the I2S clock source
* frequency, this source is inserted directly through I2S_CKIN pad.
*/
#if !defined (EXTERNAL_CLOCK_VALUE)
#define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000U) /*!< Value of the External audio frequency in Hz*/
#endif /* EXTERNAL_CLOCK_VALUE */
/* Tip: To avoid modifying this file each time you need to use different HSE,
=== you can define the HSE value in your toolchain compiler preprocessor. */
/* ########################### System Configuration ######################### */
/**
* @brief This is the HAL system configuration section
*/
#define VDD_VALUE ((uint32_t)3300U) /*!< Value of VDD in mv */
#define TICK_INT_PRIORITY ((uint32_t)0U) /*!< tick interrupt priority */
#define USE_RTOS 0U
#define PREFETCH_ENABLE 1U
#define INSTRUCTION_CACHE_ENABLE 1U
#define DATA_CACHE_ENABLE 1U
/* ########################## Assert Selection ############################## */
/**
* @brief Uncomment the line below to expanse the "assert_param" macro in the
* HAL drivers code
*/
/* #define USE_FULL_ASSERT 1U */
/* ################## Ethernet peripheral configuration ##################### */
/* Section 1 : Ethernet peripheral configuration */
/* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */
#define MAC_ADDR0 2U
#define MAC_ADDR1 0U
#define MAC_ADDR2 0U
#define MAC_ADDR3 0U
#define MAC_ADDR4 0U
#define MAC_ADDR5 0U
/* Definition of the Ethernet driver buffers size and count */
#define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */
#define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */
#define ETH_RXBUFNB ((uint32_t)4U) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */
#define ETH_TXBUFNB ((uint32_t)4U) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */
/* Section 2: PHY configuration section */
/* DP83848_PHY_ADDRESS Address*/
#define DP83848_PHY_ADDRESS 0x01U
/* PHY Reset delay these values are based on a 1 ms Systick interrupt*/
#define PHY_RESET_DELAY ((uint32_t)0x000000FFU)
/* PHY Configuration delay */
#define PHY_CONFIG_DELAY ((uint32_t)0x00000FFFU)
#define PHY_READ_TO ((uint32_t)0x0000FFFFU)
#define PHY_WRITE_TO ((uint32_t)0x0000FFFFU)
/* Section 3: Common PHY Registers */
#define PHY_BCR ((uint16_t)0x0000U) /*!< Transceiver Basic Control Register */
#define PHY_BSR ((uint16_t)0x0001U) /*!< Transceiver Basic Status Register */
#define PHY_RESET ((uint16_t)0x8000U) /*!< PHY Reset */
#define PHY_LOOPBACK ((uint16_t)0x4000U) /*!< Select loop-back mode */
#define PHY_FULLDUPLEX_100M ((uint16_t)0x2100U) /*!< Set the full-duplex mode at 100 Mb/s */
#define PHY_HALFDUPLEX_100M ((uint16_t)0x2000U) /*!< Set the half-duplex mode at 100 Mb/s */
#define PHY_FULLDUPLEX_10M ((uint16_t)0x0100U) /*!< Set the full-duplex mode at 10 Mb/s */
#define PHY_HALFDUPLEX_10M ((uint16_t)0x0000U) /*!< Set the half-duplex mode at 10 Mb/s */
#define PHY_AUTONEGOTIATION ((uint16_t)0x1000U) /*!< Enable auto-negotiation function */
#define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200U) /*!< Restart auto-negotiation function */
#define PHY_POWERDOWN ((uint16_t)0x0800U) /*!< Select the power down mode */
#define PHY_ISOLATE ((uint16_t)0x0400U) /*!< Isolate PHY from MII */
#define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020U) /*!< Auto-Negotiation process completed */
#define PHY_LINKED_STATUS ((uint16_t)0x0004U) /*!< Valid link established */
#define PHY_JABBER_DETECTION ((uint16_t)0x0002U) /*!< Jabber condition detected */
/* Section 4: Extended PHY Registers */
#define PHY_SR ((uint16_t)0x10U) /*!< PHY status register Offset */
#define PHY_SPEED_STATUS ((uint16_t)0x0002U) /*!< PHY Speed mask */
#define PHY_DUPLEX_STATUS ((uint16_t)0x0004U) /*!< PHY Duplex mask */
/* ################## SPI peripheral configuration ########################## */
/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver
* Activated: CRC code is present inside driver
* Deactivated: CRC code cleaned from driver
*/
#define USE_SPI_CRC 0U
/* Includes ------------------------------------------------------------------*/
/**
* @brief Include module's header file
*/
#ifdef HAL_RCC_MODULE_ENABLED
#include "stm32f4xx_hal_rcc.h"
#endif /* HAL_RCC_MODULE_ENABLED */
#ifdef HAL_EXTI_MODULE_ENABLED
#include "stm32f4xx_hal_exti.h"
#endif /* HAL_EXTI_MODULE_ENABLED */
#ifdef HAL_GPIO_MODULE_ENABLED
#include "stm32f4xx_hal_gpio.h"
#endif /* HAL_GPIO_MODULE_ENABLED */
#ifdef HAL_DMA_MODULE_ENABLED
#include "stm32f4xx_hal_dma.h"
#endif /* HAL_DMA_MODULE_ENABLED */
#ifdef HAL_CORTEX_MODULE_ENABLED
#include "stm32f4xx_hal_cortex.h"
#endif /* HAL_CORTEX_MODULE_ENABLED */
#ifdef HAL_ADC_MODULE_ENABLED
#include "stm32f4xx_hal_adc.h"
#endif /* HAL_ADC_MODULE_ENABLED */
#ifdef HAL_CAN_MODULE_ENABLED
#include "stm32f4xx_hal_can.h"
#endif /* HAL_CAN_MODULE_ENABLED */
#ifdef HAL_CRC_MODULE_ENABLED
#include "stm32f4xx_hal_crc.h"
#endif /* HAL_CRC_MODULE_ENABLED */
#ifdef HAL_CRYP_MODULE_ENABLED
#include "stm32f4xx_hal_cryp.h"
#endif /* HAL_CRYP_MODULE_ENABLED */
#ifdef HAL_SMBUS_MODULE_ENABLED
#include "stm32f4xx_hal_smbus.h"
#endif /* HAL_SMBUS_MODULE_ENABLED */
#ifdef HAL_DMA2D_MODULE_ENABLED
#include "stm32f4xx_hal_dma2d.h"
#endif /* HAL_DMA2D_MODULE_ENABLED */
#ifdef HAL_DAC_MODULE_ENABLED
#include "stm32f4xx_hal_dac.h"
#endif /* HAL_DAC_MODULE_ENABLED */
#ifdef HAL_DCMI_MODULE_ENABLED
#include "stm32f4xx_hal_dcmi.h"
#endif /* HAL_DCMI_MODULE_ENABLED */
#ifdef HAL_ETH_MODULE_ENABLED
#include "stm32f4xx_hal_eth.h"
#endif /* HAL_ETH_MODULE_ENABLED */
#ifdef HAL_FLASH_MODULE_ENABLED
#include "stm32f4xx_hal_flash.h"
#endif /* HAL_FLASH_MODULE_ENABLED */
#ifdef HAL_SRAM_MODULE_ENABLED
#include "stm32f4xx_hal_sram.h"
#endif /* HAL_SRAM_MODULE_ENABLED */
#ifdef HAL_NOR_MODULE_ENABLED
#include "stm32f4xx_hal_nor.h"
#endif /* HAL_NOR_MODULE_ENABLED */
#ifdef HAL_NAND_MODULE_ENABLED
#include "stm32f4xx_hal_nand.h"
#endif /* HAL_NAND_MODULE_ENABLED */
#ifdef HAL_PCCARD_MODULE_ENABLED
#include "stm32f4xx_hal_pccard.h"
#endif /* HAL_PCCARD_MODULE_ENABLED */
#ifdef HAL_SDRAM_MODULE_ENABLED
#include "stm32f4xx_hal_sdram.h"
#endif /* HAL_SDRAM_MODULE_ENABLED */
#ifdef HAL_HASH_MODULE_ENABLED
#include "stm32f4xx_hal_hash.h"
#endif /* HAL_HASH_MODULE_ENABLED */
#ifdef HAL_I2C_MODULE_ENABLED
#include "stm32f4xx_hal_i2c.h"
#endif /* HAL_I2C_MODULE_ENABLED */
#ifdef HAL_I2S_MODULE_ENABLED
#include "stm32f4xx_hal_i2s.h"
#endif /* HAL_I2S_MODULE_ENABLED */
#ifdef HAL_IWDG_MODULE_ENABLED
#include "stm32f4xx_hal_iwdg.h"
#endif /* HAL_IWDG_MODULE_ENABLED */
#ifdef HAL_LTDC_MODULE_ENABLED
#include "stm32f4xx_hal_ltdc.h"
#endif /* HAL_LTDC_MODULE_ENABLED */
#ifdef HAL_PWR_MODULE_ENABLED
#include "stm32f4xx_hal_pwr.h"
#endif /* HAL_PWR_MODULE_ENABLED */
#ifdef HAL_RNG_MODULE_ENABLED
#include "stm32f4xx_hal_rng.h"
#endif /* HAL_RNG_MODULE_ENABLED */
#ifdef HAL_RTC_MODULE_ENABLED
#include "stm32f4xx_hal_rtc.h"
#endif /* HAL_RTC_MODULE_ENABLED */
#ifdef HAL_SAI_MODULE_ENABLED
#include "stm32f4xx_hal_sai.h"
#endif /* HAL_SAI_MODULE_ENABLED */
#ifdef HAL_SD_MODULE_ENABLED
#include "stm32f4xx_hal_sd.h"
#endif /* HAL_SD_MODULE_ENABLED */
#ifdef HAL_MMC_MODULE_ENABLED
#include "stm32f4xx_hal_mmc.h"
#endif /* HAL_MMC_MODULE_ENABLED */
#ifdef HAL_SPI_MODULE_ENABLED
#include "stm32f4xx_hal_spi.h"
#endif /* HAL_SPI_MODULE_ENABLED */
#ifdef HAL_TIM_MODULE_ENABLED
#include "stm32f4xx_hal_tim.h"
#endif /* HAL_TIM_MODULE_ENABLED */
#ifdef HAL_UART_MODULE_ENABLED
#include "stm32f4xx_hal_uart.h"
#endif /* HAL_UART_MODULE_ENABLED */
#ifdef HAL_USART_MODULE_ENABLED
#include "stm32f4xx_hal_usart.h"
#endif /* HAL_USART_MODULE_ENABLED */
#ifdef HAL_IRDA_MODULE_ENABLED
#include "stm32f4xx_hal_irda.h"
#endif /* HAL_IRDA_MODULE_ENABLED */
#ifdef HAL_SMARTCARD_MODULE_ENABLED
#include "stm32f4xx_hal_smartcard.h"
#endif /* HAL_SMARTCARD_MODULE_ENABLED */
#ifdef HAL_WWDG_MODULE_ENABLED
#include "stm32f4xx_hal_wwdg.h"
#endif /* HAL_WWDG_MODULE_ENABLED */
#ifdef HAL_PCD_MODULE_ENABLED
#include "stm32f4xx_hal_pcd.h"
#endif /* HAL_PCD_MODULE_ENABLED */
#ifdef HAL_HCD_MODULE_ENABLED
#include "stm32f4xx_hal_hcd.h"
#endif /* HAL_HCD_MODULE_ENABLED */
#ifdef HAL_DSI_MODULE_ENABLED
#include "stm32f4xx_hal_dsi.h"
#endif /* HAL_DSI_MODULE_ENABLED */
#ifdef HAL_QSPI_MODULE_ENABLED
#include "stm32f4xx_hal_qspi.h"
#endif /* HAL_QSPI_MODULE_ENABLED */
#ifdef HAL_CEC_MODULE_ENABLED
#include "stm32f4xx_hal_cec.h"
#endif /* HAL_CEC_MODULE_ENABLED */
#ifdef HAL_FMPI2C_MODULE_ENABLED
#include "stm32f4xx_hal_fmpi2c.h"
#endif /* HAL_FMPI2C_MODULE_ENABLED */
#ifdef HAL_SPDIFRX_MODULE_ENABLED
#include "stm32f4xx_hal_spdifrx.h"
#endif /* HAL_SPDIFRX_MODULE_ENABLED */
#ifdef HAL_DFSDM_MODULE_ENABLED
#include "stm32f4xx_hal_dfsdm.h"
#endif /* HAL_DFSDM_MODULE_ENABLED */
#ifdef HAL_LPTIM_MODULE_ENABLED
#include "stm32f4xx_hal_lptim.h"
#endif /* HAL_LPTIM_MODULE_ENABLED */
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for function's parameters check.
* @param expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* @retval None
*/
#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4xx_HAL_CONF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Inc\stm32f4xx_it.h | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f4xx_it.h
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 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
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_IT_H
#define __STM32F4xx_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
void DMA1_Stream3_IRQHandler(void);
void DMA1_Stream4_IRQHandler(void);
void DMA1_Stream6_IRQHandler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4xx_IT_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\main.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 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
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#define ARM_MATH_CM4
#include "main.h"
#include "arm_math.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
I2S_HandleTypeDef hi2s2;
DMA_HandleTypeDef hdma_i2s2_ext_rx;
DMA_HandleTypeDef hdma_spi2_tx;
UART_HandleTypeDef huart2;
DMA_HandleTypeDef hdma_usart2_tx;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_I2S2_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
uint16_t rxBuf[16384];
uint16_t txBuf[16384];
float fft_in_buf[2048];
float fft_out_buf[2048];
arm_rfft_fast_instance_f32 fft_handler;
float real_fsample = 46875;
uint8_t callback_state = 0;
uint8_t outarray[14];
uint8_t uartfree = 1;
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_I2S2_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
HAL_I2SEx_TransmitReceive_DMA (&hi2s2, txBuf, rxBuf, 8192);
arm_rfft_fast_init_f32(&fft_handler, 2048);
while (1)
{
//do audio loopback and push mono-sum to fft_in_buf
int fft_in_ptr = 0;
if (callback_state == 1) {
for (int i=0; i<8192; i=i+4) {
fft_in_buf[fft_in_ptr] = (float) ((int) (rxBuf[i]<<16)|rxBuf[i+1]);
fft_in_buf[fft_in_ptr] += (float) ((int) (rxBuf[i+2]<<16)|rxBuf[i+3]);
txBuf[i] = rxBuf[i];
txBuf[i+1] = rxBuf[i+1];
txBuf[i+2] = rxBuf[i+2];
txBuf[i+3] = rxBuf[i+3];
fft_in_ptr++;
}
DoFFT();
}
if (callback_state == 2) {
for (int i=8192; i<16384; i=i+4) {
fft_in_buf[fft_in_ptr] = (float) ((int) (rxBuf[i]<<16)|rxBuf[i+1]);
fft_in_buf[fft_in_ptr] += (float) ((int) (rxBuf[i+2]<<16)|rxBuf[i+3]);
txBuf[i] = rxBuf[i];
txBuf[i+1] = rxBuf[i+1];
txBuf[i+2] = rxBuf[i+2];
txBuf[i+3] = rxBuf[i+3];
fft_in_ptr++;
}
DoFFT();
}
}
/* USER CODE END 3 */
}
float complexABS(float real, float compl) {
return sqrtf(real*real+compl*compl);
}
void DoFFT() {
//Do FFT
arm_rfft_fast_f32(&fft_handler, &fft_in_buf,&fft_out_buf,0);
int freqs[1024];
int freqpoint = 0;
int offset = 150; //variable noisefloor offset
//calculate abs values and linear-to-dB
for (int i=0; i<2048; i=i+2) {
freqs[freqpoint] = (int)(20*log10f(complexABS(fft_out_buf[i], fft_out_buf[i+1])))-offset;
if (freqs[freqpoint]<0) freqs[freqpoint]=0;
freqpoint++;
}
//push out data to Uart
outarray[0] = 0xff; //frame start
outarray[1] = (uint8_t)freqs[1]; //31-5Hz
outarray[2] = (uint8_t)freqs[3]; //63 Hz
outarray[3] = (uint8_t)freqs[5]; //125 Hz
outarray[4] = (uint8_t)freqs[11]; //250 Hz
outarray[5] = (uint8_t)freqs[22]; //500 Hz
outarray[6] = (uint8_t)freqs[44]; //1 kHz
outarray[7] = (uint8_t)freqs[96]; //2.2 kHz
outarray[8] = (uint8_t)freqs[197]; //4.5 kHz
outarray[9] = (uint8_t)freqs[393]; //9 kHz
outarray[10] = (uint8_t)freqs[655]; //15 lHz
if (uartfree==1) HAL_UART_Transmit_DMA(&huart2, &outarray[0], 11);
uartfree = 0;
callback_state=0;
}
void HAL_UART_TxHalfCpltCallback (UART_HandleTypeDef *huart) {
uartfree = 1;
huart2.gState=HAL_UART_STATE_READY;
}
void HAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *hi2s){
callback_state = 1;
}
void HAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *hi2s){
callback_state = 2;
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_I2S;
PeriphClkInitStruct.PLLI2S.PLLI2SN = 192;
PeriphClkInitStruct.PLLI2S.PLLI2SR = 2;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief I2S2 Initialization Function
* @param None
* @retval None
*/
static void MX_I2S2_Init(void)
{
/* USER CODE BEGIN I2S2_Init 0 */
/* USER CODE END I2S2_Init 0 */
/* USER CODE BEGIN I2S2_Init 1 */
/* USER CODE END I2S2_Init 1 */
hi2s2.Instance = SPI2;
hi2s2.Init.Mode = I2S_MODE_MASTER_TX;
hi2s2.Init.Standard = I2S_STANDARD_PHILIPS;
hi2s2.Init.DataFormat = I2S_DATAFORMAT_24B;
hi2s2.Init.MCLKOutput = I2S_MCLKOUTPUT_ENABLE;
hi2s2.Init.AudioFreq = I2S_AUDIOFREQ_48K;
hi2s2.Init.CPOL = I2S_CPOL_LOW;
hi2s2.Init.ClockSource = I2S_CLOCK_PLL;
hi2s2.Init.FullDuplexMode = I2S_FULLDUPLEXMODE_ENABLE;
if (HAL_I2S_Init(&hi2s2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2S2_Init 2 */
/* USER CODE END I2S2_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Stream3_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream3_IRQn);
/* DMA1_Stream4_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream4_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream4_IRQn);
/* DMA1_Stream6_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream6_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream6_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_0, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15
|GPIO_PIN_4, GPIO_PIN_RESET);
/*Configure GPIO pin : PE3 */
GPIO_InitStruct.Pin = GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : PC0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PA0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PA4 */
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_SPI3;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PA5 PA6 PA7 */
GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PB2 */
GPIO_InitStruct.Pin = GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : PD12 PD13 PD14 PD15
PD4 */
GPIO_InitStruct.Pin = GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15
|GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : PC7 PC10 PC12 */
GPIO_InitStruct.Pin = GPIO_PIN_7|GPIO_PIN_10|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_SPI3;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PA9 */
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PA10 PA11 PA12 */
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PD5 */
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : PB6 PB9 */
GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : PE1 */
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\stm32f4xx_hal_msp.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* File Name : stm32f4xx_hal_msp.c
* Description : This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 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
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern DMA_HandleTypeDef hdma_i2s2_ext_rx;
extern DMA_HandleTypeDef hdma_spi2_tx;
extern DMA_HandleTypeDef hdma_usart2_tx;
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_SYSCFG_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_0);
/* System interrupt init*/
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/**
* @brief I2S MSP Initialization
* This function configures the hardware resources used in this example
* @param hi2s: I2S handle pointer
* @retval None
*/
void HAL_I2S_MspInit(I2S_HandleTypeDef* hi2s)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hi2s->Instance==SPI2)
{
/* USER CODE BEGIN SPI2_MspInit 0 */
/* USER CODE END SPI2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SPI2_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/**I2S2 GPIO Configuration
PC2 ------> I2S2_ext_SD
PC3 ------> I2S2_SD
PB10 ------> I2S2_CK
PB12 ------> I2S2_WS
PC6 ------> I2S2_MCK
*/
GPIO_InitStruct.Pin = GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF6_I2S2ext;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_3|GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* I2S2 DMA Init */
/* I2S2_EXT_RX Init */
hdma_i2s2_ext_rx.Instance = DMA1_Stream3;
hdma_i2s2_ext_rx.Init.Channel = DMA_CHANNEL_3;
hdma_i2s2_ext_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_i2s2_ext_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_i2s2_ext_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_i2s2_ext_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_i2s2_ext_rx.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_i2s2_ext_rx.Init.Mode = DMA_CIRCULAR;
hdma_i2s2_ext_rx.Init.Priority = DMA_PRIORITY_HIGH;
hdma_i2s2_ext_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_i2s2_ext_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hi2s,hdmarx,hdma_i2s2_ext_rx);
/* SPI2_TX Init */
hdma_spi2_tx.Instance = DMA1_Stream4;
hdma_spi2_tx.Init.Channel = DMA_CHANNEL_0;
hdma_spi2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_spi2_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_spi2_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_spi2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_spi2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_spi2_tx.Init.Mode = DMA_CIRCULAR;
hdma_spi2_tx.Init.Priority = DMA_PRIORITY_HIGH;
hdma_spi2_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_spi2_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hi2s,hdmatx,hdma_spi2_tx);
/* USER CODE BEGIN SPI2_MspInit 1 */
/* USER CODE END SPI2_MspInit 1 */
}
}
/**
* @brief I2S MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hi2s: I2S handle pointer
* @retval None
*/
void HAL_I2S_MspDeInit(I2S_HandleTypeDef* hi2s)
{
if(hi2s->Instance==SPI2)
{
/* USER CODE BEGIN SPI2_MspDeInit 0 */
/* USER CODE END SPI2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_SPI2_CLK_DISABLE();
/**I2S2 GPIO Configuration
PC2 ------> I2S2_ext_SD
PC3 ------> I2S2_SD
PB10 ------> I2S2_CK
PB12 ------> I2S2_WS
PC6 ------> I2S2_MCK
*/
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_6);
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_12);
/* I2S2 DMA DeInit */
HAL_DMA_DeInit(hi2s->hdmarx);
HAL_DMA_DeInit(hi2s->hdmatx);
/* USER CODE BEGIN SPI2_MspDeInit 1 */
/* USER CODE END SPI2_MspDeInit 1 */
}
}
/**
* @brief UART MSP Initialization
* This function configures the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(huart->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspInit 0 */
/* USER CODE END USART2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USART2 DMA Init */
/* USART2_TX Init */
hdma_usart2_tx.Instance = DMA1_Stream6;
hdma_usart2_tx.Init.Channel = DMA_CHANNEL_4;
hdma_usart2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart2_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart2_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart2_tx.Init.Mode = DMA_NORMAL;
hdma_usart2_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart2_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart2_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(huart,hdmatx,hdma_usart2_tx);
/* USER CODE BEGIN USART2_MspInit 1 */
/* USER CODE END USART2_MspInit 1 */
}
}
/**
* @brief UART MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
if(huart->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspDeInit 0 */
/* USER CODE END USART2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART2_CLK_DISABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3);
/* USART2 DMA DeInit */
HAL_DMA_DeInit(huart->hdmatx);
/* USER CODE BEGIN USART2_MspDeInit 1 */
/* USER CODE END USART2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\stm32f4xx_it.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f4xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 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
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_i2s2_ext_rx;
extern DMA_HandleTypeDef hdma_spi2_tx;
extern DMA_HandleTypeDef hdma_usart2_tx;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M4 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Pre-fetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f4xx.s). */
/******************************************************************************/
/**
* @brief This function handles DMA1 stream3 global interrupt.
*/
void DMA1_Stream3_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Stream3_IRQn 0 */
/* USER CODE END DMA1_Stream3_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_i2s2_ext_rx);
/* USER CODE BEGIN DMA1_Stream3_IRQn 1 */
/* USER CODE END DMA1_Stream3_IRQn 1 */
}
/**
* @brief This function handles DMA1 stream4 global interrupt.
*/
void DMA1_Stream4_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Stream4_IRQn 0 */
/* USER CODE END DMA1_Stream4_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_spi2_tx);
/* USER CODE BEGIN DMA1_Stream4_IRQn 1 */
/* USER CODE END DMA1_Stream4_IRQn 1 */
}
/**
* @brief This function handles DMA1 stream6 global interrupt.
*/
void DMA1_Stream6_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Stream6_IRQn 0 */
/* USER CODE END DMA1_Stream6_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart2_tx);
/* USER CODE BEGIN DMA1_Stream6_IRQn 1 */
/* USER CODE END DMA1_Stream6_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\syscalls.c | /**
*****************************************************************************
**
** File : syscalls.c
**
** Author : Auto-generated by STM32CubeIDE
**
** Abstract : STM32CubeIDE Minimal System calls file
**
** For more information about which c-functions
** need which of these lowlevel functions
** please consult the Newlib libc-manual
**
** Environment : STM32CubeIDE MCU
**
** Distribution: The file is distributed as is, without any warranty
** of any kind.
**
*****************************************************************************
**
** <h2><center>© COPYRIGHT(c) 2018 STMicroelectronics</center></h2>
**
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
** 1. Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
** 3. Neither the name of STMicroelectronics nor the names of its contributors
** may be used to endorse or promote products derived from this software
** without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
*****************************************************************************
*/
/* Includes */
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
/* Variables */
//#undef errno
extern int errno;
extern int __io_putchar(int ch) __attribute__((weak));
extern int __io_getchar(void) __attribute__((weak));
register char * stack_ptr asm("sp");
char *__env[1] = { 0 };
char **environ = __env;
/* Functions */
void initialise_monitor_handles()
{
}
int _getpid(void)
{
return 1;
}
int _kill(int pid, int sig)
{
errno = EINVAL;
return -1;
}
void _exit (int status)
{
_kill(status, -1);
while (1) {} /* Make sure we hang here */
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
__io_putchar(*ptr++);
}
return len;
}
int _close(int file)
{
return -1;
}
int _fstat(int file, struct stat *st)
{
st->st_mode = S_IFCHR;
return 0;
}
int _isatty(int file)
{
return 1;
}
int _lseek(int file, int ptr, int dir)
{
return 0;
}
int _open(char *path, int flags, ...)
{
/* Pretend like we always fail */
return -1;
}
int _wait(int *status)
{
errno = ECHILD;
return -1;
}
int _unlink(char *name)
{
errno = ENOENT;
return -1;
}
int _times(struct tms *buf)
{
return -1;
}
int _stat(char *file, struct stat *st)
{
st->st_mode = S_IFCHR;
return 0;
}
int _link(char *old, char *new)
{
errno = EMLINK;
return -1;
}
int _fork(void)
{
errno = EAGAIN;
return -1;
}
int _execve(char *name, char **argv, char **env)
{
errno = ENOMEM;
return -1;
}
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\sysmem.c | /**
*****************************************************************************
**
** File : sysmem.c
**
** Author : Auto-generated by STM32CubeIDE
**
** Abstract : STM32CubeIDE Minimal System Memory calls file
**
** For more information about which c-functions
** need which of these lowlevel functions
** please consult the Newlib libc-manual
**
** Environment : STM32CubeIDE MCU
**
** Distribution: The file is distributed as is, without any warranty
** of any kind.
**
*****************************************************************************
**
** <h2><center>© COPYRIGHT(c) 2018 STMicroelectronics</center></h2>
**
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
** 1. Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
** 3. Neither the name of STMicroelectronics nor the names of its contributors
** may be used to endorse or promote products derived from this software
** without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
*****************************************************************************
*/
/* Includes */
#include <errno.h>
#include <stdio.h>
/* Variables */
extern int errno;
register char * stack_ptr asm("sp");
/* Functions */
/**
_sbrk
Increase program data space. Malloc and related functions depend on this
**/
caddr_t _sbrk(int incr)
{
extern char end asm("end");
static char *heap_end;
char *prev_heap_end;
if (heap_end == 0)
heap_end = &end;
prev_heap_end = heap_end;
if (heap_end + incr > stack_ptr)
{
errno = ENOMEM;
return (caddr_t) -1;
}
heap_end += incr;
return (caddr_t) prev_heap_end;
}
| 0 |
D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32 | D://workCode//uploadProject\STM32_FFT_Spectrum_Analysis\code STM32\Src\system_stm32f4xx.c | /**
******************************************************************************
* @file system_stm32f4xx.c
* @author MCD Application Team
* @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File.
*
* This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f4xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f4xx_system
* @{
*/
/** @addtogroup STM32F4xx_System_Private_Includes
* @{
*/
#include "stm32f4xx.h"
#if !defined (HSE_VALUE)
#define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Defines
* @{
*/
/************************* Miscellaneous Configuration ************************/
/*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\
|| defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx)
/* #define DATA_IN_ExtSRAM */
#endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx ||\
STM32F412Zx || STM32F412Vx */
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx)
/* #define DATA_IN_ExtSDRAM */
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\
STM32F479xx */
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Variables
* @{
*/
/* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 16000000;
const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_FunctionPrototypes
* @{
*/
#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */
/**
* @}
*/
/** @addtogroup STM32F4xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the FPU setting, vector table location and External memory
* configuration.
* @param None
* @retval None
*/
void SystemInit(void)
{
/* FPU settings ------------------------------------------------------------*/
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */
#endif
/* Reset the RCC clock configuration to the default reset state ------------*/
/* Set HSION bit */
RCC->CR |= (uint32_t)0x00000001;
/* Reset CFGR register */
RCC->CFGR = 0x00000000;
/* Reset HSEON, CSSON and PLLON bits */
RCC->CR &= (uint32_t)0xFEF6FFFF;
/* Reset PLLCFGR register */
RCC->PLLCFGR = 0x24003010;
/* Reset HSEBYP bit */
RCC->CR &= (uint32_t)0xFFFBFFFF;
/* Disable all interrupts */
RCC->CIR = 0x00000000;
#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */
/* Configure the Vector Table location add offset address ------------------*/
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */
#endif
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied/divided by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value
* depends on the application requirements), user has to ensure that HSE_VALUE
* is same as the real frequency of the crystal used. Otherwise, this function
* may have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
*
* @param None
* @retval None
*/
void SystemCoreClockUpdate(void)
{
uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2;
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00: /* HSI used as system clock source */
SystemCoreClock = HSI_VALUE;
break;
case 0x04: /* HSE used as system clock source */
SystemCoreClock = HSE_VALUE;
break;
case 0x08: /* PLL used as system clock source */
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N
SYSCLK = PLL_VCO / PLL_P
*/
pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22;
pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM;
if (pllsource != 0)
{
/* HSE used as PLL clock source */
pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
}
else
{
/* HSI used as PLL clock source */
pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
}
pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2;
SystemCoreClock = pllvco/pllp;
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK frequency --------------------------------------------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
/* HCLK frequency */
SystemCoreClock >>= tmp;
}
#if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM)
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx)
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f4xx.s before jump to main.
* This function configures the external memories (SRAM/SDRAM)
* This SRAM/SDRAM will be used as program data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmp = 0x00;
register uint32_t tmpreg = 0, timeout = 0xFFFF;
register __IO uint32_t index;
/* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */
RCC->AHB1ENR |= 0x000001F8;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x00CCC0CC;
GPIOD->AFR[1] = 0xCCCCCCCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xAAAA0A8A;
/* Configure PDx pins speed to 100 MHz */
GPIOD->OSPEEDR = 0xFFFF0FCF;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00CC0CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA828A;
/* Configure PEx pins speed to 100 MHz */
GPIOE->OSPEEDR = 0xFFFFC3CF;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0xCCCCCCCC;
GPIOF->AFR[1] = 0xCCCCCCCC;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA800AAA;
/* Configure PFx pins speed to 50 MHz */
GPIOF->OSPEEDR = 0xAA800AAA;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0xCCCCCCCC;
GPIOG->AFR[1] = 0xCCCCCCCC;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0xAAAAAAAA;
/* Configure PGx pins speed to 50 MHz */
GPIOG->OSPEEDR = 0xAAAAAAAA;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
/* Connect PHx pins to FMC Alternate function */
GPIOH->AFR[0] = 0x00C0CC00;
GPIOH->AFR[1] = 0xCCCCCCCC;
/* Configure PHx pins in Alternate function mode */
GPIOH->MODER = 0xAAAA08A0;
/* Configure PHx pins speed to 50 MHz */
GPIOH->OSPEEDR = 0xAAAA08A0;
/* Configure PHx pins Output type to push-pull */
GPIOH->OTYPER = 0x00000000;
/* No pull-up, pull-down for PHx pins */
GPIOH->PUPDR = 0x00000000;
/* Connect PIx pins to FMC Alternate function */
GPIOI->AFR[0] = 0xCCCCCCCC;
GPIOI->AFR[1] = 0x00000CC0;
/* Configure PIx pins in Alternate function mode */
GPIOI->MODER = 0x0028AAAA;
/* Configure PIx pins speed to 50 MHz */
GPIOI->OSPEEDR = 0x0028AAAA;
/* Configure PIx pins Output type to push-pull */
GPIOI->OTYPER = 0x00000000;
/* No pull-up, pull-down for PIx pins */
GPIOI->PUPDR = 0x00000000;
/*-- FMC Configuration -------------------------------------------------------*/
/* Enable the FMC interface clock */
RCC->AHB3ENR |= 0x00000001;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
FMC_Bank5_6->SDCR[0] = 0x000019E4;
FMC_Bank5_6->SDTR[0] = 0x01115351;
/* SDRAM initialization sequence */
/* Clock enable command */
FMC_Bank5_6->SDCMR = 0x00000011;
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Delay */
for (index = 0; index<1000; index++);
/* PALL command */
FMC_Bank5_6->SDCMR = 0x00000012;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Auto refresh command */
FMC_Bank5_6->SDCMR = 0x00000073;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* MRD register program */
FMC_Bank5_6->SDCMR = 0x00046014;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Set refresh count */
tmpreg = FMC_Bank5_6->SDRTR;
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1));
/* Disable write protection */
tmpreg = FMC_Bank5_6->SDCR[0];
FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF);
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001011;
FMC_Bank1->BTCR[3] = 0x00000201;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
#if defined(STM32F469xx) || defined(STM32F479xx)
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001091;
FMC_Bank1->BTCR[3] = 0x00110212;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F469xx || STM32F479xx */
(void)(tmp);
}
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
#elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM)
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f4xx.s before jump to main.
* This function configures the external memories (SRAM/SDRAM)
* This SRAM/SDRAM will be used as program data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmp = 0x00;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx)
#if defined (DATA_IN_ExtSDRAM)
register uint32_t tmpreg = 0, timeout = 0xFFFF;
register __IO uint32_t index;
#if defined(STM32F446xx)
/* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface
clock */
RCC->AHB1ENR |= 0x0000007D;
#else
/* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface
clock */
RCC->AHB1ENR |= 0x000001F8;
#endif /* STM32F446xx */
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);
#if defined(STM32F446xx)
/* Connect PAx pins to FMC Alternate function */
GPIOA->AFR[0] |= 0xC0000000;
GPIOA->AFR[1] |= 0x00000000;
/* Configure PDx pins in Alternate function mode */
GPIOA->MODER |= 0x00008000;
/* Configure PDx pins speed to 50 MHz */
GPIOA->OSPEEDR |= 0x00008000;
/* Configure PDx pins Output type to push-pull */
GPIOA->OTYPER |= 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOA->PUPDR |= 0x00000000;
/* Connect PCx pins to FMC Alternate function */
GPIOC->AFR[0] |= 0x00CC0000;
GPIOC->AFR[1] |= 0x00000000;
/* Configure PDx pins in Alternate function mode */
GPIOC->MODER |= 0x00000A00;
/* Configure PDx pins speed to 50 MHz */
GPIOC->OSPEEDR |= 0x00000A00;
/* Configure PDx pins Output type to push-pull */
GPIOC->OTYPER |= 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOC->PUPDR |= 0x00000000;
#endif /* STM32F446xx */
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x000000CC;
GPIOD->AFR[1] = 0xCC000CCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xA02A000A;
/* Configure PDx pins speed to 50 MHz */
GPIOD->OSPEEDR = 0xA02A000A;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00000CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA800A;
/* Configure PEx pins speed to 50 MHz */
GPIOE->OSPEEDR = 0xAAAA800A;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0xCCCCCCCC;
GPIOF->AFR[1] = 0xCCCCCCCC;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA800AAA;
/* Configure PFx pins speed to 50 MHz */
GPIOF->OSPEEDR = 0xAA800AAA;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0xCCCCCCCC;
GPIOG->AFR[1] = 0xCCCCCCCC;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0xAAAAAAAA;
/* Configure PGx pins speed to 50 MHz */
GPIOG->OSPEEDR = 0xAAAAAAAA;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx)
/* Connect PHx pins to FMC Alternate function */
GPIOH->AFR[0] = 0x00C0CC00;
GPIOH->AFR[1] = 0xCCCCCCCC;
/* Configure PHx pins in Alternate function mode */
GPIOH->MODER = 0xAAAA08A0;
/* Configure PHx pins speed to 50 MHz */
GPIOH->OSPEEDR = 0xAAAA08A0;
/* Configure PHx pins Output type to push-pull */
GPIOH->OTYPER = 0x00000000;
/* No pull-up, pull-down for PHx pins */
GPIOH->PUPDR = 0x00000000;
/* Connect PIx pins to FMC Alternate function */
GPIOI->AFR[0] = 0xCCCCCCCC;
GPIOI->AFR[1] = 0x00000CC0;
/* Configure PIx pins in Alternate function mode */
GPIOI->MODER = 0x0028AAAA;
/* Configure PIx pins speed to 50 MHz */
GPIOI->OSPEEDR = 0x0028AAAA;
/* Configure PIx pins Output type to push-pull */
GPIOI->OTYPER = 0x00000000;
/* No pull-up, pull-down for PIx pins */
GPIOI->PUPDR = 0x00000000;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
/*-- FMC Configuration -------------------------------------------------------*/
/* Enable the FMC interface clock */
RCC->AHB3ENR |= 0x00000001;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable SDRAM bank1 */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCR[0] = 0x00001954;
#else
FMC_Bank5_6->SDCR[0] = 0x000019E4;
#endif /* STM32F446xx */
FMC_Bank5_6->SDTR[0] = 0x01115351;
/* SDRAM initialization sequence */
/* Clock enable command */
FMC_Bank5_6->SDCMR = 0x00000011;
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Delay */
for (index = 0; index<1000; index++);
/* PALL command */
FMC_Bank5_6->SDCMR = 0x00000012;
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Auto refresh command */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCMR = 0x000000F3;
#else
FMC_Bank5_6->SDCMR = 0x00000073;
#endif /* STM32F446xx */
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* MRD register program */
#if defined(STM32F446xx)
FMC_Bank5_6->SDCMR = 0x00044014;
#else
FMC_Bank5_6->SDCMR = 0x00046014;
#endif /* STM32F446xx */
timeout = 0xFFFF;
while((tmpreg != 0) && (timeout-- > 0))
{
tmpreg = FMC_Bank5_6->SDSR & 0x00000020;
}
/* Set refresh count */
tmpreg = FMC_Bank5_6->SDRTR;
#if defined(STM32F446xx)
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1));
#else
FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1));
#endif /* STM32F446xx */
/* Disable write protection */
tmpreg = FMC_Bank5_6->SDCR[0];
FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF);
#endif /* DATA_IN_ExtSDRAM */
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\
|| defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\
|| defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx)
#if defined(DATA_IN_ExtSRAM)
/*-- GPIOs Configuration -----------------------------------------------------*/
/* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */
RCC->AHB1ENR |= 0x00000078;
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);
/* Connect PDx pins to FMC Alternate function */
GPIOD->AFR[0] = 0x00CCC0CC;
GPIOD->AFR[1] = 0xCCCCCCCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xAAAA0A8A;
/* Configure PDx pins speed to 100 MHz */
GPIOD->OSPEEDR = 0xFFFF0FCF;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FMC Alternate function */
GPIOE->AFR[0] = 0xC00CC0CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA828A;
/* Configure PEx pins speed to 100 MHz */
GPIOE->OSPEEDR = 0xFFFFC3CF;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FMC Alternate function */
GPIOF->AFR[0] = 0x00CCCCCC;
GPIOF->AFR[1] = 0xCCCC0000;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA000AAA;
/* Configure PFx pins speed to 100 MHz */
GPIOF->OSPEEDR = 0xFF000FFF;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FMC Alternate function */
GPIOG->AFR[0] = 0x00CCCCCC;
GPIOG->AFR[1] = 0x000000C0;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0x00085AAA;
/* Configure PGx pins speed to 100 MHz */
GPIOG->OSPEEDR = 0x000CAFFF;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
/*-- FMC/FSMC Configuration --------------------------------------------------*/
/* Enable the FMC/FSMC interface clock */
RCC->AHB3ENR |= 0x00000001;
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001011;
FMC_Bank1->BTCR[3] = 0x00000201;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */
#if defined(STM32F469xx) || defined(STM32F479xx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);
/* Configure and enable Bank1_SRAM2 */
FMC_Bank1->BTCR[2] = 0x00001091;
FMC_Bank1->BTCR[3] = 0x00110212;
FMC_Bank1E->BWTR[2] = 0x0fffffff;
#endif /* STM32F469xx || STM32F479xx */
#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)\
|| defined(STM32F412Zx) || defined(STM32F412Vx)
/* Delay after an RCC peripheral clock enabling */
tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);
/* Configure and enable Bank1_SRAM2 */
FSMC_Bank1->BTCR[2] = 0x00001011;
FSMC_Bank1->BTCR[3] = 0x00000201;
FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF;
#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\
STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx */
(void)(tmp);
}
#endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO | D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO\Inc\usbd_audio.h | /**
******************************************************************************
* @file usbd_audio.h
* @author MCD Application Team
* @brief header file for the usbd_audio.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_AUDIO_H
#define __USB_AUDIO_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_AUDIO
* @brief This file is the Header file for usbd_audio.c
* @{
*/
/** @defgroup USBD_AUDIO_Exported_Defines
* @{
*/
#ifndef USBD_AUDIO_FREQ
/* AUDIO Class Config */
#define USBD_AUDIO_FREQ 48000U
#endif /* USBD_AUDIO_FREQ */
#ifndef USBD_MAX_NUM_INTERFACES
#define USBD_MAX_NUM_INTERFACES 1U
#endif /* USBD_AUDIO_FREQ */
#ifndef AUDIO_HS_BINTERVAL
#define AUDIO_HS_BINTERVAL 0x01U
#endif /* AUDIO_HS_BINTERVAL */
#ifndef AUDIO_FS_BINTERVAL
#define AUDIO_FS_BINTERVAL 0x01U
#endif /* AUDIO_FS_BINTERVAL */
#ifndef AUDIO_OUT_EP
#define AUDIO_OUT_EP 0x01U
#endif /* AUDIO_OUT_EP */
#define USB_AUDIO_CONFIG_DESC_SIZ 0x6DU
#define AUDIO_INTERFACE_DESC_SIZE 0x09U
#define USB_AUDIO_DESC_SIZ 0x09U
#define AUDIO_STANDARD_ENDPOINT_DESC_SIZE 0x09U
#define AUDIO_STREAMING_ENDPOINT_DESC_SIZE 0x07U
#define AUDIO_DESCRIPTOR_TYPE 0x21U
#define USB_DEVICE_CLASS_AUDIO 0x01U
#define AUDIO_SUBCLASS_AUDIOCONTROL 0x01U
#define AUDIO_SUBCLASS_AUDIOSTREAMING 0x02U
#define AUDIO_PROTOCOL_UNDEFINED 0x00U
#define AUDIO_STREAMING_GENERAL 0x01U
#define AUDIO_STREAMING_FORMAT_TYPE 0x02U
/* Audio Descriptor Types */
#define AUDIO_INTERFACE_DESCRIPTOR_TYPE 0x24U
#define AUDIO_ENDPOINT_DESCRIPTOR_TYPE 0x25U
/* Audio Control Interface Descriptor Subtypes */
#define AUDIO_CONTROL_HEADER 0x01U
#define AUDIO_CONTROL_INPUT_TERMINAL 0x02U
#define AUDIO_CONTROL_OUTPUT_TERMINAL 0x03U
#define AUDIO_CONTROL_FEATURE_UNIT 0x06U
#define AUDIO_INPUT_TERMINAL_DESC_SIZE 0x0CU
#define AUDIO_OUTPUT_TERMINAL_DESC_SIZE 0x09U
#define AUDIO_STREAMING_INTERFACE_DESC_SIZE 0x07U
#define AUDIO_CONTROL_MUTE 0x0001U
#define AUDIO_FORMAT_TYPE_I 0x01U
#define AUDIO_FORMAT_TYPE_III 0x03U
#define AUDIO_ENDPOINT_GENERAL 0x01U
#define AUDIO_REQ_GET_CUR 0x81U
#define AUDIO_REQ_SET_CUR 0x01U
#define AUDIO_OUT_STREAMING_CTRL 0x02U
#define AUDIO_OUT_TC 0x01U
#define AUDIO_IN_TC 0x02U
#define AUDIO_OUT_PACKET (uint16_t)(((USBD_AUDIO_FREQ * 2U * 2U) / 1000U))
#define AUDIO_DEFAULT_VOLUME 70U
/* Number of sub-packets in the audio transfer buffer. You can modify this value but always make sure
that it is an even number and higher than 3 */
#define AUDIO_OUT_PACKET_NUM 80U
/* Total size of the audio transfer buffer */
#define AUDIO_TOTAL_BUF_SIZE ((uint16_t)(AUDIO_OUT_PACKET * AUDIO_OUT_PACKET_NUM))
/* Audio Commands enumeration */
typedef enum
{
AUDIO_CMD_START = 1,
AUDIO_CMD_PLAY,
AUDIO_CMD_STOP,
} AUDIO_CMD_TypeDef;
typedef enum
{
AUDIO_OFFSET_NONE = 0,
AUDIO_OFFSET_HALF,
AUDIO_OFFSET_FULL,
AUDIO_OFFSET_UNKNOWN,
} AUDIO_OffsetTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef struct
{
uint8_t cmd;
uint8_t data[USB_MAX_EP0_SIZE];
uint8_t len;
uint8_t unit;
} USBD_AUDIO_ControlTypeDef;
typedef struct
{
uint32_t alt_setting;
uint8_t buffer[AUDIO_TOTAL_BUF_SIZE];
AUDIO_OffsetTypeDef offset;
uint8_t rd_enable;
uint16_t rd_ptr;
uint16_t wr_ptr;
USBD_AUDIO_ControlTypeDef control;
} USBD_AUDIO_HandleTypeDef;
typedef struct
{
int8_t (*Init)(uint32_t AudioFreq, uint32_t Volume, uint32_t options);
int8_t (*DeInit)(uint32_t options);
int8_t (*AudioCmd)(uint8_t *pbuf, uint32_t size, uint8_t cmd);
int8_t (*VolumeCtl)(uint8_t vol);
int8_t (*MuteCtl)(uint8_t cmd);
int8_t (*PeriodicTC)(uint8_t *pbuf, uint32_t size, uint8_t cmd);
int8_t (*GetState)(void);
} USBD_AUDIO_ItfTypeDef;
/*
* Audio Class specification release 1.0
*/
/* Table 4-2: Class-Specific AC Interface Header Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdADC;
uint16_t wTotalLength;
uint8_t bInCollection;
uint8_t baInterfaceNr;
} __PACKED USBD_SpeakerIfDescTypeDef;
/* Table 4-3: Input Terminal Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bNrChannels;
uint16_t wChannelConfig;
uint8_t iChannelNames;
uint8_t iTerminal;
} __PACKED USBD_SpeakerInDescTypeDef;
/* USB Speaker Audio Feature Unit Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bUnitID;
uint8_t bSourceID;
uint8_t bControlSize;
uint16_t bmaControls;
uint8_t iTerminal;
} __PACKED USBD_SpeakerFeatureDescTypeDef;
/* Table 4-4: Output Terminal Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bSourceID;
uint8_t iTerminal;
} __PACKED USBD_SpeakerOutDescTypeDef;
/* Table 4-19: Class-Specific AS Interface Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalLink;
uint8_t bDelay;
uint16_t wFormatTag;
} __PACKED USBD_SpeakerStreamIfDescTypeDef;
/* USB Speaker Audio Type III Format Interface Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bFormatType;
uint8_t bNrChannels;
uint8_t bSubFrameSize;
uint8_t bBitResolution;
uint8_t bSamFreqType;
uint8_t tSamFreq2;
uint8_t tSamFreq1;
uint8_t tSamFreq0;
} USBD_SpeakerIIIFormatIfDescTypeDef;
/* Table 4-17: Standard AC Interrupt Endpoint Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
uint8_t bRefresh;
uint8_t bSynchAddress;
} __PACKED USBD_SpeakerEndDescTypeDef;
/* Table 4-21: Class-Specific AS Isochronous Audio Data Endpoint Descriptor */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptor;
uint8_t bmAttributes;
uint8_t bLockDelayUnits;
uint16_t wLockDelay;
} __PACKED USBD_SpeakerEndStDescTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_AUDIO;
#define USBD_AUDIO_CLASS &USBD_AUDIO
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_AUDIO_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_AUDIO_ItfTypeDef *fops);
void USBD_AUDIO_Sync(USBD_HandleTypeDef *pdev, AUDIO_OffsetTypeDef offset);
#ifdef USE_USBD_COMPOSITE
uint32_t USBD_AUDIO_GetEpPcktSze(USBD_HandleTypeDef *pdev, uint8_t If, uint8_t Ep);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_AUDIO_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO | D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO\Inc\usbd_audio_if_template.h | /**
******************************************************************************
* @file usbd_audio_if_template.h
* @author MCD Application Team
* @brief Header for usbd_audio_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_AUDIO_IF_TEMPLATE_H
#define __USBD_AUDIO_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_audio.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
extern USBD_AUDIO_ItfTypeDef USBD_AUDIO_Template_fops;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#ifdef __cplusplus
}
#endif
#endif /* __USBD_AUDIO_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO | D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO\Src\usbd_audio.c | /**
******************************************************************************
* @file usbd_audio.c
* @author MCD Application Team
* @brief This file provides the Audio core functions.
*
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* AUDIO Class Description
* ===================================================================
* This driver manages the Audio Class 1.0 following the "USB Device Class Definition for
* Audio Devices V1.0 Mar 18, 98".
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Standard AC Interface Descriptor management
* - 1 Audio Streaming Interface (with single channel, PCM, Stereo mode)
* - 1 Audio Streaming Endpoint
* - 1 Audio Terminal Input (1 channel)
* - Audio Class-Specific AC Interfaces
* - Audio Class-Specific AS Interfaces
* - AudioControl Requests: only SET_CUR and GET_CUR requests are supported (for Mute)
* - Audio Feature Unit (limited to Mute control)
* - Audio Synchronization type: Asynchronous
* - Single fixed audio sampling rate (configurable in usbd_conf.h file)
* The current audio class version supports the following audio features:
* - Pulse Coded Modulation (PCM) format
* - sampling rate: 48KHz.
* - Bit resolution: 16
* - Number of channels: 2
* - No volume control
* - Mute/Unmute capability
* - Asynchronous Endpoints
*
* @note In HS mode and when the DMA is used, all variables and data structures
* dealing with the DMA during the transaction process should be 32-bit aligned.
*
*
* @endverbatim
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}_audio.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_audio.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_AUDIO
* @brief usbd core module
* @{
*/
/** @defgroup USBD_AUDIO_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Macros
* @{
*/
#define AUDIO_SAMPLE_FREQ(frq) \
(uint8_t)(frq), (uint8_t)((frq >> 8)), (uint8_t)((frq >> 16))
#define AUDIO_PACKET_SZE(frq) \
(uint8_t)(((frq * 2U * 2U) / 1000U) & 0xFFU), (uint8_t)((((frq * 2U * 2U) / 1000U) >> 8) & 0xFFU)
#ifdef USE_USBD_COMPOSITE
#define AUDIO_PACKET_SZE_WORD(frq) (uint32_t)((((frq) * 2U * 2U)/1000U))
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_AUDIO_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_AUDIO_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_AUDIO_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_AUDIO_GetCfgDesc(uint16_t *length);
static uint8_t *USBD_AUDIO_GetDeviceQualifierDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
static uint8_t USBD_AUDIO_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_AUDIO_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_AUDIO_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_AUDIO_EP0_TxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_AUDIO_SOF(USBD_HandleTypeDef *pdev);
static uint8_t USBD_AUDIO_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_AUDIO_IsoOutIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
static void AUDIO_REQ_GetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void AUDIO_REQ_SetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void *USBD_AUDIO_GetAudioHeaderDesc(uint8_t *pConfDesc);
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_AUDIO =
{
USBD_AUDIO_Init,
USBD_AUDIO_DeInit,
USBD_AUDIO_Setup,
USBD_AUDIO_EP0_TxReady,
USBD_AUDIO_EP0_RxReady,
USBD_AUDIO_DataIn,
USBD_AUDIO_DataOut,
USBD_AUDIO_SOF,
USBD_AUDIO_IsoINIncomplete,
USBD_AUDIO_IsoOutIncomplete,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_AUDIO_GetCfgDesc,
USBD_AUDIO_GetCfgDesc,
USBD_AUDIO_GetCfgDesc,
USBD_AUDIO_GetDeviceQualifierDesc,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB AUDIO device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_AUDIO_CfgDesc[USB_AUDIO_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration 1 */
0x09, /* bLength */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType */
LOBYTE(USB_AUDIO_CONFIG_DESC_SIZ), /* wTotalLength */
HIBYTE(USB_AUDIO_CONFIG_DESC_SIZ),
0x02, /* bNumInterfaces */
0x01, /* bConfigurationValue */
0x00, /* iConfiguration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/* 09 byte*/
/* USB Speaker Standard interface descriptor */
AUDIO_INTERFACE_DESC_SIZE, /* bLength */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */
0x00, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x00, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOCONTROL, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* 09 byte*/
/* USB Speaker Class-specific AC Interface Descriptor */
AUDIO_INTERFACE_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_HEADER, /* bDescriptorSubtype */
0x00, /* 1.00 */ /* bcdADC */
0x01,
0x27, /* wTotalLength */
0x00,
0x01, /* bInCollection */
0x01, /* baInterfaceNr */
/* 09 byte*/
/* USB Speaker Input Terminal Descriptor */
AUDIO_INPUT_TERMINAL_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_INPUT_TERMINAL, /* bDescriptorSubtype */
0x01, /* bTerminalID */
0x01, /* wTerminalType AUDIO_TERMINAL_USB_STREAMING 0x0101 */
0x01,
0x00, /* bAssocTerminal */
0x01, /* bNrChannels */
0x00, /* wChannelConfig 0x0000 Mono */
0x00,
0x00, /* iChannelNames */
0x00, /* iTerminal */
/* 12 byte*/
/* USB Speaker Audio Feature Unit Descriptor */
0x09, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_FEATURE_UNIT, /* bDescriptorSubtype */
AUDIO_OUT_STREAMING_CTRL, /* bUnitID */
0x01, /* bSourceID */
0x01, /* bControlSize */
AUDIO_CONTROL_MUTE, /* bmaControls(0) */
0, /* bmaControls(1) */
0x00, /* iTerminal */
/* 09 byte */
/* USB Speaker Output Terminal Descriptor */
0x09, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_OUTPUT_TERMINAL, /* bDescriptorSubtype */
0x03, /* bTerminalID */
0x01, /* wTerminalType 0x0301 */
0x03,
0x00, /* bAssocTerminal */
0x02, /* bSourceID */
0x00, /* iTerminal */
/* 09 byte */
/* USB Speaker Standard AS Interface Descriptor - Audio Streaming Zero Bandwidth */
/* Interface 1, Alternate Setting 0 */
AUDIO_INTERFACE_DESC_SIZE, /* bLength */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */
0x01, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x00, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOSTREAMING, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* 09 byte*/
/* USB Speaker Standard AS Interface Descriptor - Audio Streaming Operational */
/* Interface 1, Alternate Setting 1 */
AUDIO_INTERFACE_DESC_SIZE, /* bLength */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */
0x01, /* bInterfaceNumber */
0x01, /* bAlternateSetting */
0x01, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOSTREAMING, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* 09 byte*/
/* USB Speaker Audio Streaming Interface Descriptor */
AUDIO_STREAMING_INTERFACE_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_GENERAL, /* bDescriptorSubtype */
0x01, /* bTerminalLink */
0x01, /* bDelay */
0x01, /* wFormatTag AUDIO_FORMAT_PCM 0x0001 */
0x00,
/* 07 byte*/
/* USB Speaker Audio Type III Format Interface Descriptor */
0x0B, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_FORMAT_TYPE, /* bDescriptorSubtype */
AUDIO_FORMAT_TYPE_I, /* bFormatType */
0x02, /* bNrChannels */
0x02, /* bSubFrameSize : 2 Bytes per frame (16bits) */
16, /* bBitResolution (16-bits per sample) */
0x01, /* bSamFreqType only one frequency supported */
AUDIO_SAMPLE_FREQ(USBD_AUDIO_FREQ), /* Audio sampling frequency coded on 3 bytes */
/* 11 byte*/
/* Endpoint 1 - Standard Descriptor */
AUDIO_STANDARD_ENDPOINT_DESC_SIZE, /* bLength */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType */
AUDIO_OUT_EP, /* bEndpointAddress 1 out endpoint */
USBD_EP_TYPE_ISOC, /* bmAttributes */
AUDIO_PACKET_SZE(USBD_AUDIO_FREQ), /* wMaxPacketSize in Bytes (Freq(Samples)*2(Stereo)*2(HalfWord)) */
AUDIO_FS_BINTERVAL, /* bInterval */
0x00, /* bRefresh */
0x00, /* bSynchAddress */
/* 09 byte*/
/* Endpoint - Audio Streaming Descriptor */
AUDIO_STREAMING_ENDPOINT_DESC_SIZE, /* bLength */
AUDIO_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_ENDPOINT_GENERAL, /* bDescriptor */
0x00, /* bmAttributes */
0x00, /* bLockDelayUnits */
0x00, /* wLockDelay */
0x00,
/* 07 byte*/
} ;
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_AUDIO_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t AUDIOOutEpAdd = AUDIO_OUT_EP;
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Functions
* @{
*/
/**
* @brief USBD_AUDIO_Init
* Initialize the AUDIO interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_AUDIO_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_AUDIO_HandleTypeDef *haudio;
/* Allocate Audio structure */
haudio = (USBD_AUDIO_HandleTypeDef *)USBD_malloc(sizeof(USBD_AUDIO_HandleTypeDef));
if (haudio == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)haudio;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
AUDIOOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pdev->ep_out[AUDIOOutEpAdd & 0xFU].bInterval = AUDIO_HS_BINTERVAL;
}
else /* LOW and FULL-speed endpoints */
{
pdev->ep_out[AUDIOOutEpAdd & 0xFU].bInterval = AUDIO_FS_BINTERVAL;
}
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, AUDIOOutEpAdd, USBD_EP_TYPE_ISOC, AUDIO_OUT_PACKET);
pdev->ep_out[AUDIOOutEpAdd & 0xFU].is_used = 1U;
haudio->alt_setting = 0U;
haudio->offset = AUDIO_OFFSET_UNKNOWN;
haudio->wr_ptr = 0U;
haudio->rd_ptr = 0U;
haudio->rd_enable = 0U;
/* Initialize the Audio output Hardware layer */
if (((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init(USBD_AUDIO_FREQ,
AUDIO_DEFAULT_VOLUME,
0U) != 0U)
{
return (uint8_t)USBD_FAIL;
}
/* Prepare Out endpoint to receive 1st packet */
(void)USBD_LL_PrepareReceive(pdev, AUDIOOutEpAdd, haudio->buffer,
AUDIO_OUT_PACKET);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_Init
* DeInitialize the AUDIO layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_AUDIO_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
AUDIOOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Open EP OUT */
(void)USBD_LL_CloseEP(pdev, AUDIOOutEpAdd);
pdev->ep_out[AUDIOOutEpAdd & 0xFU].is_used = 0U;
pdev->ep_out[AUDIOOutEpAdd & 0xFU].bInterval = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit(0U);
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_Setup
* Handle the AUDIO specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_AUDIO_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_AUDIO_HandleTypeDef *haudio;
uint16_t len;
uint8_t *pbuf;
uint16_t status_info = 0U;
USBD_StatusTypeDef ret = USBD_OK;
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (haudio == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
switch (req->bRequest)
{
case AUDIO_REQ_GET_CUR:
AUDIO_REQ_GetCurrent(pdev, req);
break;
case AUDIO_REQ_SET_CUR:
AUDIO_REQ_SetCurrent(pdev, req);
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_DESCRIPTOR:
if ((req->wValue >> 8) == AUDIO_DESCRIPTOR_TYPE)
{
pbuf = (uint8_t *)USBD_AUDIO_GetAudioHeaderDesc(pdev->pConfDesc);
if (pbuf != NULL)
{
len = MIN(USB_AUDIO_DESC_SIZ, req->wLength);
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&haudio->alt_setting, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if ((uint8_t)(req->wValue) <= USBD_MAX_NUM_INTERFACES)
{
haudio->alt_setting = (uint8_t)(req->wValue);
}
else
{
/* Call the error management function (command will be NAKed */
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_AUDIO_GetCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_AUDIO_GetCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_AUDIO_CfgDesc);
return USBD_AUDIO_CfgDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_AUDIO_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_AUDIO_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(pdev);
UNUSED(epnum);
/* Only OUT data are processed */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_EP0_RxReady
* handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_AUDIO_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_AUDIO_HandleTypeDef *haudio;
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (haudio == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (haudio->control.cmd == AUDIO_REQ_SET_CUR)
{
/* In this driver, to simplify code, only SET_CUR request is managed */
if (haudio->control.unit == AUDIO_OUT_STREAMING_CTRL)
{
((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->MuteCtl(haudio->control.data[0]);
haudio->control.cmd = 0U;
haudio->control.len = 0U;
}
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_EP0_TxReady
* handle EP0 TRx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_AUDIO_EP0_TxReady(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
/* Only OUT control data are processed */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_SOF
* handle SOF event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_AUDIO_SOF(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_SOF
* handle SOF event
* @param pdev: device instance
* @param offset: audio offset
* @retval status
*/
void USBD_AUDIO_Sync(USBD_HandleTypeDef *pdev, AUDIO_OffsetTypeDef offset)
{
USBD_AUDIO_HandleTypeDef *haudio;
uint32_t BufferSize = AUDIO_TOTAL_BUF_SIZE / 2U;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return;
}
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
haudio->offset = offset;
if (haudio->rd_enable == 1U)
{
haudio->rd_ptr += (uint16_t)BufferSize;
if (haudio->rd_ptr == AUDIO_TOTAL_BUF_SIZE)
{
/* roll back */
haudio->rd_ptr = 0U;
}
}
if (haudio->rd_ptr > haudio->wr_ptr)
{
if ((haudio->rd_ptr - haudio->wr_ptr) < AUDIO_OUT_PACKET)
{
BufferSize += 4U;
}
else
{
if ((haudio->rd_ptr - haudio->wr_ptr) > (AUDIO_TOTAL_BUF_SIZE - AUDIO_OUT_PACKET))
{
BufferSize -= 4U;
}
}
}
else
{
if ((haudio->wr_ptr - haudio->rd_ptr) < AUDIO_OUT_PACKET)
{
BufferSize -= 4U;
}
else
{
if ((haudio->wr_ptr - haudio->rd_ptr) > (AUDIO_TOTAL_BUF_SIZE - AUDIO_OUT_PACKET))
{
BufferSize += 4U;
}
}
}
if (haudio->offset == AUDIO_OFFSET_FULL)
{
((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->AudioCmd(&haudio->buffer[0],
BufferSize, AUDIO_CMD_PLAY);
haudio->offset = AUDIO_OFFSET_NONE;
}
}
/**
* @brief USBD_AUDIO_IsoINIncomplete
* handle data ISO IN Incomplete event
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_AUDIO_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(pdev);
UNUSED(epnum);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_IsoOutIncomplete
* handle data ISO OUT Incomplete event
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_AUDIO_IsoOutIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_AUDIO_HandleTypeDef *haudio;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Prepare Out endpoint to receive next audio packet */
(void)USBD_LL_PrepareReceive(pdev, epnum,
&haudio->buffer[haudio->wr_ptr],
AUDIO_OUT_PACKET);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_AUDIO_DataOut
* handle data OUT Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_AUDIO_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
uint16_t PacketSize;
USBD_AUDIO_HandleTypeDef *haudio;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
AUDIOOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (haudio == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (epnum == AUDIOOutEpAdd)
{
/* Get received data packet length */
PacketSize = (uint16_t)USBD_LL_GetRxDataSize(pdev, epnum);
/* Packet received Callback */
((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->PeriodicTC(&haudio->buffer[haudio->wr_ptr],
PacketSize, AUDIO_OUT_TC);
/* Increment the Buffer pointer or roll it back when all buffers are full */
haudio->wr_ptr += PacketSize;
if (haudio->wr_ptr >= AUDIO_TOTAL_BUF_SIZE)
{
/* All buffers are full: roll back */
haudio->wr_ptr = 0U;
if (haudio->offset == AUDIO_OFFSET_UNKNOWN)
{
((USBD_AUDIO_ItfTypeDef *)pdev->pUserData[pdev->classId])->AudioCmd(&haudio->buffer[0],
AUDIO_TOTAL_BUF_SIZE / 2U,
AUDIO_CMD_START);
haudio->offset = AUDIO_OFFSET_NONE;
}
}
if (haudio->rd_enable == 0U)
{
if (haudio->wr_ptr == (AUDIO_TOTAL_BUF_SIZE / 2U))
{
haudio->rd_enable = 1U;
}
}
/* Prepare Out endpoint to receive next audio packet */
(void)USBD_LL_PrepareReceive(pdev, AUDIOOutEpAdd,
&haudio->buffer[haudio->wr_ptr],
AUDIO_OUT_PACKET);
}
return (uint8_t)USBD_OK;
}
/**
* @brief AUDIO_Req_GetCurrent
* Handles the GET_CUR Audio control request.
* @param pdev: device instance
* @param req: setup class request
* @retval status
*/
static void AUDIO_REQ_GetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_AUDIO_HandleTypeDef *haudio;
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (haudio == NULL)
{
return;
}
(void)USBD_memset(haudio->control.data, 0, USB_MAX_EP0_SIZE);
/* Send the current mute state */
(void)USBD_CtlSendData(pdev, haudio->control.data,
MIN(req->wLength, USB_MAX_EP0_SIZE));
}
/**
* @brief AUDIO_Req_SetCurrent
* Handles the SET_CUR Audio control request.
* @param pdev: device instance
* @param req: setup class request
* @retval status
*/
static void AUDIO_REQ_SetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_AUDIO_HandleTypeDef *haudio;
haudio = (USBD_AUDIO_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (haudio == NULL)
{
return;
}
if (req->wLength != 0U)
{
haudio->control.cmd = AUDIO_REQ_SET_CUR; /* Set the request value */
haudio->control.len = (uint8_t)MIN(req->wLength, USB_MAX_EP0_SIZE); /* Set the request data length */
haudio->control.unit = HIBYTE(req->wIndex); /* Set the request target unit */
/* Prepare the reception of the buffer over EP0 */
(void)USBD_CtlPrepareRx(pdev, haudio->control.data, haudio->control.len);
}
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_AUDIO_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_AUDIO_DeviceQualifierDesc);
return USBD_AUDIO_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_AUDIO_RegisterInterface
* @param pdev: device instance
* @param fops: Audio interface callback
* @retval status
*/
uint8_t USBD_AUDIO_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_AUDIO_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
#ifdef USE_USBD_COMPOSITE
/**
* @brief USBD_AUDIO_GetEpPcktSze
* @param pdev: device instance (reserved for future use)
* @param If: Interface number (reserved for future use)
* @param Ep: Endpoint number (reserved for future use)
* @retval status
*/
uint32_t USBD_AUDIO_GetEpPcktSze(USBD_HandleTypeDef *pdev, uint8_t If, uint8_t Ep)
{
uint32_t mps;
UNUSED(pdev);
UNUSED(If);
UNUSED(Ep);
mps = AUDIO_PACKET_SZE_WORD(USBD_AUDIO_FREQ);
/* Return the wMaxPacketSize value in Bytes (Freq(Samples)*2(Stereo)*2(HalfWord)) */
return mps;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_AUDIO_GetAudioHeaderDesc
* This function return the Audio descriptor
* @param pdev: device instance
* @param pConfDesc: pointer to Bos descriptor
* @retval pointer to the Audio AC Header descriptor
*/
static void *USBD_AUDIO_GetAudioHeaderDesc(uint8_t *pConfDesc)
{
USBD_ConfigDescTypeDef *desc = (USBD_ConfigDescTypeDef *)(void *)pConfDesc;
USBD_DescHeaderTypeDef *pdesc = (USBD_DescHeaderTypeDef *)(void *)pConfDesc;
uint8_t *pAudioDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_GetNextDesc((uint8_t *)pdesc, &ptr);
if ((pdesc->bDescriptorType == AUDIO_INTERFACE_DESCRIPTOR_TYPE) &&
(pdesc->bDescriptorSubType == AUDIO_CONTROL_HEADER))
{
pAudioDesc = (uint8_t *)pdesc;
break;
}
}
}
return pAudioDesc;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO | D://workCode//uploadProject\stm32_mw_usb_device\Class\AUDIO\Src\usbd_audio_if_template.c | /**
******************************************************************************
* @file usbd_cdc_if_template.c
* @author MCD Application Team
* @brief Generic media access Layer.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}_audio.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_audio_if_template.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_AUDIO
* @brief usbd core module
* @{
*/
/** @defgroup USBD_AUDIO_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_AUDIO_Private_FunctionPrototypes
* @{
*/
static int8_t TEMPLATE_Init(uint32_t AudioFreq, uint32_t Volume, uint32_t options);
static int8_t TEMPLATE_DeInit(uint32_t options);
static int8_t TEMPLATE_AudioCmd(uint8_t *pbuf, uint32_t size, uint8_t cmd);
static int8_t TEMPLATE_VolumeCtl(uint8_t vol);
static int8_t TEMPLATE_MuteCtl(uint8_t cmd);
static int8_t TEMPLATE_PeriodicTC(uint8_t *pbuf, uint32_t size, uint8_t cmd);
static int8_t TEMPLATE_GetState(void);
USBD_AUDIO_ItfTypeDef USBD_AUDIO_Template_fops =
{
TEMPLATE_Init,
TEMPLATE_DeInit,
TEMPLATE_AudioCmd,
TEMPLATE_VolumeCtl,
TEMPLATE_MuteCtl,
TEMPLATE_PeriodicTC,
TEMPLATE_GetState,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief TEMPLATE_Init
* Initializes the AUDIO media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Init(uint32_t AudioFreq, uint32_t Volume, uint32_t options)
{
UNUSED(AudioFreq);
UNUSED(Volume);
UNUSED(options);
/*
Add your initialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_DeInit
* DeInitializes the AUDIO media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_DeInit(uint32_t options)
{
UNUSED(options);
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_AudioCmd
* AUDIO command handler
* @param Buf: Buffer of data to be sent
* @param size: Number of data to be sent (in bytes)
* @param cmd: command opcode
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_AudioCmd(uint8_t *pbuf, uint32_t size, uint8_t cmd)
{
UNUSED(pbuf);
UNUSED(size);
UNUSED(cmd);
return (0);
}
/**
* @brief TEMPLATE_VolumeCtl
* @param vol: volume level (0..100)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_VolumeCtl(uint8_t vol)
{
UNUSED(vol);
return (0);
}
/**
* @brief TEMPLATE_MuteCtl
* @param cmd: vmute command
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_MuteCtl(uint8_t cmd)
{
UNUSED(cmd);
return (0);
}
/**
* @brief TEMPLATE_PeriodicTC
* @param cmd
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_PeriodicTC(uint8_t *pbuf, uint32_t size, uint8_t cmd)
{
UNUSED(pbuf);
UNUSED(size);
UNUSED(cmd);
return (0);
}
/**
* @brief TEMPLATE_GetState
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_GetState(void)
{
return (0);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\BillBoard | D://workCode//uploadProject\stm32_mw_usb_device\Class\BillBoard\Inc\usbd_billboard.h | /**
******************************************************************************
* @file usbd_billboard.h
* @author MCD Application Team
* @brief Header file for the usbd_billboard.c file.
******************************************************************************
* @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 __USB_BB_H
#define __USB_BB_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
#include "usbd_desc.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_BB
* @brief This file is the Header file for usbd_billboard.c
* @{
*/
/** @defgroup USBD_BB_Exported_Defines
* @{
*/
#define USB_BB_CONFIG_DESC_SIZ 18U
#ifndef USB_BB_MAX_NUM_ALT_MODE
#define USB_BB_MAX_NUM_ALT_MODE 0x2U
#endif /* USB_BB_MAX_NUM_ALT_MODE */
#ifndef USBD_BB_IF_STRING_INDEX
#define USBD_BB_IF_STRING_INDEX 0x10U
#endif /* USBD_BB_IF_STRING_INDEX */
#define USBD_BILLBOARD_CAPABILITY 0x0DU
#define USBD_BILLBOARD_ALTMODE_CAPABILITY 0x0FU
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef struct _BB_DescHeader
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDevCapabilityType;
}
USBD_BB_DescHeader_t;
typedef struct
{
uint16_t wSVID;
uint8_t bAlternateMode;
uint8_t iAlternateModeString;
} USBD_BB_AltModeTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDevCapabilityType;
uint8_t bIndex;
uint32_t dwAlternateModeVdo;
} USBD_BB_AltModeCapDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDevCapabilityType;
uint8_t iAddtionalInfoURL;
uint8_t bNbrOfAltModes;
uint8_t bPreferredAltMode;
uint16_t VconnPwr;
uint8_t bmConfigured[32];
uint16_t bcdVersion;
uint8_t bAdditionalFailureInfo;
uint8_t bReserved;
USBD_BB_AltModeTypeDef wSVID[USB_BB_MAX_NUM_ALT_MODE];
} USBD_BosBBCapDescTypedef;
typedef enum
{
UNSPECIFIED_ERROR = 0,
CONFIGURATION_NOT_ATTEMPTED,
CONFIGURATION_UNSUCCESSFUL,
CONFIGURATION_SUCCESSFUL,
} BB_AltModeState;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_BB;
#define USBD_BB_CLASS &USBD_BB
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
#if (USBD_CLASS_BOS_ENABLED == 1)
void *USBD_BB_GetCapDesc(USBD_HandleTypeDef *pdev, uint8_t *buf);
void *USBD_BB_GetAltModeDesc(USBD_HandleTypeDef *pdev, uint8_t *buf, uint8_t idx);
#endif /* (USBD_CLASS_BOS_ENABLED == 1) */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_BB_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\BillBoard | D://workCode//uploadProject\stm32_mw_usb_device\Class\BillBoard\Src\usbd_billboard.c | /**
******************************************************************************
* @file usbd_billboard.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB BillBoard Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as BillBoard Device
* - Error 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
*
* ===================================================================
* BillBoard Class Description
* ===================================================================
* This module manages the BillBoard class V1.2.1 following the "Device Class Definition
* for BillBoard Devices (BB) Version R1.2.1 Sept 08, 2016".
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as an USB BillBoard device
* - Enumeration & management of BillBoard device supported alternate modes
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_billboard.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_BB
* @brief usbd core module
* @{
*/
/** @defgroup USBD_BB_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_BB_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_BB_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_BB_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_BB_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_BB_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_BB_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_BB_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_BB_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_BB_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t *USBD_BB_GetCfgDesc(uint16_t *length);
static uint8_t *USBD_BB_GetDeviceQualifierDesc(uint16_t *length);
static uint8_t *USBD_BB_GetOtherSpeedCfgDesc(uint16_t *length);
#if (USBD_CLASS_BOS_ENABLED == 1)
USBD_BB_DescHeader_t *USBD_BB_GetNextDesc(uint8_t *pbuf, uint16_t *ptr);
#endif /* USBD_CLASS_BOS_ENABLED */
/**
* @}
*/
/** @defgroup USBD_BB_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_BB =
{
USBD_BB_Init, /* Init */
USBD_BB_DeInit, /* DeInit */
USBD_BB_Setup, /* Setup */
NULL, /* EP0_TxSent */
USBD_BB_EP0_RxReady, /* EP0_RxReady */
USBD_BB_DataIn, /* DataIn */
USBD_BB_DataOut, /* DataOut */
NULL, /* SOF */
NULL,
NULL,
USBD_BB_GetCfgDesc,
USBD_BB_GetCfgDesc,
USBD_BB_GetOtherSpeedCfgDesc,
USBD_BB_GetDeviceQualifierDesc,
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
NULL,
#endif /* USBD_SUPPORT_USER_STRING_DESC */
};
/* USB Standard Device Qualifier Descriptor */
__ALIGN_BEGIN static uint8_t USBD_BB_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC, /* bLength */
USB_DESC_TYPE_DEVICE_QUALIFIER, /* bDescriptorType */
0x01, /* bcdUSB */
0x20,
0x11, /* bDeviceClass */
0x00, /* bDeviceSubClass */
0x00, /* bDeviceProtocol */
0x40, /* bMaxPacketSize0 */
0x01, /* bNumConfigurations */
0x00, /* bReserved */
};
/* USB device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_BB_CfgDesc[USB_BB_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_BB_CONFIG_DESC_SIZ, /* wTotalLength: Bytes returned */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
USBD_IDX_CONFIG_STR, /* iConfiguration: Index of string descriptor describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/* 09 */
/************** Descriptor of BillBoard interface ****************/
/* 09 */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x00, /* bNumEndpoints */
0x11, /* bInterfaceClass: billboard */
0x00, /* bInterfaceSubClass */
0x00, /* nInterfaceProtocol */
USBD_BB_IF_STRING_INDEX, /* iInterface: Index of string descriptor */
};
/* USB device Other Speed Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_BB_OtherSpeedCfgDesc[USB_BB_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION,
USB_BB_CONFIG_DESC_SIZ,
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue */
USBD_IDX_CONFIG_STR, /* iConfiguration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/************** Descriptor of BillBoard interface ****************/
/* 09 */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x00, /* bNumEndpoints*/
0x11, /* bInterfaceClass: billboard */
0x00, /* bInterfaceSubClass */
0x00, /* nInterfaceProtocol */
USBD_BB_IF_STRING_INDEX, /* iInterface: Index of string descriptor */
} ;
/**
* @}
*/
/** @defgroup USBD_BB_Private_Functions
* @{
*/
/**
* @brief USBD_BB_Init
* Initialize the BB interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_BB_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
UNUSED(cfgidx);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_BB_Init
* DeInitialize the BB layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_BB_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
UNUSED(cfgidx);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_BB_Setup
* Handle the BB specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_BB_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
uint16_t status_info = 0U;
uint16_t AltSetting = 0U;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&AltSetting, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_BB_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_BB_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
UNUSED(epnum);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_BB_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_BB_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
UNUSED(epnum);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_BB_EP0_RxReady
* Handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_BB_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_BB_GetCfgDesc
* return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_BB_GetCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_BB_CfgDesc);
return USBD_BB_CfgDesc;
}
/**
* @brief USBD_BB_GetOtherSpeedCfgDesc
* return other speed configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_BB_GetOtherSpeedCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_BB_OtherSpeedCfgDesc);
return USBD_BB_OtherSpeedCfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_BB_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_BB_DeviceQualifierDesc);
return USBD_BB_DeviceQualifierDesc;
}
#if (USBD_CLASS_BOS_ENABLED == 1U)
/**
* @brief USBD_BB_GetNextDesc
* This function return the next descriptor header
* @param buf: Buffer where the descriptor is available
* @param ptr: data pointer inside the descriptor
* @retval next header
*/
USBD_BB_DescHeader_t *USBD_BB_GetNextDesc(uint8_t *pbuf, uint16_t *ptr)
{
USBD_BB_DescHeader_t *pnext = (USBD_BB_DescHeader_t *)(void *)pbuf;
*ptr += pnext->bLength;
pnext = (USBD_BB_DescHeader_t *)(void *)(pbuf + pnext->bLength);
return (pnext);
}
/**
* @brief USBD_BB_GetCapDesc
* This function return the Billboard Capability descriptor
* @param pdev: device instance
* @param pBosDesc: pointer to Bos descriptor
* @retval pointer to Billboard Capability descriptor
*/
void *USBD_BB_GetCapDesc(USBD_HandleTypeDef *pdev, uint8_t *pBosDesc)
{
UNUSED(pdev);
USBD_BB_DescHeader_t *pdesc = (USBD_BB_DescHeader_t *)(void *)pBosDesc;
USBD_BosDescTypeDef *desc = (USBD_BosDescTypeDef *)(void *)pBosDesc;
USBD_BosBBCapDescTypedef *pCapDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_BB_GetNextDesc((uint8_t *)pdesc, &ptr);
if (pdesc->bDevCapabilityType == USBD_BILLBOARD_CAPABILITY)
{
pCapDesc = (USBD_BosBBCapDescTypedef *)(void *)pdesc;
break;
}
}
}
return (void *)pCapDesc;
}
/**
* @brief USBD_BB_GetAltModeDesc
* This function return the Billboard Alternate Mode descriptor
* @param pdev: device instance
* @param pBosDesc: pointer to Bos descriptor
* @param idx: Index of requested Alternate Mode descriptor
* @retval pointer to Alternate Mode descriptor
*/
void *USBD_BB_GetAltModeDesc(USBD_HandleTypeDef *pdev, uint8_t *pBosDesc, uint8_t idx)
{
UNUSED(pdev);
USBD_BB_DescHeader_t *pdesc = (USBD_BB_DescHeader_t *)(void *)pBosDesc;
USBD_BosDescTypeDef *desc = (USBD_BosDescTypeDef *)(void *)pBosDesc;
USBD_BB_AltModeCapDescTypeDef *pAltModDesc = NULL;
uint8_t cnt = 0U;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_BB_GetNextDesc((uint8_t *)pdesc, &ptr);
if (pdesc->bDevCapabilityType == USBD_BILLBOARD_ALTMODE_CAPABILITY)
{
if (cnt == idx)
{
pAltModDesc = (USBD_BB_AltModeCapDescTypeDef *)(void *)pdesc;
break;
}
else
{
cnt++;
}
}
}
}
return (void *)pAltModDesc;
}
#endif /* USBD_CLASS_BOS_ENABLED */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Inc\usbd_ccid.h | /**
******************************************************************************
* @file usbd_ccid.h
* @author MCD Application Team
* @brief header file for the usbd_ccid.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CCID_H
#define __USBD_CCID_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_cdc
* @brief This file is the Header file for usbd_ccid.c
* @{
*/
/** @defgroup usbd_cdc_Exported_Defines
* @{
*/
#ifndef CCID_IN_EP
#define CCID_IN_EP 0x81U /* EP1 for data IN */
#endif /* CCID_IN_EP */
#ifndef CCID_OUT_EP
#define CCID_OUT_EP 0x01U /* EP1 for data OUT */
#endif /* CCID_OUT_EP */
#ifndef CCID_CMD_EP
#define CCID_CMD_EP 0x82U /* EP2 for CCID commands */
#endif /* CCID_CMD_EP */
#ifndef CCID_CMD_HS_BINTERVAL
#define CCID_CMD_HS_BINTERVAL 0x10U
#endif /* CCID_CMD_HS_BINTERVAL */
#ifndef CCID_CMD_FS_BINTERVAL
#define CCID_CMD_FS_BINTERVAL 0x10U
#endif /* CCID_CMD_FS_BINTERVAL */
#define CCID_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#define CCID_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define CCID_CMD_PACKET_SIZE 8U /* Control Endpoint Packet size */
#define USB_CCID_CONFIG_DESC_SIZ 93U
#define CCID_DATA_HS_IN_PACKET_SIZE CCID_DATA_HS_MAX_PACKET_SIZE
#define CCID_DATA_HS_OUT_PACKET_SIZE CCID_DATA_HS_MAX_PACKET_SIZE
#define CCID_DATA_FS_IN_PACKET_SIZE CCID_DATA_FS_MAX_PACKET_SIZE
#define CCID_DATA_FS_OUT_PACKET_SIZE CCID_DATA_FS_MAX_PACKET_SIZE
/*---------------------------------------------------------------------*/
/* CCID definitions */
/*---------------------------------------------------------------------*/
#define CCID_SEND_ENCAPSULATED_COMMAND 0x00U
#define CCID_GET_ENCAPSULATED_RESPONSE 0x01U
#define CCID_SET_COMM_FEATURE 0x02U
#define CCID_GET_COMM_FEATURE 0x03U
#define CCID_CLEAR_COMM_FEATURE 0x04U
#define CCID_SET_LINE_CODING 0x20U
#define CCID_GET_LINE_CODING 0x21U
#define CCID_SET_CONTROL_LINE_STATE 0x22U
#define CCID_SEND_BREAK 0x23U
/*---------------------------------------------------------------------*/
#define REQUEST_ABORT 0x01U
#define REQUEST_GET_CLOCK_FREQUENCIES 0x02U
#define REQUEST_GET_DATA_RATES 0x03U
/*---------------------------------------------------------------------*/
/* The Smart Card Device Class Descriptor definitions */
/*---------------------------------------------------------------------*/
#define CCID_INTERFACE_DESC_SIZE 0x09U
#define USB_DEVICE_CLASS_CCID 0x0BU
#define CCID_CLASS_DESC_SIZE 0x36U
#define CCID_DESC_TYPE 0x21U
#ifndef CCID_VOLTAGE_SUPP
#define CCID_VOLTAGE_SUPP 0x07U
#endif /* CCID_VOLTAGE_SUPP */
#ifndef USBD_CCID_PROTOCOL
#define USBD_CCID_PROTOCOL 0x03U
#endif /* USBD_CCID_PROTOCOL */
#ifndef USBD_CCID_DEFAULT_CLOCK_FREQ
#define USBD_CCID_DEFAULT_CLOCK_FREQ 3600U
#endif /* USBD_CCID_DEFAULT_CLOCK_FREQ */
#ifndef USBD_CCID_MAX_CLOCK_FREQ
#define USBD_CCID_MAX_CLOCK_FREQ USBD_CCID_DEFAULT_CLOCK_FREQ
#endif /* USBD_CCID_MAX_CLOCK_FREQ */
#ifndef USBD_CCID_DEFAULT_DATA_RATE
#define USBD_CCID_DEFAULT_DATA_RATE 9677U
#endif /* USBD_CCID_DEFAULT_DATA_RATE */
#ifndef USBD_CCID_MAX_DATA_RATE
#define USBD_CCID_MAX_DATA_RATE USBD_CCID_DEFAULT_DATA_RATE
#endif /* USBD_CCID_MAX_DATA_RATE */
#ifndef USBD_CCID_MAX_INF_FIELD_SIZE
#define USBD_CCID_MAX_INF_FIELD_SIZE 254U
#endif /* USBD_CCID_MAX_INF_FIELD_SIZE */
#ifndef CCID_MAX_BLOCK_SIZE_HEADER
#define CCID_MAX_BLOCK_SIZE_HEADER 271U
#endif /* CCID_MAX_BLOCK_SIZE_HEADER */
#define TPDU_EXCHANGE 0x01U
#define SHORT_APDU_EXCHANGE 0x02U
#define EXTENDED_APDU_EXCHANGE 0x04U
#define CHARACTER_EXCHANGE 0x00U
#ifndef EXCHANGE_LEVEL_FEATURE
#define EXCHANGE_LEVEL_FEATURE TPDU_EXCHANGE
#endif /* EXCHANGE_LEVEL_FEATURE */
#define CCID_ENDPOINT_DESC_SIZE 0x07U
#ifndef CCID_EP0_BUFF_SIZ
#define CCID_EP0_BUFF_SIZ 64U
#endif /* CCID_EP0_BUFF_SIZ */
#ifndef CCID_BULK_EPIN_SIZE
#define CCID_BULK_EPIN_SIZE 64U
#endif /* CCID_BULK_EPIN_SIZE */
#define CCID_INT_BUFF_SIZ 2U
/*---------------------------------------------------------------------*/
/*
* CCID Class specification revision 1.1
* Command Pipe. Bulk Messages
*/
/* CCID Bulk Out Command definitions */
#define PC_TO_RDR_ICCPOWERON 0x62U
#define PC_TO_RDR_ICCPOWEROFF 0x63U
#define PC_TO_RDR_GETSLOTSTATUS 0x65U
#define PC_TO_RDR_XFRBLOCK 0x6FU
#define PC_TO_RDR_GETPARAMETERS 0x6CU
#define PC_TO_RDR_RESETPARAMETERS 0x6DU
#define PC_TO_RDR_SETPARAMETERS 0x61U
#define PC_TO_RDR_ESCAPE 0x6BU
#define PC_TO_RDR_ICCCLOCK 0x6EU
#define PC_TO_RDR_T0APDU 0x6AU
#define PC_TO_RDR_SECURE 0x69U
#define PC_TO_RDR_MECHANICAL 0x71U
#define PC_TO_RDR_ABORT 0x72U
#define PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY 0x73U
/* CCID Bulk In Command definitions */
#define RDR_TO_PC_DATABLOCK 0x80U
#define RDR_TO_PC_SLOTSTATUS 0x81U
#define RDR_TO_PC_PARAMETERS 0x82U
#define RDR_TO_PC_ESCAPE 0x83U
#define RDR_TO_PC_DATARATEANDCLOCKFREQUENCY 0x84U
/* CCID Interrupt In Command definitions */
#define RDR_TO_PC_NOTIFYSLOTCHANGE 0x50U
#define RDR_TO_PC_HARDWAREERROR 0x51U
/* Bulk-only Command Block Wrapper */
#define ABDATA_SIZE 261U
#define CCID_CMD_HEADER_SIZE 10U
#define CCID_RESPONSE_HEADER_SIZE 10U
/* Number of SLOTS. For single card, this value is 1 */
#define CCID_NUMBER_OF_SLOTS 1U
#define CARD_SLOT_FITTED 1U
#define CARD_SLOT_REMOVED 0U
#define OFFSET_INT_BMESSAGETYPE 0x00U
#define OFFSET_INT_BMSLOTICCSTATE 0x01U
#define SLOT_ICC_PRESENT 0x01U
/* LSb : (0b = no ICC present, 1b = ICC present) */
#define SLOT_ICC_CHANGE 0x02U
/* MSb : (0b = no change, 1b = change) */
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct
{
uint32_t bitrate;
uint8_t format;
uint8_t paritytype;
uint8_t datatype;
} USBD_CCID_LineCodingTypeDef;
typedef struct
{
uint8_t bMessageType; /* Offset = 0*/
uint32_t dwLength; /* Offset = 1, The length field (dwLength) is the length
of the message not including the 10-byte header.*/
uint8_t bSlot; /* Offset = 5*/
uint8_t bSeq; /* Offset = 6*/
uint8_t bSpecific_0; /* Offset = 7*/
uint8_t bSpecific_1; /* Offset = 8*/
uint8_t bSpecific_2; /* Offset = 9*/
uint8_t abData [ABDATA_SIZE]; /* Offset = 10, For reference, the absolute
maximum block size for a TPDU T=0 block is 260 bytes
(5 bytes command; 255 bytes data),
or for a TPDU T=1 block is 259 bytes,
or for a short APDU T=1 block is 261 bytes,
or for an extended APDU T=1 block is 65544 bytes.*/
} __PACKED USBD_CCID_BulkOut_DataTypeDef;
typedef struct
{
uint8_t bMessageType; /* Offset = 0 */
uint32_t dwLength; /* Offset = 1 */
uint8_t bSlot; /* Offset = 5, Same as Bulk-OUT message */
uint8_t bSeq; /* Offset = 6, Same as Bulk-OUT message */
uint8_t bStatus; /* Offset = 7, Slot status as defined in section 6.2.6 */
uint8_t bError; /* Offset = 8, Slot error as defined in section 6.2.6 */
uint8_t bSpecific; /* Offset = 9 */
uint8_t abData[ABDATA_SIZE]; /* Offset = 10 */
uint16_t u16SizeToSend;
} __PACKED USBD_CCID_BulkIn_DataTypeDef;
typedef struct
{
__IO uint8_t SlotStatus;
__IO uint8_t SlotStatusChange;
} USBD_CCID_SlotStatusTypeDef;
typedef struct
{
__IO uint8_t bAbortRequestFlag;
__IO uint8_t bSeq;
__IO uint8_t bSlot;
} USBD_CCID_ParamTypeDef;
/*
* CCID Class specification revision 1.1
* Smart Card Device Class Descriptor Table
*/
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdCCID;
uint8_t bMaxSlotIndex;
uint8_t bVoltageSupport;
uint32_t dwProtocols;
uint32_t dwDefaultClock;
uint32_t dwMaximumClock;
uint8_t bNumClockSupported;
uint32_t dwDataRate;
uint32_t dwMaxDataRate;
uint8_t bNumDataRatesSupported;
uint32_t dwMaxIFSD;
uint32_t dwSynchProtocols;
uint32_t dwMechanical;
uint32_t dwFeatures;
uint32_t dwMaxCCIDMessageLength;
uint8_t bClassGetResponse;
uint8_t bClassEnvelope;
uint16_t wLcdLayout;
uint8_t bPINSupport;
uint8_t bMaxCCIDBusySlots;
} __PACKED USBD_CCID_DescTypeDef;
typedef struct
{
uint8_t data[CCID_DATA_HS_MAX_PACKET_SIZE / 4U]; /* Force 32-bit alignment */
uint32_t UsbMessageLength;
uint8_t UsbIntData[CCID_CMD_PACKET_SIZE]; /* Buffer for the Interrupt In Data */
uint32_t alt_setting;
USBD_CCID_BulkIn_DataTypeDef UsbBlkInData; /* Buffer for the Out Data */
USBD_CCID_BulkOut_DataTypeDef UsbBlkOutData; /* Buffer for the In Data */
USBD_CCID_SlotStatusTypeDef SlotStatus;
USBD_CCID_ParamTypeDef USBD_CCID_Param;
__IO uint32_t MaxPcktLen;
__IO uint8_t blkt_state; /* Bulk transfer state */
uint16_t slot_nb;
uint16_t seq_nb;
} USBD_CCID_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CCID;
#define USBD_CCID_CLASS &USBD_CCID
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
typedef struct _USBD_CCID_Itf
{
uint8_t (* Init)(USBD_HandleTypeDef *pdev);
uint8_t (* DeInit)(USBD_HandleTypeDef *pdev);
uint8_t (* Control)(uint8_t req, uint8_t *pbuf, uint16_t *length);
uint8_t (* Response_SendData)(USBD_HandleTypeDef *pdev, uint8_t *buf, uint16_t len);
uint8_t (* Send_Process)(uint8_t *Command, uint8_t *Data);
uint8_t (* SetSlotStatus)(USBD_HandleTypeDef *pdev);
} USBD_CCID_ItfTypeDef;
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_CCID_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CCID_ItfTypeDef *fops);
uint8_t USBD_CCID_IntMessage(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CCID_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Inc\usbd_ccid_cmd.h | /**
******************************************************************************
* @file usbd_ccid_cmd.h
* @author MCD Application Team
* @brief header file for the usbd_ccid_cmd.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CCID_CMD_H
#define __USBD_CCID_CMD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#ifndef __USBD_CCID_IF_H
#include "usbd_ccid_if_template.h"
#endif /* __USBD_CCID_IF_H */
#ifndef __USBD_CCID_SC_IF_H
#include "usbd_ccid_sc_if_template.h"
#endif /* __USBD_CCID_SC_IF_H */
/* Exported types ------------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/******************************************************************************/
/* ERROR CODES for USB Bulk In Messages : bError */
/******************************************************************************/
#define SLOT_NO_ERROR 0x81U
#define SLOTERROR_UNKNOWN 0x82U
/*----------------------------------------------------------------------------*/
/* Index of not supported / incorrect message parameter : 7Fh to 01h */
/* These Values are used for Return Types between Firmware Layers */
/*
Failure of a command
The CCID cannot parse one parameter or the ICC is not supporting one parameter.
Then the Slot Error register contains the index of the first bad parameter as a
positive number (1-127). For instance, if the CCID receives an ICC command to
an unimplemented slot, then the Slot Error register shall be set to 5 (index of bSlot field) */
/*
* CCID Class specification revision 1.1
*/
/* Following Parameters used in PC_to_RDR_XfrBlock */
#define SLOTERROR_BAD_LENTGH 0x01U
#define SLOTERROR_BAD_SLOT 0x05U
#define SLOTERROR_BAD_POWERSELECT 0x07U
#define SLOTERROR_BAD_PROTOCOLNUM 0x07U
#define SLOTERROR_BAD_CLOCKCOMMAND 0x07U
#define SLOTERROR_BAD_ABRFU_3B 0x07U
#define SLOTERROR_BAD_BMCHANGES 0x07U
#define SLOTERROR_BAD_BFUNCTION_MECHANICAL 0x07U
#define SLOTERROR_BAD_ABRFU_2B 0x08U
#define SLOTERROR_BAD_LEVELPARAMETER 0x08U
#define SLOTERROR_BAD_FIDI 0x0AU
#define SLOTERROR_BAD_T01CONVCHECKSUM 0x0BU
#define SLOTERROR_BAD_GUARDTIME 0x0CU
#define SLOTERROR_BAD_WAITINGINTEGER 0x0DU
#define SLOTERROR_BAD_CLOCKSTOP 0x0EU
#define SLOTERROR_BAD_IFSC 0x0FU
#define SLOTERROR_BAD_NAD 0x10U
#define SLOTERROR_BAD_DWLENGTH 0x08U
/*---------- Table 6.2-2 Slot error register when bmCommandStatus = 1 */
#define SLOTERROR_CMD_ABORTED 0xFFU
#define SLOTERROR_ICC_MUTE 0xFEU
#define SLOTERROR_XFR_PARITY_ERROR 0xFDU
#define SLOTERROR_XFR_OVERRUN 0xFCU
#define SLOTERROR_HW_ERROR 0xFBU
#define SLOTERROR_BAD_ATR_TS 0xF8U
#define SLOTERROR_BAD_ATR_TCK 0xF7U
#define SLOTERROR_ICC_PROTOCOL_NOT_SUPPORTED 0xF6U
#define SLOTERROR_ICC_CLASS_NOT_SUPPORTED 0xF5U
#define SLOTERROR_PROCEDURE_BYTE_CONFLICT 0xF4U
#define SLOTERROR_DEACTIVATED_PROTOCOL 0xF3U
#define SLOTERROR_BUSY_WITH_AUTO_SEQUENCE 0xF2U
#define SLOTERROR_PIN_TIMEOUT 0xF0U
#define SLOTERROR_PIN_CANCELLED 0xEFU
#define SLOTERROR_CMD_SLOT_BUSY 0xE0U
#define SLOTERROR_CMD_NOT_SUPPORTED 0x00U
/* Following Parameters used in PC_to_RDR_ResetParameters */
/* DEFAULT_FIDI_VALUE */
#ifndef DEFAULT_FIDI
#define DEFAULT_FIDI 0x11U
#endif /* DEFAULT_FIDI */
#ifndef DEFAULT_T01CONVCHECKSUM
#define DEFAULT_T01CONVCHECKSUM 0x00U
#endif /* DEFAULT_T01CONVCHECKSUM */
#ifndef DEFAULT_EXTRA_GUARDTIME
#define DEFAULT_EXTRA_GUARDTIME 0x00U
#endif /* DEFAULT_EXTRA_GUARDTIME */
#ifndef DEFAULT_WAITINGINTEGER
#define DEFAULT_WAITINGINTEGER 0x0AU
#endif /* DEFAULT_WAITINGINTEGER */
#ifndef DEFAULT_CLOCKSTOP
#define DEFAULT_CLOCKSTOP 0x00U
#endif /* DEFAULT_CLOCKSTOP */
#ifndef DEFAULT_IFSC
#define DEFAULT_IFSC 0x20U
#endif /* DEFAULT_IFSC */
#ifndef DEFAULT_NAD
#define DEFAULT_NAD 0x00U
#endif /* DEFAULT_NAD */
/* Following Parameters used in PC_to_RDR_IccPowerOn */
#define VOLTAGE_SELECTION_AUTOMATIC 0xFFU
#define VOLTAGE_SELECTION_3V 0x02U
#define VOLTAGE_SELECTION_5V 0x01U
#define VOLTAGE_SELECTION_1V8 0x03U
/*
Offset=0 bmICCStatus 2 bit 0, 1, 2
0 - An ICC is present and active (power is on and stable, RST is inactive)
1 - An ICC is present and inactive (not activated or shut down by hardware error)
2 - No ICC is present
3 - RFU
Offset=0 bmRFU 4 bits 0 RFU
Offset=6 bmCommandStatus 2 bits 0, 1, 2
0 - Processed without error
1 - Failed (error code provided by the error register)
2 - Time Extension is requested
3 - RFU
*/
#define BM_ICC_PRESENT_ACTIVE 0x00U
#define BM_ICC_PRESENT_INACTIVE 0x01U
#define BM_ICC_NO_ICC_PRESENT 0x02U
#define BM_COMMAND_STATUS_OFFSET 0x06U
#define BM_COMMAND_STATUS_NO_ERROR 0x00U
#define BM_COMMAND_STATUS_FAILED (0x01U << BM_COMMAND_STATUS_OFFSET)
#define BM_COMMAND_STATUS_TIME_EXTN (0x02 << BM_COMMAND_STATUS_OFFSET)
#if (ATR_T01 == 0)
#define SIZE_OF_ATR 19U
#else
#define SIZE_OF_ATR 15U
#endif /* (ATR_T01 == 0) */
/* defines for the CCID_CMD Layers */
#define LEN_PROTOCOL_STRUCT_T0 5U
#define LEN_PROTOCOL_STRUCT_T1 7U
#define BPROTOCOL_NUM_T0 0U
#define BPROTOCOL_NUM_T1 1U
/************************************************************************************/
/* ERROR CODES for RDR_TO_PC_HARDWAREERROR Message : bHardwareErrorCode */
/************************************************************************************/
#define HARDWAREERRORCODE_OVERCURRENT 0x01U
#define HARDWAREERRORCODE_VOLTAGEERROR 0x02U
#define HARDWAREERRORCODE_OVERCURRENT_IT 0x04U
#define HARDWAREERRORCODE_VOLTAGEERROR_IT 0x08U
#define CHK_PARAM_SLOT 0x01U
#define CHK_PARAM_DWLENGTH 0x02U
#define CHK_PARAM_ABRFU2 0x04U
#define CHK_PARAM_ABRFU3 0x08U
#define CHK_PARAM_CARD_PRESENT 0x10U
#define CHK_PARAM_ABORT 0x20U
#define CHK_ACTIVE_STATE 0x40U
/* Exported functions ------------------------------------------------------- */
uint8_t PC_to_RDR_IccPowerOn(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_IccPowerOff(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_GetSlotStatus(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_XfrBlock(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_GetParameters(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_ResetParameters(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_SetParameters(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_Escape(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_IccClock(USBD_HandleTypeDef *pdev);
uint8_t PC_to_RDR_Abort(USBD_HandleTypeDef *pdev);
uint8_t PC_TO_RDR_T0Apdu(USBD_HandleTypeDef *pdev);
uint8_t PC_TO_RDR_Mechanical(USBD_HandleTypeDef *pdev);
uint8_t PC_TO_RDR_SetDataRateAndClockFrequency(USBD_HandleTypeDef *pdev);
uint8_t PC_TO_RDR_Secure(USBD_HandleTypeDef *pdev);
void RDR_to_PC_DataBlock(uint8_t errorCode, USBD_HandleTypeDef *pdev);
void RDR_to_PC_NotifySlotChange(USBD_HandleTypeDef *pdev);
void RDR_to_PC_SlotStatus(uint8_t errorCode, USBD_HandleTypeDef *pdev);
void RDR_to_PC_Parameters(uint8_t errorCode, USBD_HandleTypeDef *pdev);
void RDR_to_PC_Escape(uint8_t errorCode, USBD_HandleTypeDef *pdev);
void RDR_to_PC_DataRateAndClockFrequency(uint8_t errorCode, USBD_HandleTypeDef *pdev);
void CCID_UpdSlotStatus(USBD_HandleTypeDef *pdev, uint8_t slotStatus);
void CCID_UpdSlotChange(USBD_HandleTypeDef *pdev, uint8_t changeStatus);
uint8_t CCID_IsSlotStatusChange(USBD_HandleTypeDef *pdev);
uint8_t CCID_CmdAbort(USBD_HandleTypeDef *pdev, uint8_t slot, uint8_t seq);
uint8_t USBD_CCID_Transfer_Data_Request(USBD_HandleTypeDef *pdev,
uint8_t *dataPointer, uint16_t dataLen);
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CCID_CMD_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Inc\usbd_ccid_if_template.h | /**
******************************************************************************
* @file usbd_ccid_if_template.h
* @author MCD Application Team
* @brief header file for the usbd_ccid_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CCID_IF_TEMPLATE_H
#define __USBD_CCID_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid.h"
#include "usbd_ccid_cmd.h"
#ifndef __USBD_CCID_SMARTCARD_H
#include "usbd_ccid_smartcard_template.h"
#endif /* __USBD_CCID_SMARTCARD_H */
/* Exported defines ----------------------------------------------------------*/
/*****************************************************************************/
/*********************** CCID Bulk Transfer State machine ********************/
/*****************************************************************************/
#define CCID_STATE_IDLE 0U
#define CCID_STATE_DATA_OUT 1U
#define CCID_STATE_RECEIVE_DATA 2U
#define CCID_STATE_SEND_RESP 3U
#define CCID_STATE_DATAIN 4U
#define CCID_STATE_UNCORRECT_LENGTH 5U
#define DIR_IN 0U
#define DIR_OUT 1U
#define BOTH_DIR 2U
/************ Value of the Interrupt transfer status to set ******************/
#define INTRSTATUS_COMPLETE 1U
#define INTRSTATUS_RESET 0U
/************** slot change status *******************************************/
#define SLOTSTATUS_CHANGED 1U
#define SLOTSTATUS_RESET 0U
/* Exported types ------------------------------------------------------------*/
extern USBD_HandleTypeDef USBD_Device;
/* CCID Interface callback */
extern USBD_CCID_ItfTypeDef USBD_CCID_If_fops;
/* Exported macros -----------------------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CCID_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Inc\usbd_ccid_sc_if_template.h | /**
******************************************************************************
* @file usbd_ccid_sc_if_template.h
* @author MCD Application Team
* @brief header file for the usbd_ccid_sc_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CCID_SC_IF_TEMPLATE_H
#define __USBD_CCID_SC_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid.h"
#include "usbd_ccid_cmd.h"
#ifndef __USBD_CCID_SMARTCARD_H
#include "usbd_ccid_smartcard_template.h"
#endif /* __USBD_CCID_SMARTCARD_H */
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
typedef struct
{
uint8_t voltage; /* Voltage for the Card Already Selected */
uint8_t USART_GuardTime;
uint8_t SC_A2R_FiDi;
uint8_t SC_hostFiDi;
uint8_t USART_DefaultGuardTime;
uint32_t USART_BaudRate;
} SC_Param_t;
#pragma pack(1)
typedef struct
{
uint8_t bmFindexDindex;
uint8_t bmTCCKST0;
uint8_t bGuardTimeT0;
uint8_t bWaitingIntegerT0;
uint8_t bClockStop;
uint8_t bIfsc;
uint8_t bNad;
} Protocol_01_DataTypeDef;
#pragma pack()
extern Protocol_01_DataTypeDef ProtocolData;
extern SC_Param_t SC_Param;
/* Exported macro ------------------------------------------------------------*/
#define MAX_EXTRA_GUARD_TIME (0xFF - DEFAULT_EXTRA_GUARDTIME)
/* Following macros are used for SC_XferBlock command */
#define XFER_BLK_SEND_DATA 1U /* Command is for issuing the data */
#define XFER_BLK_RECEIVE_DATA 2U /* Command is for receiving the data */
#define XFER_BLK_NO_DATA 3U /* Command type is No data exchange */
/* Exported functions ------------------------------------------------------- */
/* APPLICATION LAYER ---------------------------------------------------------*/
void SC_Itf_InitParams(void);
void SC_Itf_IccPowerOn(uint8_t voltage);
void SC_Itf_IccPowerOff(void);
uint8_t SC_GetState(void);
uint8_t SC_Itf_XferBlock(uint8_t *ptrBlock, uint32_t blockLen,
uint16_t expectedLen,
USBD_CCID_BulkIn_DataTypeDef *CCID_BulkIn_Data);
uint8_t SC_Itf_SetParams(Protocol_01_DataTypeDef *pPtr, uint8_t T_01);
uint8_t SC_Itf_Escape(uint8_t *escapePtr, uint32_t escapeLen,
uint8_t *responseBuff, uint32_t *responseLen);
uint8_t SC_Itf_SetClock(uint8_t bClockCommand);
uint8_t SC_Itf_T0Apdu(uint8_t bmChanges, uint8_t bClassGetResponse,
uint8_t bClassEnvelope);
uint8_t SC_Itf_Mechanical(uint8_t bFunction);
uint8_t SC_Itf_SetDataRateAndClockFrequency(uint32_t dwClockFrequency,
uint32_t dwDataRate);
uint8_t SC_Itf_Secure(uint32_t dwLength, uint8_t bBWI, uint16_t wLevelParameter,
uint8_t *pbuf, uint32_t *returnLen);
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CCID_SC_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Inc\usbd_ccid_smartcard_template.h | /**
******************************************************************************
* @file usbd_ccid_smartcard_template.h
* @author MCD Application Team
* @brief header file for the usbd_ccid_smartcard_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CCID_SMARTCARD_TEMPLATE_H
#define __USBD_CCID_SMARTCARD_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#ifndef __USBD_CCID_IF_H
#include "usbd_ccid_if_template.h"
#endif /* __USBD_CCID_IF_H */
/* Exported constants --------------------------------------------------------*/
#define T0_PROTOCOL 0x00U /* T0 protocol */
#define T1_PROTOCOL 0x01U /* T1 protocol */
#define DIRECT 0x3BU /* Direct bit convention */
#define INDIRECT 0x3FU /* Indirect bit convention */
#define SETUP_LENGTH 20U
#define HIST_LENGTH 20U
#define SC_TRANSMIT_TIMEOUT 200U /* Direction to transmit */
#define MAX_PROTOCOLLEVEL 7U /* Maximum levels of protocol */
#define MAX_INTERFACEBYTE 4U /* Maximum number of interface bytes per protocol */
#define LC_MAX 24U
#define SC_RECEIVE_TIMEOUT 0x8000U /* Direction to reader */
/* T=1 protocol constants */
#define T1_I_BLOCK 0x00U /* PCB (I-block: b8 = 0) */
#define T1_R_BLOCK 0x80U /* PCB (R-block: b8 b7 = 10) */
#define T1_S_BLOCK 0xC0U /* PCB (S-block: b8 b7 = 11) */
/* I block */
#define T1_I_SEQ_SHIFT 6U /* N(S) position (bit 7) */
/* R block */
#define T1_IS_ERROR(pcb) ((pcb) & 0x0FU)
#define T1_EDC_ERROR 0x01U /* [b6..b1] = 0-N(R)-0001 */
#define T1_OTHER_ERROR 0x02U /* [b6..b1] = 0-N(R)-0010 */
#define T1_R_SEQ_SHIFT 4U /* N(R) position (b5) */
/* S block */
#define T1_S_RESPONSE 0x20U /* If response: set bit b6, if request reset b6 in PCB S-Block */
#define T1_S_RESYNC 0x00U /* RESYNCH: b6->b1: 000000 of PCB S-Block */
#define T1_S_IFS 0x01U /* IFS: b6->b1: 000001 of PCB S-Block */
#define T1_S_ABORT 0x02U /* ABORT: b6->b1: 000010 of PCB S-Block */
#define T1_S_WTX 0x03U /* WTX: b6->b1: 000011 of PCB S-Block */
#define NAD 0U /* NAD byte position in the block */
#define PCB 1U /* PCB byte position in the block */
#define LEN 2U /* LEN byte position in the block */
#define DATA 3U /* The position of the first byte of INF field in the block */
/* Modifiable parameters */
#define SAD 0x0U /* Source address: reader (allowed values 0 -> 7) */
#define DAD 0x0U /* Destination address: card (allowed values 0 -> 7) */
#define IFSD_VALUE 254U /* Max length of INF field Supported by the reader */
#define SC_FILE_SIZE 0x100U /* File size */
#define SC_FILE_ID 0x0001U /* File identifier */
#define SC_CLASS 0x00U
/* Constant parameters */
#define INS_SELECT_FILE 0xA4U /* Select file instruction */
#define INS_READ_FILE 0xB0U /* Read file instruction */
#define INS_WRITE_FILE 0xD6U /* Write file instruction */
#define TRAILER_LENGTH 2U /* Trailer length (SW1 and SW2: 2 bytes) */
#define SC_T1_RECEIVE_SUCCESS 0U
#define SC_T1_BWT_TIMEOUT 1U
#define SC_T1_CWT_TIMEOUT 2U
#define DEFAULT_FIDI_VALUE 0x11U
#define PPS_REQUEST 0xFFU
/* SC Tree Structure -----------------------------------------------------------
MasterFile
________|___________
| | |
System UserData Note
------------------------------------------------------------------------------*/
/* SC ADPU Command: Operation Code -------------------------------------------*/
#define SC_CLA_NAME 0x00U
/*------------------------ Data Area Management Commands ---------------------*/
#define SC_SELECT_FILE 0xA4U
#define SC_GET_RESPONCE 0xC0U
#define SC_STATUS 0xF2U
#define SC_UPDATE_BINARY 0xD6U
#define SC_READ_BINARY 0xB0U
#define SC_WRITE_BINARY 0xD0U
#define SC_UPDATE_RECORD 0xDCU
#define SC_READ_RECORD 0xB2U
/*-------------------------- Administrative Commands -------------------------*/
#define SC_CREATE_FILE 0xE0U
/*-------------------------- Safety Management Commands ----------------------*/
#define SC_VERIFY 0x20U
#define SC_CHANGE 0x24U
#define SC_DISABLE 0x26U
#define SC_ENABLE 0x28U
#define SC_UNBLOCK 0x2CU
#define SC_EXTERNAL_AUTH 0x82U
#define SC_GET_CHALLENGE 0x84U
/*-------------------------- Smartcard Interface Byte-------------------------*/
#define SC_INTERFACEBYTE_TA 0U /* Interface byte TA(i) */
#define SC_INTERFACEBYTE_TB 1U /* Interface byte TB(i) */
#define SC_INTERFACEBYTE_TC 2U /* Interface byte TC(i) */
#define SC_INTERFACEBYTE_TD 3U /* Interface byte TD(i) */
/*-------------------------- Answer to reset Commands ------------------------*/
#define SC_GET_A2R 0x00U
/* SC STATUS: Status Code ----------------------------------------------------*/
#define SC_EF_SELECTED 0x9FU
#define SC_DF_SELECTED 0x9FU
#define SC_OP_TERMINATED 0x9000U
/* Smartcard Voltage */
#define SC_VOLTAGE_5V 0x00U
#define SC_VOLTAGE_3V 0x01U
#define SC_VOLTAGE_NOINIT 0xFFU
/*----------------- ATR Protocole supported ----------------------------------*/
#define ATR_T01 0x00U
/* Exported types ------------------------------------------------------------*/
typedef enum
{
SC_POWER_ON = 0x00,
SC_RESET_LOW = 0x01,
SC_RESET_HIGH = 0x02,
SC_ACTIVE = 0x03,
SC_ACTIVE_ON_T0 = 0x04,
SC_ACTIVE_ON_T1 = 0x05,
SC_POWER_OFF = 0x06,
SC_NO_INIT = 0x07
} SC_State;
/* Interface Byte structure - TA(i), TB(i), TC(i) and TD(i) ------------------*/
typedef struct
{
uint8_t Status; /* The Presence of the Interface byte */
uint8_t Value; /* The Value of the Interface byte */
} SC_InterfaceByteTypeDef;
/* Protocol Level structure - ------------------------------------------------*/
typedef struct
{
SC_InterfaceByteTypeDef InterfaceByte[MAX_INTERFACEBYTE]; /* The Values of the Interface byte
TA(i), TB(i), TC(i)and TD(i) */
} SC_ProtocolLevelTypeDef;
/* ATR structure - Answer To Reset -------------------------------------------*/
typedef struct
{
uint8_t TS; /* Bit Convention Direct/Indirect */
uint8_t T0; /* Each bit in the high nibble = Presence of the further interface byte;
Low nibble = Number of historical byte */
SC_ProtocolLevelTypeDef T[MAX_PROTOCOLLEVEL]; /* Setup array */
uint8_t Historical[HIST_LENGTH]; /* Historical array */
uint8_t Tlength; /* Setup array dimension */
uint8_t Hlength; /* Historical array dimension */
uint8_t TCK;
} SC_ATRTypeDef;
/* ADPU-Header command structure ---------------------------------------------*/
typedef struct
{
uint8_t CLA; /* Command class */
uint8_t INS; /* Operation code */
uint8_t P1; /* Selection Mode */
uint8_t P2; /* Selection Option */
} SC_HeaderTypeDef;
/* ADPU-Body command structure -----------------------------------------------*/
typedef struct
{
uint8_t LC; /* Data field length */
uint8_t Data[LC_MAX]; /* Command parameters */
uint8_t LE; /* Expected length of data to be returned */
} SC_BodyTypeDef;
/* ADPU Command structure ----------------------------------------------------*/
typedef struct
{
SC_HeaderTypeDef Header;
SC_BodyTypeDef Body;
} SC_ADPU_CommandsTypeDef;
/* SC response structure -----------------------------------------------------*/
typedef struct
{
uint8_t Data[LC_MAX]; /* Data returned from the card */
uint8_t SW1; /* Command Processing status */
uint8_t SW2; /* Command Processing qualification */
} SC_ADPU_ResponseTypeDef;
/* SC Command Status -----------------------------------------------------*/
typedef enum
{
SC_CS_FAILED = 0x00,
SC_CS_PIN_ENABLED = 0x01,
SC_CS_PIN_VERIFIED = 0x02,
SC_CS_READ = 0x03,
SC_CS_PIN_CHANGED = 0x04
} SC_Command_State;
/* SC Response Status -----------------------------------------------------*/
typedef enum
{
REP_OK = 0x00,
REP_NOT_OK = 0x01,
REP_NOT_SUPP = 0x02,
REP_ENABLED = 0x03,
REP_CHANGE = 0x04
} REP_Command_t;
/* Conforming of Command with ICC APP -----------------------------------------------------*/
typedef enum
{
Command_OK = 0x00,
Command_NOT_OK = 0x01,
} Command_State_t;
typedef enum
{
SC_DISABLED = 0U,
SC_ENABLED = !SC_DISABLED
} SCPowerState;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
/* APPLICATION LAYER ---------------------------------------------------------*/
void SC_Handler(SC_State *SCState, SC_ADPU_CommandsTypeDef *SC_ADPU, SC_ADPU_ResponseTypeDef *SC_Response);
void SC_PowerCmd(SCPowerState NewState);
void SC_ParityErrorHandler(void);
void SC_PTSConfig(void);
uint8_t SC_Detect(void);
uint32_t SC_GetDTableValue(uint32_t idx);
void SC_VoltageConfig(uint32_t SC_Voltage);
void SC_SetState(SC_State scState);
void SC_IOConfig(void);
extern uint8_t SC_ATR_Table[40];
extern SC_ATRTypeDef SC_A2R;
extern SC_ADPU_ResponseTypeDef SC_Response;
extern uint8_t ProtocolNUM_OUT;
extern SC_ADPU_CommandsTypeDef SC_ADPU;
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CCID_SMARTCARD_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Src\usbd_ccid.c | /**
******************************************************************************
* @file usbd_ccid.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage
* all the functionalities of the USB CCID Class:
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
* @verbatim
*
* ===================================================================
* CCID Class Driver Description
* ===================================================================
* This module manages the Specification for Integrated Circuit(s)
* Cards Interface Revision 1.1
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as CCID device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN)
* and enumeration for each implemented memory interface
* - Bulk OUT/IN data Transfers
* - Requests management
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid.h"
#include "usbd_ccid_cmd.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CCID
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CCID_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CCID_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CCID_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CCID_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CCID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CCID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CCID_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_CCID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CCID_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CCID_DispatchCommand(USBD_HandleTypeDef *pdev);
static uint8_t USBD_CCID_ReceiveCmdHeader(USBD_HandleTypeDef *pdev,
uint8_t *pDst, uint16_t u8length);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_CCID_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CCID_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CCID_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_CCID_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_CCID_Private_Variables
* @{
*/
static uint8_t CCIDInEpAdd = CCID_IN_EP;
static uint8_t CCIDOutEpAdd = CCID_OUT_EP;
static uint8_t CCIDCmdEpAdd = CCID_CMD_EP;
/* CCID interface class callbacks structure */
USBD_ClassTypeDef USBD_CCID =
{
USBD_CCID_Init,
USBD_CCID_DeInit,
USBD_CCID_Setup,
NULL, /*EP0_TxSent*/
NULL, /*EP0_RxReady*/
USBD_CCID_DataIn,
USBD_CCID_DataOut,
NULL, /*SOF */
NULL, /*ISOIn*/
NULL, /*ISOOut*/
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_CCID_GetHSCfgDesc,
USBD_CCID_GetFSCfgDesc,
USBD_CCID_GetOtherSpeedCfgDesc,
USBD_CCID_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB CCID device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CCID_CfgDesc[USB_CCID_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_CCID_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: */
0x00, /* iConfiguration: */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/******************** CCID **** interface ********************/
CCID_INTERFACE_DESC_SIZE, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x03, /* bNumEndpoints: 3 endpoints used */
USB_DEVICE_CLASS_CCID, /* bInterfaceClass: user's interface for CCID */
0x00, /* bInterfaceSubClass : No subclass,
can be changed but no description in USB 2.0 Spec */
0x00, /* nInterfaceProtocol : None */
0x00, /* iInterface */
/******************* CCID class descriptor ********************/
CCID_CLASS_DESC_SIZE, /* bLength: CCID Descriptor size */
CCID_DESC_TYPE, /* bDescriptorType: Functional Descriptor type. */
0x10, /* bcdCCID(LSB): CCID Class Spec release number (1.1) */
0x01, /* bcdCCID(MSB) */
0x00, /* bMaxSlotIndex :highest available slot on this device */
CCID_VOLTAGE_SUPP, /* bVoltageSupport: bVoltageSupport: 5v, 3v and 1.8v */
LOBYTE(USBD_CCID_PROTOCOL), /* dwProtocols: supports T=0 and T=1 */
HIBYTE(USBD_CCID_PROTOCOL),
0x00,
0x00,
LOBYTE(USBD_CCID_DEFAULT_CLOCK_FREQ), /* dwDefaultClock: 3.6Mhz */
HIBYTE(USBD_CCID_DEFAULT_CLOCK_FREQ),
0x00,
0x00,
LOBYTE(USBD_CCID_MAX_CLOCK_FREQ), /* dwMaximumClock */
HIBYTE(USBD_CCID_MAX_CLOCK_FREQ),
0x00,
0x00,
0x00, /* bNumClockSupported */
LOBYTE(USBD_CCID_DEFAULT_DATA_RATE), /* dwDataRate: 9677 bps */
HIBYTE(USBD_CCID_DEFAULT_DATA_RATE),
0x00,
0x00,
LOBYTE(USBD_CCID_MAX_DATA_RATE), /* dwMaxDataRate */
HIBYTE(USBD_CCID_MAX_DATA_RATE),
0x00,
0x00,
0x35, /* bNumDataRatesSupported */
LOBYTE(USBD_CCID_MAX_INF_FIELD_SIZE), /* dwMaxIFSD: maximum IFSD supported for T=1 */
HIBYTE(USBD_CCID_MAX_INF_FIELD_SIZE),
0x00,
0x00,
0x00, 0x00, 0x00, 0x00, /* dwSynchProtocols */
0x00, 0x00, 0x00, 0x00, /* dwMechanical: no special characteristics */
0xBA, 0x04, EXCHANGE_LEVEL_FEATURE, 0x00, /* dwFeatures */
LOBYTE(CCID_MAX_BLOCK_SIZE_HEADER), /* dwMaxCCIDMessageLength: Maximum block size + header*/
HIBYTE(CCID_MAX_BLOCK_SIZE_HEADER),
0x00,
0x00,
0x00, /* bClassGetResponse*/
0x00, /* bClassEnvelope */
0x00, 0x00, /* wLcdLayout : 0000h no LCD. */
0x03, /* bPINSupport : PIN verification and PIN modification */
0x01, /* bMaxCCIDBusySlots */
/******************** CCID Endpoints ********************/
CCID_ENDPOINT_DESC_SIZE, /* Endpoint descriptor length = 7 */
USB_DESC_TYPE_ENDPOINT, /* Endpoint descriptor type */
CCID_IN_EP, /* Endpoint address (IN, address 1) */
USBD_EP_TYPE_BULK, /* Bulk endpoint type */
LOBYTE(CCID_DATA_FS_MAX_PACKET_SIZE),
HIBYTE(CCID_DATA_FS_MAX_PACKET_SIZE),
0x00, /* Polling interval in milliseconds */
CCID_ENDPOINT_DESC_SIZE, /* Endpoint descriptor length = 7 */
USB_DESC_TYPE_ENDPOINT, /* Endpoint descriptor type */
CCID_OUT_EP, /* Endpoint address (OUT, address 1) */
USBD_EP_TYPE_BULK, /* Bulk endpoint type */
LOBYTE(CCID_DATA_FS_MAX_PACKET_SIZE),
HIBYTE(CCID_DATA_FS_MAX_PACKET_SIZE),
0x00, /* Polling interval in milliseconds */
CCID_ENDPOINT_DESC_SIZE, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType:*/
CCID_CMD_EP, /* bEndpointAddress: Endpoint Address (IN) */
USBD_EP_TYPE_INTR, /* bmAttributes: Interrupt endpoint */
LOBYTE(CCID_CMD_PACKET_SIZE),
HIBYTE(CCID_CMD_PACKET_SIZE),
CCID_CMD_FS_BINTERVAL /* Polling interval in milliseconds */
};
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CCID_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_CCID_Private_Functions
* @{
*/
/**
* @brief USBD_CCID_Init
* Initialize the CCID interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CCID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
USBD_CCID_HandleTypeDef *hccid;
UNUSED(cfgidx);
/* Allocate CCID structure */
hccid = (USBD_CCID_HandleTypeDef *)USBD_malloc(sizeof(USBD_CCID_HandleTypeDef));
if (hccid == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)hccid;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CCIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CCIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CCIDCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Init the CCID parameters into a state where it can receive a new command message */
hccid->USBD_CCID_Param.bAbortRequestFlag = 0U;
hccid->USBD_CCID_Param.bSeq = 0U;
hccid->USBD_CCID_Param.bSlot = 0U;
hccid->MaxPcktLen = (pdev->dev_speed == USBD_SPEED_HIGH) ? \
CCID_DATA_HS_MAX_PACKET_SIZE : CCID_DATA_FS_MAX_PACKET_SIZE;
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CCIDInEpAdd, USBD_EP_TYPE_BULK, (uint16_t)hccid->MaxPcktLen);
pdev->ep_in[CCIDInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CCIDOutEpAdd, USBD_EP_TYPE_BULK, (uint16_t)hccid->MaxPcktLen);
pdev->ep_out[CCIDOutEpAdd & 0xFU].is_used = 1U;
/* Open INTR EP IN */
(void)USBD_LL_OpenEP(pdev, CCIDCmdEpAdd,
USBD_EP_TYPE_INTR, CCID_CMD_PACKET_SIZE);
pdev->ep_in[CCIDCmdEpAdd & 0xFU].is_used = 1U;
/* Init physical Interface components */
((USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init(pdev);
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CCIDOutEpAdd,
hccid->data, hccid->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_DeInit
* DeInitialize the CCID layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CCID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CCIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CCIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CCIDCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, CCIDInEpAdd);
pdev->ep_in[CCIDInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, CCIDOutEpAdd);
pdev->ep_out[CCIDOutEpAdd & 0xFU].is_used = 0U;
/* Close EP Command */
(void)USBD_LL_CloseEP(pdev, CCIDCmdEpAdd);
pdev->ep_in[CCIDCmdEpAdd & 0xFU].is_used = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit(pdev);
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_Setup
* Handle the CCID specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CCID_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_CCID_ItfTypeDef *hCCIDitf = (USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint8_t ifalt = 0U;
uint16_t status_info = 0U;
uint16_t len;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
/* Class request */
case USB_REQ_TYPE_CLASS :
if (req->wLength != 0U)
{
len = MIN(CCID_EP0_BUFF_SIZ, req->wLength);
if ((req->bmRequest & 0x80U) != 0U)
{
hCCIDitf->Control(req->bRequest, hccid->data, &len);
(void)USBD_CtlSendData(pdev, hccid->data, len);
}
else
{
(void)USBD_CtlPrepareRx(pdev, hccid->data, len);
}
}
else
{
len = 0U;
hCCIDitf->Control(req->bRequest, (uint8_t *)&req->wValue, &len);
}
break;
/* Interface & Endpoint request */
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, &ifalt, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CCID_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CCID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CCIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CCIDCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (epnum == (CCIDInEpAdd & 0x7FU))
{
/* Filter the epnum by masking with 0x7f (mask of IN Direction) */
/*************** Handle Bulk Transfer IN data completion *****************/
switch (hccid->blkt_state)
{
case CCID_STATE_SEND_RESP:
/* won't wait ack to avoid missing a command */
hccid->blkt_state = CCID_STATE_IDLE;
/* Prepare EP to Receive Cmd */
(void)USBD_LL_PrepareReceive(pdev, CCID_OUT_EP,
hccid->data, hccid->MaxPcktLen);
break;
default:
break;
}
}
else if (epnum == (CCIDCmdEpAdd & 0x7FU))
{
/* Filter the epnum by masking with 0x7f (mask of IN Direction) */
/*************** Handle Interrupt Transfer IN data completion *****************/
(void)USBD_CCID_IntMessage(pdev);
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CCID_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t CurrPcktLen;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CCIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hccid == NULL)
{
return (uint8_t)USBD_EMEM;
}
if (epnum == CCIDOutEpAdd)
{
CurrPcktLen = (uint16_t)USBD_GetRxCount(pdev, epnum);
switch (hccid->blkt_state)
{
case CCID_STATE_IDLE:
if (CurrPcktLen >= (uint16_t)CCID_CMD_HEADER_SIZE)
{
hccid->UsbMessageLength = CurrPcktLen; /* Store for future use */
/* Fill CCID_BulkOut Data Buffer from USB Buffer */
(void)USBD_CCID_ReceiveCmdHeader(pdev, (uint8_t *)&hccid->UsbBlkOutData.bMessageType,
(uint16_t)CurrPcktLen);
/*
Refer : 6 CCID Messages
The response messages always contain the exact same slot number,
and sequence number fields from the header that was contained in
the Bulk-OUT command message.
*/
hccid->UsbBlkInData.bSlot = hccid->UsbBlkOutData.bSlot;
hccid->UsbBlkInData.bSeq = hccid->UsbBlkOutData.bSeq;
if (CurrPcktLen < hccid->MaxPcktLen)
{
/* Short message, less than the EP Out Size, execute the command,
if parameter like dwLength is too big, the appropriate command will
give an error */
(void)USBD_CCID_DispatchCommand(pdev);
}
else
{
/* Check if length of data to be sent by host is > buffer size */
if (hccid->UsbBlkOutData.dwLength > (uint32_t)ABDATA_SIZE)
{
/* Too long data received.... Error ! */
hccid->blkt_state = CCID_STATE_UNCORRECT_LENGTH;
}
else
{
/* Expect more data on OUT EP */
hccid->blkt_state = CCID_STATE_RECEIVE_DATA;
/* Prepare EP to Receive next Cmd */
(void)USBD_LL_PrepareReceive(pdev, CCID_OUT_EP,
hccid->data, hccid->MaxPcktLen);
} /* if (CurrPcktLen == CCID_DATA_MAX_PACKET_SIZE) ends */
} /* if (CurrPcktLen >= CCID_DATA_MAX_PACKET_SIZE) ends */
} /* if (CurrPcktLen >= CCID_CMD_HEADER_SIZE) ends */
else
{
if (CurrPcktLen == 0x00U) /* Zero Length Packet Received */
{
hccid->blkt_state = CCID_STATE_IDLE;
}
}
break;
case CCID_STATE_RECEIVE_DATA:
hccid->UsbMessageLength += CurrPcktLen;
if (CurrPcktLen < hccid->MaxPcktLen)
{
/* Short message, less than the EP Out Size, execute the command,
if parameter like dwLength is too big, the appropriate command will
give an error */
/* Full command is received, process the Command */
(void)USBD_CCID_ReceiveCmdHeader(pdev, (uint8_t *)&hccid->UsbBlkOutData.bMessageType,
(uint16_t)CurrPcktLen);
(void)USBD_CCID_DispatchCommand(pdev);
}
else if (CurrPcktLen == hccid->MaxPcktLen)
{
if (hccid->UsbMessageLength < (hccid->UsbBlkOutData.dwLength + (uint32_t)CCID_CMD_HEADER_SIZE))
{
(void)USBD_CCID_ReceiveCmdHeader(pdev, (uint8_t *)&hccid->UsbBlkOutData.bMessageType,
(uint16_t)CurrPcktLen); /* Copy data */
/* Prepare EP to Receive next Cmd */
(void)USBD_LL_PrepareReceive(pdev, CCID_OUT_EP,
hccid->data, hccid->MaxPcktLen);
}
else if (hccid->UsbMessageLength == (hccid->UsbBlkOutData.dwLength + (uint32_t)CCID_CMD_HEADER_SIZE))
{
/* Full command is received, process the Command */
(void)USBD_CCID_ReceiveCmdHeader(pdev, (uint8_t *)&hccid->UsbBlkOutData.bMessageType,
(uint16_t)CurrPcktLen);
(void)USBD_CCID_DispatchCommand(pdev);
}
else
{
/* Too long data received.... Error ! */
hccid->blkt_state = CCID_STATE_UNCORRECT_LENGTH;
}
}
else
{
/* Too long data received.... Error ! */
hccid->blkt_state = CCID_STATE_UNCORRECT_LENGTH;
}
break;
case CCID_STATE_UNCORRECT_LENGTH:
hccid->blkt_state = CCID_STATE_IDLE;
break;
default:
break;
}
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_DispatchCommand
* Parse the commands and Process command
* @param pdev: device instance
* @retval status value
*/
static uint8_t USBD_CCID_DispatchCommand(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t errorCode;
switch (hccid->UsbBlkOutData.bMessageType)
{
case PC_TO_RDR_ICCPOWERON:
errorCode = PC_to_RDR_IccPowerOn(pdev);
RDR_to_PC_DataBlock(errorCode, pdev);
break;
case PC_TO_RDR_ICCPOWEROFF:
errorCode = PC_to_RDR_IccPowerOff(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_GETSLOTSTATUS:
errorCode = PC_to_RDR_GetSlotStatus(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_XFRBLOCK:
errorCode = PC_to_RDR_XfrBlock(pdev);
RDR_to_PC_DataBlock(errorCode, pdev);
break;
case PC_TO_RDR_GETPARAMETERS:
errorCode = PC_to_RDR_GetParameters(pdev);
RDR_to_PC_Parameters(errorCode, pdev);
break;
case PC_TO_RDR_RESETPARAMETERS:
errorCode = PC_to_RDR_ResetParameters(pdev);
RDR_to_PC_Parameters(errorCode, pdev);
break;
case PC_TO_RDR_SETPARAMETERS:
errorCode = PC_to_RDR_SetParameters(pdev);
RDR_to_PC_Parameters(errorCode, pdev);
break;
case PC_TO_RDR_ESCAPE:
errorCode = PC_to_RDR_Escape(pdev);
RDR_to_PC_Escape(errorCode, pdev);
break;
case PC_TO_RDR_ICCCLOCK:
errorCode = PC_to_RDR_IccClock(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_ABORT:
errorCode = PC_to_RDR_Abort(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_T0APDU:
errorCode = PC_TO_RDR_T0Apdu(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_MECHANICAL:
errorCode = PC_TO_RDR_Mechanical(pdev);
RDR_to_PC_SlotStatus(errorCode, pdev);
break;
case PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY:
errorCode = PC_TO_RDR_SetDataRateAndClockFrequency(pdev);
RDR_to_PC_DataRateAndClockFrequency(errorCode, pdev);
break;
case PC_TO_RDR_SECURE:
errorCode = PC_TO_RDR_Secure(pdev);
RDR_to_PC_DataBlock(errorCode, pdev);
break;
default:
RDR_to_PC_SlotStatus(SLOTERROR_CMD_NOT_SUPPORTED, pdev);
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_Transfer_Data_Request
* Prepare the request response to be sent to the host
* @param pdev: device instance
* @param dataPointer: Pointer to the data buffer to send
* @param dataLen : number of bytes to send
* @retval status value
*/
uint8_t USBD_CCID_Transfer_Data_Request(USBD_HandleTypeDef *pdev,
uint8_t *dataPointer, uint16_t dataLen)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_CCID_ItfTypeDef *hCCIDitf = (USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId];
UNUSED(dataPointer);
hccid->blkt_state = CCID_STATE_SEND_RESP;
hccid->UsbMessageLength = (uint32_t)dataLen; /* Store for future use */
/* use the header declared size packet must be well formed */
hCCIDitf->Response_SendData(pdev, (uint8_t *)&hccid->UsbBlkInData,
(uint16_t)MIN(CCID_DATA_FS_MAX_PACKET_SIZE, hccid->UsbMessageLength));
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_ReceiveCmdHeader
* Receive the Data from USB BulkOut Buffer to Pointer
* @param pdev: device instance
* @param pDst: destination address to copy the buffer
* @param u8length: length of data to copy
* @retval status
*/
static uint8_t USBD_CCID_ReceiveCmdHeader(USBD_HandleTypeDef *pdev,
uint8_t *pDst, uint16_t u8length)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t *pdst = pDst;
uint32_t Counter;
for (Counter = 0U; Counter < u8length; Counter++)
{
*pdst = hccid->data[Counter];
pdst++;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CCID_IntMessage
* Send the Interrupt-IN data to the host
* @param pdev: device instance
* @retval None
*/
uint8_t USBD_CCID_IntMessage(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CCIDCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Check if there is change in Smartcard Slot status */
if (CCID_IsSlotStatusChange(pdev) != 0U)
{
/* Check Slot Status is changed. Card is Removed/Fitted */
RDR_to_PC_NotifySlotChange(pdev);
/* Set the Slot status */
((USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId])->SetSlotStatus(pdev);
(void)USBD_LL_Transmit(pdev, CCIDCmdEpAdd, hccid->UsbIntData, 2U);
}
else
{
/* Set the Slot status */
((USBD_CCID_ItfTypeDef *)pdev->pUserData[pdev->classId])->SetSlotStatus(pdev);
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_CCID_GetHSCfgDesc
* Return configuration descriptor
* @param length pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CCID_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CCID_DATA_HS_MAX_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CCID_DATA_HS_MAX_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CCID_CMD_HS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CCID_CfgDesc);
return USBD_CCID_CfgDesc;
}
/**
* @brief USBD_CCID_GetFSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CCID_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CCID_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CCID_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CCID_CMD_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CCID_CfgDesc);
return USBD_CCID_CfgDesc;
}
/**
* @brief USBD_CCID_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CCID_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CCID_CfgDesc, CCID_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CCID_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CCID_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CCID_CMD_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CCID_CfgDesc);
return USBD_CCID_CfgDesc;
}
/**
* @brief USBD_CCID_GetDeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CCID_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)(sizeof(USBD_CCID_DeviceQualifierDesc));
return USBD_CCID_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CCID_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_CCID_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CCID_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Src\usbd_ccid_cmd.c | /**
******************************************************************************
* @file usbd_ccid_cmd.c
* @author MCD Application Team
* @brief CCID command (Bulk-OUT Messages / Bulk-IN Messages) handling
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid.h"
#include "usbd_ccid_cmd.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static uint8_t CCID_CheckCommandParams(USBD_HandleTypeDef *pdev, uint32_t param_type);
static void CCID_UpdateCommandStatus(USBD_HandleTypeDef *pdev, uint8_t cmd_status, uint8_t icc_status);
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* BULK OUT ROUTINES */
/******************************************************************************/
/**
* @brief PC_to_RDR_IccPowerOn
* PC_TO_RDR_ICCPOWERON message execution, apply voltage and get ATR
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_IccPowerOn(USBD_HandleTypeDef *pdev)
{
/* Apply the ICC VCC
Fills the Response buffer with ICC ATR
This Command is returned with RDR_to_PC_DataBlock();
*/
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t voltage;
uint8_t sc_voltage = 0U;
uint8_t index;
uint8_t error;
hccid->UsbBlkInData.dwLength = 0U; /* Reset Number of Bytes in abData */
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_DWLENGTH |
CHK_PARAM_ABRFU2 | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABORT);
if (error != 0U)
{
return error;
}
/* Voltage that is applied to the ICC
00h Automatic Voltage Selection
01h 5.0 volts
02h 3.0 volts
03h 1.8 volts
*/
/* UsbBlkOutData.bSpecific_0 Contains bPowerSelect */
voltage = hccid->UsbBlkOutData.bSpecific_0;
if (voltage >= VOLTAGE_SELECTION_1V8)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_POWERSELECT; /* The Voltage specified is out of Spec */
}
/* Correct Voltage Requested by the Host */
if ((voltage == VOLTAGE_SELECTION_AUTOMATIC) || (voltage == VOLTAGE_SELECTION_3V))
{
sc_voltage = SC_VOLTAGE_3V;
}
else
{
if (voltage == VOLTAGE_SELECTION_5V)
{
sc_voltage = SC_VOLTAGE_5V;
}
}
SC_Itf_IccPowerOn(sc_voltage);
/* Check if the Card has come to Active State*/
error = CCID_CheckCommandParams(pdev, (uint32_t)CHK_ACTIVE_STATE);
if (error != 0U)
{
/* Check if Voltage is not Automatic */
if (voltage != 0U)
{
/* If Specific Voltage requested by Host i.e 3V or 5V*/
return error;
}
else
{
/* Automatic Voltage selection requested by Host */
if (sc_voltage != SC_VOLTAGE_5V)
{
/* If voltage selected was Automatic and 5V is not yet tried */
sc_voltage = SC_VOLTAGE_5V;
SC_Itf_IccPowerOn(sc_voltage);
/* Check again the State */
error = CCID_CheckCommandParams(pdev, (uint32_t)CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
}
else
{
/* Voltage requested from Host was 5V already*/
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_INACTIVE));
return error;
}
} /* Voltage Selection was automatic */
} /* If Active State */
/* ATR is received, No Error Condition Found */
hccid->UsbBlkInData.dwLength = SIZE_OF_ATR;
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
for (index = 0U; index < SIZE_OF_ATR; index++)
{
/* Copy the ATR to the Response Buffer */
hccid->UsbBlkInData.abData[index] = SC_ATR_Table[index];
}
return SLOT_NO_ERROR;
}
/**
* @brief PC_to_RDR_IccPowerOff
* Icc VCC is switched Off
* @param pdev: device instance
* @retval error: status of the command execution
*/
uint8_t PC_to_RDR_IccPowerOff(USBD_HandleTypeDef *pdev)
{
/* The response to this command is the RDR_to_PC_SlotStatus*/
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_ABRFU3 |
CHK_PARAM_DWLENGTH);
if (error != 0U)
{
return error;
}
/* Command is ok, Check for Card Presence */
if (SC_Detect() != 0U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_INACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_NO_ICC_PRESENT));
}
/* Power OFF the card */
SC_Itf_IccPowerOff();
return SLOT_NO_ERROR;
}
/**
* @brief PC_to_RDR_GetSlotStatus
* Provides the Slot status to the host
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_GetSlotStatus(USBD_HandleTypeDef *pdev)
{
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_DWLENGTH |
CHK_PARAM_CARD_PRESENT | CHK_PARAM_ABRFU3);
if (error != 0U)
{
return error;
}
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
return SLOT_NO_ERROR;
}
/**
* @brief PC_to_RDR_XfrBlock
* Handles the Block transfer from Host.
* Response to this command message is the RDR_to_PC_DataBlock
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_XfrBlock(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t expectedLength;
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU3 | CHK_PARAM_ABORT | CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
if (hccid->UsbBlkOutData.dwLength > ABDATA_SIZE)
{
/* Check amount of Data Sent by Host is > than memory allocated ? */
return SLOTERROR_BAD_DWLENGTH;
}
/* wLevelParameter = Size of expected data to be returned by the
bulk-IN endpoint */
expectedLength = (uint8_t)((hccid->UsbBlkOutData.bSpecific_2 << 8) |
hccid->UsbBlkOutData.bSpecific_1);
hccid->UsbBlkInData.dwLength = (uint16_t)expectedLength;
error = SC_Itf_XferBlock(&(hccid->UsbBlkOutData.abData[0]),
hccid->UsbBlkOutData.dwLength,
expectedLength, &hccid->UsbBlkInData);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
error = SLOT_NO_ERROR;
}
return error;
}
/**
* @brief PC_to_RDR_GetParameters
* Provides the ICC parameters to the host
* Response to this command message is the RDR_to_PC_Parameters
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_GetParameters(USBD_HandleTypeDef *pdev)
{
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_DWLENGTH |
CHK_PARAM_CARD_PRESENT | CHK_PARAM_ABRFU3);
if (error != 0U)
{
return error;
}
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
return SLOT_NO_ERROR;
}
/**
* @brief PC_to_RDR_ResetParameters
* Set the ICC parameters to the default
* Response to this command message is the RDR_to_PC_Parameters
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_ResetParameters(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_DWLENGTH |
CHK_PARAM_CARD_PRESENT | CHK_PARAM_ABRFU3 |
CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
/* This command resets the slot parameters to their default values */
hccid->UsbBlkOutData.abData[0] = DEFAULT_FIDI;
hccid->UsbBlkOutData.abData[1] = DEFAULT_T01CONVCHECKSUM;
hccid->UsbBlkOutData.abData[2] = DEFAULT_EXTRA_GUARDTIME;
hccid->UsbBlkOutData.abData[3] = DEFAULT_WAITINGINTEGER;
hccid->UsbBlkOutData.abData[4] = DEFAULT_CLOCKSTOP;
hccid->UsbBlkOutData.abData[5] = 0x00U;
hccid->UsbBlkOutData.abData[6] = 0x00U;
(void)USBD_memcpy(&ProtocolData, (void const *)(&hccid->UsbBlkOutData.abData[0]),
sizeof(ProtocolData));
error = SC_Itf_SetParams(&ProtocolData, ProtocolNUM_OUT);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
error = SLOT_NO_ERROR;
}
return error;
}
/**
* @brief PC_to_RDR_SetParameters
* Set the ICC parameters to the host defined parameters
* Response to this command message is the RDR_to_PC_Parameters
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_SetParameters(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU2 | CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
error = SLOT_NO_ERROR;
/* for Protocol T=0 (dwLength=00000005h) */
/* for Protocol T=1 (dwLength=00000007h) */
if (((hccid->UsbBlkOutData.dwLength == 5U) && (hccid->UsbBlkOutData.bSpecific_0 != 0U))
|| ((hccid->UsbBlkOutData.dwLength == 7U) && (hccid->UsbBlkOutData.bSpecific_0 != 1U)))
{
error = SLOTERROR_BAD_PROTOCOLNUM;
}
if (hccid->UsbBlkOutData.abData[4] != DEFAULT_CLOCKSTOP)
{
error = SLOTERROR_BAD_CLOCKSTOP;
}
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
(void)USBD_memcpy(&ProtocolData, (void const *)(&hccid->UsbBlkOutData.abData[0]),
sizeof(ProtocolData));
error = SC_Itf_SetParams(&ProtocolData, ProtocolNUM_OUT);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
error = SLOT_NO_ERROR;
}
return error;
}
/**
* @brief PC_to_RDR_Escape
* Execute the Escape command. This is user specific Implementation
* Response to this command message is the RDR_to_PC_Escape
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_Escape(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
uint32_t size;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU3 | CHK_PARAM_ABORT | CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
error = SC_Itf_Escape(&hccid->UsbBlkOutData.abData[0], hccid->UsbBlkOutData.dwLength,
&hccid->UsbBlkInData.abData[0], &size);
hccid->UsbBlkInData.dwLength = size;
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/**
* @brief PC_to_RDR_IccClock
* Execute the Clock specific command from host
* Response to this command message is the RDR_to_PC_SlotStatus
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_IccClock(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU2 | CHK_PARAM_DWLENGTH | CHK_ACTIVE_STATE);
if (error != 0U)
{
return error;
}
/* bClockCommand :
00h restarts Clock
01h Stops Clock in the state shown in the bClockStop field */
if (hccid->UsbBlkOutData.bSpecific_0 > 1U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_CLOCKCOMMAND;
}
error = SC_Itf_SetClock(hccid->UsbBlkOutData.bSpecific_0);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/**
* @brief PC_to_RDR_Abort
* Execute the Abort command from host, This stops all Bulk transfers
* from host and ICC
* Response to this command message is the RDR_to_PC_SlotStatus
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_to_RDR_Abort(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_ABRFU3 |
CHK_PARAM_DWLENGTH);
if (error != 0U)
{
return error;
}
(void)CCID_CmdAbort(pdev, hccid->UsbBlkOutData.bSlot, hccid->UsbBlkOutData.bSeq);
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
return SLOT_NO_ERROR;
}
/**
* @brief CCID_CmdAbort
* Execute the Abort command from Bulk EP or from Control EP,
* This stops all Bulk transfers from host and ICC
* @param pdev: device instance
* @param slot: slot number that host wants to abort
* @param seq : Seq number for PC_to_RDR_Abort
* @retval status of the command execution
*/
uint8_t CCID_CmdAbort(USBD_HandleTypeDef *pdev, uint8_t slot, uint8_t seq)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t BSlot = hccid->USBD_CCID_Param.bSlot;
/* This function is called for REQUEST_ABORT & PC_to_RDR_Abort */
if (slot >= CCID_NUMBER_OF_SLOTS)
{
/* error from CLASS_REQUEST*/
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_NO_ICC_PRESENT));
return SLOTERROR_BAD_SLOT;
}
if (hccid->USBD_CCID_Param.bAbortRequestFlag == 1U)
{
/* Abort Command was already received from ClassReq or PC_to_RDR */
if ((hccid->USBD_CCID_Param.bSeq == seq) && (BSlot == slot))
{
/* CLASS Specific request is already Received, Reset the abort flag */
hccid->USBD_CCID_Param.bAbortRequestFlag = 0;
}
}
else
{
/* Abort Command was NOT received from ClassReq or PC_to_RDR,
so save them for next ABORT command to verify */
hccid->USBD_CCID_Param.bAbortRequestFlag = 1U;
hccid->USBD_CCID_Param.bSeq = seq;
hccid->USBD_CCID_Param.bSlot = slot;
}
return 0;
}
/**
* @brief PC_TO_RDR_T0Apdu
* Execute the PC_TO_RDR_T0APDU command from host
* Response to this command message is the RDR_to_PC_SlotStatus
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_TO_RDR_T0Apdu(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_DWLENGTH | CHK_PARAM_ABORT);
if (error != 0U)
{
return error;
}
if (hccid->UsbBlkOutData.bSpecific_0 > 0x03U)
{
/* Bit 0 is associated with bClassGetResponse
Bit 1 is associated with bClassEnvelope */
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_BMCHANGES;
}
error = SC_Itf_T0Apdu(hccid->UsbBlkOutData.bSpecific_0,
hccid->UsbBlkOutData.bSpecific_1,
hccid->UsbBlkOutData.bSpecific_2);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/**
* @brief PC_TO_RDR_Mechanical
* Execute the PC_TO_RDR_MECHANICAL command from host
* Response to this command message is the RDR_to_PC_SlotStatus
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_TO_RDR_Mechanical(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU2 | CHK_PARAM_DWLENGTH);
if (error != 0U)
{
return error;
}
if (hccid->UsbBlkOutData.bSpecific_0 > 0x05U)
{
/*
01h Accept Card
02h Eject Card
03h Capture Card
04h Lock Card
05h Unlock Card
*/
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_BFUNCTION_MECHANICAL;
}
error = SC_Itf_Mechanical(hccid->UsbBlkOutData.bSpecific_0);
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/**
* @brief PC_TO_RDR_SetDataRateAndClockFrequency
* Set the required Card Frequency and Data rate from the host.
* Response to this command message is the
* RDR_to_PC_DataRateAndClockFrequency
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_TO_RDR_SetDataRateAndClockFrequency(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
uint32_t clockFrequency;
uint32_t dataRate;
uint32_t temp;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABRFU3);
if (error != 0U)
{
return error;
}
if (hccid->UsbBlkOutData.dwLength != 0x08U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_LENTGH;
}
/* HERE we avoiding to an unaligned memory access*/
temp = (uint32_t)(hccid->UsbBlkOutData.abData[0]) & 0x000000FFU;
clockFrequency = temp;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[1]) & 0x000000FFU;
clockFrequency |= temp << 8;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[2]) & 0x000000FFU;
clockFrequency |= temp << 16;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[3]) & 0x000000FFU;
clockFrequency |= temp << 24;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[4]) & 0x000000FFU;
dataRate = temp;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[5]) & 0x000000FFU;
dataRate |= temp << 8;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[6]) & 0x000000FFU;
dataRate |= temp << 16;
temp = (uint32_t)(hccid->UsbBlkOutData.abData[7]) & 0x000000FFU;
dataRate |= temp << 24;
error = SC_Itf_SetDataRateAndClockFrequency(clockFrequency, dataRate);
hccid->UsbBlkInData.bError = error;
if (error != SLOT_NO_ERROR)
{
hccid->UsbBlkInData.dwLength = 0;
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
hccid->UsbBlkInData.dwLength = 8;
(hccid->UsbBlkInData.abData[0]) = (uint8_t)(clockFrequency & 0x000000FFU) ;
(hccid->UsbBlkInData.abData[1]) = (uint8_t)((clockFrequency & 0x0000FF00U) >> 8);
(hccid->UsbBlkInData.abData[2]) = (uint8_t)((clockFrequency & 0x00FF0000U) >> 16);
(hccid->UsbBlkInData.abData[3]) = (uint8_t)((clockFrequency & 0xFF000000U) >> 24);
(hccid->UsbBlkInData.abData[4]) = (uint8_t)(dataRate & 0x000000FFU) ;
(hccid->UsbBlkInData.abData[5]) = (uint8_t)((dataRate & 0x0000FF00U) >> 8);
(hccid->UsbBlkInData.abData[6]) = (uint8_t)((dataRate & 0x00FF0000U) >> 16);
(hccid->UsbBlkInData.abData[7]) = (uint8_t)((dataRate & 0xFF000000U) >> 24);
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/**
* @brief PC_TO_RDR_Secure
* Execute the Secure Command from the host.
* Response to this command message is the RDR_to_PC_DataBlock
* @param pdev: device instance
* @retval status of the command execution
*/
uint8_t PC_TO_RDR_Secure(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t error;
uint8_t bBWI;
uint16_t wLevelParameter;
uint32_t responseLen;
hccid->UsbBlkInData.dwLength = 0;
error = CCID_CheckCommandParams(pdev, CHK_PARAM_SLOT | CHK_PARAM_CARD_PRESENT |
CHK_PARAM_ABORT);
if (error != 0U)
{
return error;
}
bBWI = hccid->UsbBlkOutData.bSpecific_0;
wLevelParameter = (hccid->UsbBlkOutData.bSpecific_1 + ((uint16_t)hccid->UsbBlkOutData.bSpecific_2 << 8));
if ((EXCHANGE_LEVEL_FEATURE == TPDU_EXCHANGE) ||
(EXCHANGE_LEVEL_FEATURE == SHORT_APDU_EXCHANGE))
{
/* TPDU level & short APDU level, wLevelParameter is RFU, = 0000h */
if (wLevelParameter != 0U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
error = SLOTERROR_BAD_LEVELPARAMETER;
return error;
}
}
error = SC_Itf_Secure(hccid->UsbBlkOutData.dwLength, bBWI, wLevelParameter,
&(hccid->UsbBlkOutData.abData[0]), &responseLen);
hccid->UsbBlkInData.dwLength = responseLen;
if (error != SLOT_NO_ERROR)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
}
else
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_NO_ERROR), (BM_ICC_PRESENT_ACTIVE));
}
return error;
}
/******************************************************************************/
/* BULK IN ROUTINES */
/******************************************************************************/
/**
* @brief RDR_to_PC_DataBlock
* Provide the data block response to the host
* Response for PC_to_RDR_IccPowerOn, PC_to_RDR_XfrBlock
* @param errorCode: code to be returned to the host
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_DataBlock(uint8_t errorCode, USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t length = CCID_RESPONSE_HEADER_SIZE;
hccid->UsbBlkInData.bMessageType = RDR_TO_PC_DATABLOCK;
hccid->UsbBlkInData.bError = 0U;
hccid->UsbBlkInData.bSpecific = 0U; /* bChainParameter */
if (errorCode == SLOT_NO_ERROR)
{
length += hccid->UsbBlkInData.dwLength; /* Length Specified in Command */
}
(void)USBD_CCID_Transfer_Data_Request(pdev, (uint8_t *)&hccid->UsbBlkInData, (uint16_t)length);
}
/**
* @brief RDR_to_PC_SlotStatus
* Provide the Slot status response to the host
* Response for PC_to_RDR_IccPowerOff
* PC_to_RDR_GetSlotStatus
* PC_to_RDR_IccClock
* PC_to_RDR_T0APDU
* PC_to_RDR_Mechanical
* Also the device sends this response message when it has completed
* aborting a slot after receiving both the Class Specific ABORT request
* and PC_to_RDR_Abort command message.
* @param errorCode: code to be returned to the host
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_SlotStatus(uint8_t errorCode, USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t length = CCID_RESPONSE_HEADER_SIZE;
hccid->UsbBlkInData.bMessageType = RDR_TO_PC_SLOTSTATUS;
hccid->UsbBlkInData.dwLength = 0U;
hccid->UsbBlkInData.bError = 0U;
hccid->UsbBlkInData.bSpecific = 0U; /* bClockStatus = 00h Clock running
01h Clock stopped in state L
02h Clock stopped in state H
03h Clock stopped in an unknown state */
if (errorCode == SLOT_NO_ERROR)
{
length += (uint16_t)hccid->UsbBlkInData.dwLength;
}
(void)USBD_CCID_Transfer_Data_Request(pdev, (uint8_t *)(&hccid->UsbBlkInData), length);
}
/**
* @brief RDR_to_PC_Parameters
* Provide the data block response to the host
* Response for PC_to_RDR_GetParameters, PC_to_RDR_ResetParameters
* PC_to_RDR_SetParameters
* @param errorCode: code to be returned to the host
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_Parameters(uint8_t errorCode, USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t length = CCID_RESPONSE_HEADER_SIZE;
hccid->UsbBlkInData.bMessageType = RDR_TO_PC_PARAMETERS;
hccid->UsbBlkInData.bError = 0U;
if (errorCode == SLOT_NO_ERROR)
{
if (ProtocolNUM_OUT == 0x00U)
{
hccid->UsbBlkInData.dwLength = LEN_PROTOCOL_STRUCT_T0;
length += (uint16_t)hccid->UsbBlkInData.dwLength;
}
else
{
hccid->UsbBlkInData.dwLength = LEN_PROTOCOL_STRUCT_T1;
length += (uint16_t)hccid->UsbBlkInData.dwLength;
}
}
else
{
hccid->UsbBlkInData.dwLength = 0;
}
hccid->UsbBlkInData.abData[0] = ProtocolData.bmFindexDindex;
hccid->UsbBlkInData.abData[1] = ProtocolData.bmTCCKST0;
hccid->UsbBlkInData.abData[2] = ProtocolData.bGuardTimeT0;
hccid->UsbBlkInData.abData[3] = ProtocolData.bWaitingIntegerT0;
hccid->UsbBlkInData.abData[4] = ProtocolData.bClockStop;
hccid->UsbBlkInData.abData[5] = ProtocolData.bIfsc;
hccid->UsbBlkInData.abData[6] = ProtocolData.bNad;
/* bProtocolNum */
if (ProtocolNUM_OUT == 0x00U)
{
hccid->UsbBlkInData.bSpecific = BPROTOCOL_NUM_T0;
}
else
{
hccid->UsbBlkInData.bSpecific = BPROTOCOL_NUM_T1;
}
(void)USBD_CCID_Transfer_Data_Request(pdev, (uint8_t *)(&hccid->UsbBlkInData), length);
}
/**
* @brief RDR_to_PC_Escape
* Provide the Escaped data block response to the host
* Response for PC_to_RDR_Escape
* @param errorCode: code to be returned to the host
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_Escape(uint8_t errorCode, USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t length = CCID_RESPONSE_HEADER_SIZE;
hccid->UsbBlkInData.bMessageType = RDR_TO_PC_ESCAPE;
hccid->UsbBlkInData.bSpecific = 0U; /* Reserved for Future Use */
hccid->UsbBlkInData.bError = errorCode;
if (errorCode == SLOT_NO_ERROR)
{
length += hccid->UsbBlkInData.dwLength; /* Length Specified in Command */
}
(void)USBD_CCID_Transfer_Data_Request(pdev, (uint8_t *)(&hccid->UsbBlkInData), (uint16_t)length);
}
/**
* @brief RDR_to_PC_DataRateAndClockFrequency
* Provide the Clock and Data Rate information to host
* Response for PC_TO_RDR_SetDataRateAndClockFrequency
* @param errorCode: code to be returned to the host
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_DataRateAndClockFrequency(uint8_t errorCode, USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t length = CCID_RESPONSE_HEADER_SIZE;
hccid->UsbBlkInData.bMessageType = RDR_TO_PC_DATARATEANDCLOCKFREQUENCY;
hccid->UsbBlkInData.bError = errorCode;
hccid->UsbBlkInData.bSpecific = 0U; /* Reserved for Future Use */
if (errorCode == SLOT_NO_ERROR)
{
length += hccid->UsbBlkInData.dwLength; /* Length Specified in Command */
}
(void)USBD_CCID_Transfer_Data_Request(pdev, (uint8_t *)(&hccid->UsbBlkInData), (uint16_t)length);
}
/**
* @brief RDR_to_PC_NotifySlotChange
* Interrupt message to be sent to the host, Checks the card presence
* status and update the buffer accordingly
* @param pdev: device instance
* @retval None
*/
void RDR_to_PC_NotifySlotChange(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hccid->UsbIntData[OFFSET_INT_BMESSAGETYPE] = RDR_TO_PC_NOTIFYSLOTCHANGE;
if (SC_Detect() != 0U)
{
/*
SLOT_ICC_PRESENT 0x01 : LSb : (0b = no ICC present, 1b = ICC present)
SLOT_ICC_CHANGE 0x02 : MSb : (0b = no change, 1b = change).
*/
hccid->UsbIntData[OFFSET_INT_BMSLOTICCSTATE] = SLOT_ICC_PRESENT | SLOT_ICC_CHANGE;
}
else
{
hccid->UsbIntData[OFFSET_INT_BMSLOTICCSTATE] = SLOT_ICC_CHANGE;
/* Power OFF the card */
SC_Itf_IccPowerOff();
}
}
/**
* @brief CCID_UpdSlotStatus
* Updates the variable for the slot status
* @param pdev: device instance
* @param slotStatus : slot status from the calling function
* @retval None
*/
void CCID_UpdSlotStatus(USBD_HandleTypeDef *pdev, uint8_t slotStatus)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hccid->SlotStatus.SlotStatus = slotStatus;
}
/**
* @brief CCID_UpdSlotChange
* Updates the variable for the slot change status
* @param pdev: device instance
* @param changeStatus : slot change status from the calling function
* @retval None
*/
void CCID_UpdSlotChange(USBD_HandleTypeDef *pdev, uint8_t changeStatus)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hccid->SlotStatus.SlotStatusChange = changeStatus;
}
/**
* @brief CCID_IsSlotStatusChange
* Provides the value of the variable for the slot change status
* @param pdev: device instance
* @retval slot change status
*/
uint8_t CCID_IsSlotStatusChange(USBD_HandleTypeDef *pdev)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
return hccid->SlotStatus.SlotStatusChange;
}
/**
* @brief CCID_UpdateCommandStatus
* Updates the variable for the BulkIn status
* @param pdev: device instance
* @param cmd_status : Command change status from the calling function
* @param icc_status : Slot change status from the calling function
* @retval None
*/
static void CCID_UpdateCommandStatus(USBD_HandleTypeDef *pdev, uint8_t cmd_status, uint8_t icc_status)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hccid->UsbBlkInData.bStatus = (cmd_status | icc_status);
}
/**
* @brief CCID_CheckCommandParams
* Checks the specific parameters requested by the function and update
* status accordingly. This function is called from all
* PC_to_RDR functions
* @param pdev: device instance
* @param param_type : Parameter enum to be checked by calling function
* @retval status
*/
static uint8_t CCID_CheckCommandParams(USBD_HandleTypeDef *pdev, uint32_t param_type)
{
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t parameter;
uint8_t GetState = SC_GetState();
hccid->UsbBlkInData.bStatus = BM_ICC_PRESENT_ACTIVE | BM_COMMAND_STATUS_NO_ERROR;
parameter = (uint32_t)param_type;
if ((parameter & CHK_PARAM_SLOT) != 0U)
{
/*
The slot number (bSlot) identifies which ICC slot is being addressed
by the message*/
/* SLOT Number is 0 onwards, so always < CCID_NUMBER_OF_SLOTs */
/* Error Condition !!! */
if (hccid->UsbBlkOutData.bSlot >= CCID_NUMBER_OF_SLOTS)
{
/* Slot requested is more than supported by Firmware */
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_NO_ICC_PRESENT));
return SLOTERROR_BAD_SLOT;
}
}
if ((parameter & CHK_PARAM_CARD_PRESENT) != 0U)
{
/* Commands Parameters ok, Check the Card Status */
if (SC_Detect() == 0U)
{
/* Card is Not detected */
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_NO_ICC_PRESENT));
return SLOTERROR_ICC_MUTE;
}
}
/* Check that DwLength is 0 */
if ((parameter & CHK_PARAM_DWLENGTH) != 0U)
{
if (hccid->UsbBlkOutData.dwLength != 0U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_LENTGH;
}
}
/* abRFU 2 : Reserved for Future Use*/
if ((parameter & CHK_PARAM_ABRFU2) != 0U)
{
if ((hccid->UsbBlkOutData.bSpecific_1 != 0U) || (hccid->UsbBlkOutData.bSpecific_2 != 0U))
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_ABRFU_2B; /* bSpecific_1 */
}
}
if ((parameter & CHK_PARAM_ABRFU3) != 0U)
{
/* abRFU 3 : Reserved for Future Use*/
if ((hccid->UsbBlkOutData.bSpecific_0 != 0U) ||
(hccid->UsbBlkOutData.bSpecific_1 != 0U) ||
(hccid->UsbBlkOutData.bSpecific_2 != 0U))
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_ACTIVE));
return SLOTERROR_BAD_ABRFU_3B;
}
}
if ((parameter & CHK_PARAM_ABORT) != 0U)
{
if (hccid->USBD_CCID_Param.bAbortRequestFlag != 0U)
{
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_INACTIVE));
return SLOTERROR_CMD_ABORTED;
}
}
if ((parameter & CHK_ACTIVE_STATE) != 0U)
{
/* Commands Parameters ok, Check the Card Status */
/* Card is detected */
if ((GetState != (uint8_t)SC_ACTIVE_ON_T0) && (GetState != (uint8_t)SC_ACTIVE_ON_T1))
{
/* Check that from Lower Layers, the SmartCard come to known state */
CCID_UpdateCommandStatus(pdev, (BM_COMMAND_STATUS_FAILED), (BM_ICC_PRESENT_INACTIVE));
return SLOTERROR_HW_ERROR;
}
}
return 0U;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Src\usbd_ccid_if_template.c | /**
******************************************************************************
* @file usbd_ccid_if_template.c
* @author MCD Application Team
* @brief This file provides all the functions for USB Interface for CCID
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid.h"
#include "usbd_ccid_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static REP_Command_t REP_command;
/* Private function prototypes -----------------------------------------------*/
static uint8_t CCID_Init(USBD_HandleTypeDef *pdev);
static uint8_t CCID_DeInit(USBD_HandleTypeDef *pdev);
static uint8_t CCID_ControlReq(uint8_t req, uint8_t *pbuf, uint16_t *length);
static uint8_t CCID_Response_SendData(USBD_HandleTypeDef *pdev, uint8_t *buf, uint16_t len);
static uint8_t CCID_Send_Process(uint8_t *Command, uint8_t *Data);
static uint8_t CCID_Response_Process(void);
static uint8_t CCID_SetSlotStatus(USBD_HandleTypeDef *pdev);
/* Private functions ---------------------------------------------------------*/
/**
* @}
*/
USBD_CCID_ItfTypeDef USBD_CCID_If_fops =
{
CCID_Init,
CCID_DeInit,
CCID_ControlReq,
CCID_Response_SendData,
CCID_Send_Process,
CCID_SetSlotStatus,
};
/**
* @brief CCID_Init
* Initialize the CCID USB Layer
* @param pdev: device instance
* @retval status value
*/
uint8_t CCID_Init(USBD_HandleTypeDef *pdev)
{
#ifdef USE_USBD_COMPOSITE
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#else
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassData;
#endif /* USE_USBD_COMPOSITE */
/* CCID Related Initialization */
hccid->blkt_state = CCID_STATE_IDLE;
return (uint8_t)USBD_OK;
}
/**
* @brief CCID_DeInit
* Uninitialize the CCID Machine
* @param pdev: device instance
* @retval status value
*/
uint8_t CCID_DeInit(USBD_HandleTypeDef *pdev)
{
#ifdef USE_USBD_COMPOSITE
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#else
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassData;
#endif /* USE_USBD_COMPOSITE */
hccid->blkt_state = CCID_STATE_IDLE;
return (uint8_t)USBD_OK;
}
/**
* @brief CCID_ControlReq
* Manage the CCID class requests
* @param Cmd: Command code
* @param Buf: Buffer containing command data (request parameters)
* @param Len: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static uint8_t CCID_ControlReq(uint8_t req, uint8_t *pbuf, uint16_t *length)
{
#ifdef USE_USBD_COMPOSITE
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)USBD_Device.pClassDataCmsit[USBD_Device.classId];
#else
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)USBD_Device.pClassData;
#endif /* USE_USBD_COMPOSITE */
UNUSED(length);
switch (req)
{
case REQUEST_ABORT:
/* The wValue field contains the slot number (bSlot) in the low byte
and the sequence number (bSeq) in the high byte.*/
hccid->slot_nb = ((uint16_t) * pbuf & 0x0fU);
hccid->seq_nb = (((uint16_t) * pbuf & 0xf0U) >> 8);
if (CCID_CmdAbort(&USBD_Device, (uint8_t)hccid->slot_nb, (uint8_t)hccid->seq_nb) != 0U)
{
/* If error is returned by lower layer :
Generally Slot# may not have matched */
return (int8_t)USBD_FAIL;
}
break;
case REQUEST_GET_CLOCK_FREQUENCIES:
/* User have to fill the pbuf with the GetClockFrequency data buffer */
break;
case REQUEST_GET_DATA_RATES:
/* User have to fill the pbuf with the GetDataRates data buffer */
break;
default:
break;
}
UNUSED(pbuf);
return ((int8_t)USBD_OK);
}
/**
* @brief CCID_Response_SendData
* Send the data on bulk-in EP
* @param pdev: device instance
* @param buf: pointer to data buffer
* @param len: Data Length
* @retval status value
*/
uint8_t CCID_Response_SendData(USBD_HandleTypeDef *pdev, uint8_t *buf, uint16_t len)
{
(void)USBD_LL_Transmit(pdev, CCID_IN_EP, buf, len);
return (uint8_t)USBD_OK;
}
/**
* @brief CCID_SEND_Process
* @param Command: pointer to a buffer containing command header
* @param Data: pointer to a buffer containing data sent from Host
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static uint8_t CCID_Send_Process(uint8_t *Command, uint8_t *Data)
{
Command_State_t Command_State = Command_NOT_OK;
/* Initialize ICC APP header */
uint8_t SC_Command[5] = {0};
UNUSED(Data);
UNUSED(Command_State);
UNUSED(SC_Command);
/* Start SC Demo ---------------------------------------------------------*/
switch (Command[1]) /* type of instruction */
{
case SC_ENABLE:
/* Add your code here */
break;
case SC_VERIFY:
/* Add your code here */
break;
case SC_READ_BINARY :
/* Add your code here */
break;
case SC_CHANGE :
/* Add your code here */
break;
default:
break;
}
/* check if Command header is OK */
(void)CCID_Response_Process(); /* Get ICC response */
return ((uint8_t)USBD_OK);
}
/**
* @brief CCID_Response_Process
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static uint8_t CCID_Response_Process(void)
{
switch (REP_command)
{
case REP_OK:
/* Add your code here */
break;
case REP_NOT_OK :
/* Add your code here */
break;
case REP_NOT_SUPP :
/* Add your code here */
break;
case REP_ENABLED :
/* Add your code here */
break;
case REP_CHANGE :
/* Add your code here */
break;
default:
break;
}
return ((uint8_t)USBD_OK);
}
/**
* @brief CCID_SetSlotStatus
* Set Slot Status of the Interrupt Transfer
* @param pdev: device instance
* @retval status
*/
uint8_t CCID_SetSlotStatus(USBD_HandleTypeDef *pdev)
{
/* Get the CCID handler pointer */
#ifdef USE_USBD_COMPOSITE
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#else
USBD_CCID_HandleTypeDef *hccid = (USBD_CCID_HandleTypeDef *)pdev->pClassData;
#endif /* USE_USBD_COMPOSITE */
if ((hccid->SlotStatus.SlotStatus) == 1U) /* Transfer Complete Status
of previous Interrupt transfer */
{
/* Add your code here */
}
else
{
/* Add your code here */
}
return (uint8_t)USBD_OK;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Src\usbd_ccid_sc_if_template.c | /**
******************************************************************************
* @file usbd_ccid_sc_if_template.c
* @author MCD Application Team
* @brief SmartCard Interface file
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid_sc_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* State Machine for the SmartCard Interface */
static SC_State SCState = SC_POWER_OFF;
/* APDU Transport Structures */
SC_ADPU_CommandsTypeDef SC_ADPU;
SC_ADPU_ResponseTypeDef SC_Response;
SC_Param_t SC_Param;
Protocol_01_DataTypeDef ProtocolData;
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void SC_SaveVoltage(uint8_t voltage);
static void SC_Itf_UpdateParams(void);
/* Private functions ---------------------------------------------------------*/
/**
* @brief SC_Itf_IccPowerOn Manages the Warm and Cold Reset
and get the Answer to Reset from ICC
* @param voltage: required by host
* @retval None
*/
void SC_Itf_IccPowerOn(uint8_t voltage)
{
SCState = SC_POWER_ON;
SC_ADPU.Header.CLA = 0x00U;
SC_ADPU.Header.INS = SC_GET_A2R;
SC_ADPU.Header.P1 = 0x00U;
SC_ADPU.Header.P2 = 0x00U;
SC_ADPU.Body.LC = 0x00U;
/* Power ON the card */
SC_PowerCmd(SC_ENABLED);
/* Configure the Voltage, Even if IO is still not configured */
SC_VoltageConfig(voltage);
while ((SCState != SC_ACTIVE_ON_T0) && (SCState != SC_ACTIVE_ON_T1)
&& (SCState != SC_NO_INIT))
{
/* If Either The Card has become Active or Become De-Active */
SC_Handler(&SCState, &SC_ADPU, &SC_Response);
}
if ((SCState == SC_ACTIVE_ON_T0) || (SCState == SC_ACTIVE_ON_T1))
{
SC_Itf_UpdateParams();
/* Apply the Procedure Type Selection (PTS) */
SC_PTSConfig();
/* Save Voltage for Future use */
SC_SaveVoltage(voltage);
}
return;
}
/**
* @brief SC_Itf_IccPowerOff Power OFF the card
* @param None
* @retval None
*/
void SC_Itf_IccPowerOff(void)
{
SC_PowerCmd(SC_DISABLED);
SC_SetState(SC_POWER_OFF);
return;
}
/**
* @brief Initialize the parameters structures to the default value
* @param None
* @retval None
*/
void SC_Itf_InitParams(void)
{
/*
FI, the reference to a clock rate conversion factor
over the bits b8 to b5
- DI, the reference to a baud rate adjustment factor
over the bits b4 to bl
*/
SC_Param.SC_A2R_FiDi = DEFAULT_FIDI;
SC_Param.SC_hostFiDi = DEFAULT_FIDI;
ProtocolData.bmFindexDindex = DEFAULT_FIDI;
/* Placeholder, Ignored */
/* 0 = Direct, first byte of the ICC ATR data. */
ProtocolData.bmTCCKST0 = DEFAULT_T01CONVCHECKSUM;
/* Extra GuardTime = 0 etu */
ProtocolData.bGuardTimeT0 = DEFAULT_EXTRA_GUARDTIME;
ProtocolData.bWaitingIntegerT0 = DEFAULT_WAITINGINTEGER;
ProtocolData.bClockStop = 0U; /* Stopping the Clock is not allowed */
/*T=1 protocol */
ProtocolData.bIfsc = DEFAULT_IFSC;
ProtocolData.bNad = DEFAULT_NAD;
return;
}
/**
* @brief Save the A2R Parameters for further usage
* @param None
* @retval None
*/
static void SC_Itf_UpdateParams(void)
{
/*
FI, the reference to a clock rate conversion factor
over the bits b8 to b5
DI, the reference to a baud rate adjustment factor
over the bits b4 to bl
*/
SC_Param.SC_A2R_FiDi = SC_A2R.T[0].InterfaceByte[0].Value;
SC_Param.SC_hostFiDi = SC_A2R.T[0].InterfaceByte[0].Value;
ProtocolData.bmFindexDindex = SC_A2R.T[0].InterfaceByte[0].Value;
return;
}
/**
* @brief SC_Itf_SetParams
* Set the parameters for CCID/USART interface
* @param pPtr: pointer to buffer containing the
* parameters to be set in USART
* @param T_01: type of protocol, T=1 or T=0
* @retval status value
*/
uint8_t SC_Itf_SetParams(Protocol_01_DataTypeDef *pPtr, uint8_t T_01)
{
/* uint16_t guardTime; */ /* Keep it 16b for handling 8b additions */
uint32_t fi_new;
uint32_t di_new;
Protocol_01_DataTypeDef New_DataStructure;
fi_new = pPtr->bmFindexDindex;
di_new = pPtr->bmFindexDindex;
New_DataStructure.bmTCCKST0 = pPtr->bmTCCKST0;
New_DataStructure.bGuardTimeT0 = pPtr->bGuardTimeT0;
New_DataStructure.bWaitingIntegerT0 = pPtr->bWaitingIntegerT0;
New_DataStructure.bClockStop = pPtr->bClockStop;
if (T_01 == 0x01U)
{
New_DataStructure.bIfsc = pPtr->bIfsc;
New_DataStructure.bNad = pPtr->bNad;
}
else
{
New_DataStructure.bIfsc = 0x00U;
New_DataStructure.bNad = 0x00U;
}
/* Check for the FIDI Value set by Host */
di_new &= (uint8_t)0x0F;
if (SC_GetDTableValue(di_new) == 0U)
{
return SLOTERROR_BAD_FIDI;
}
fi_new >>= 4U;
fi_new &= 0x0FU;
if (SC_GetDTableValue(fi_new) == 0U)
{
return SLOTERROR_BAD_FIDI;
}
if ((T_01 == 0x00U)
&& (New_DataStructure.bmTCCKST0 != 0x00U)
&& (New_DataStructure.bmTCCKST0 != 0x02U))
{
return SLOTERROR_BAD_T01CONVCHECKSUM;
}
if ((T_01 == 0x01U)
&& (New_DataStructure.bmTCCKST0 != 0x10U)
&& (New_DataStructure.bmTCCKST0 != 0x11U)
&& (New_DataStructure.bmTCCKST0 != 0x12U)
&& (New_DataStructure.bmTCCKST0 != 0x13U))
{
return SLOTERROR_BAD_T01CONVCHECKSUM;
}
if ((New_DataStructure.bWaitingIntegerT0 >= 0xA0U)
&& ((New_DataStructure.bmTCCKST0 & 0x10U) == 0x10U))
{
return SLOTERROR_BAD_WAITINGINTEGER;
}
if ((New_DataStructure.bClockStop != 0x00U)
&& (New_DataStructure.bClockStop != 0x03U))
{
return SLOTERROR_BAD_CLOCKSTOP;
}
if (New_DataStructure.bNad != 0x00U)
{
return SLOTERROR_BAD_NAD;
}
/* Put Total GuardTime in USART Settings */
/* USART_SetGuardTime(SC_USART, (uint8_t)(guardTime + DEFAULT_EXTRA_GUARDTIME)); */
/* Save Extra GuardTime Value */
ProtocolData.bGuardTimeT0 = New_DataStructure.bGuardTimeT0;
ProtocolData.bmTCCKST0 = New_DataStructure.bmTCCKST0;
ProtocolData.bWaitingIntegerT0 = New_DataStructure.bWaitingIntegerT0;
ProtocolData.bClockStop = New_DataStructure.bClockStop;
ProtocolData.bIfsc = New_DataStructure.bIfsc;
ProtocolData.bNad = New_DataStructure.bNad;
/* Save New bmFindexDindex */
SC_Param.SC_hostFiDi = pPtr->bmFindexDindex;
SC_PTSConfig();
ProtocolData.bmFindexDindex = pPtr->bmFindexDindex;
return SLOT_NO_ERROR;
}
/**
* @brief SC_Itf_Escape function from the host
* This is user implementable
* @param ptrEscape: pointer to buffer containing the Escape data
* @param escapeLen: length of escaped data
* @param responseBuff: pointer containing escape buffer response
* @param responseLen: length of escape response buffer
* @retval status value
*/
uint8_t SC_Itf_Escape(uint8_t *ptrEscape, uint32_t escapeLen,
uint8_t *responseBuff, uint32_t *responseLen)
{
UNUSED(ptrEscape);
UNUSED(escapeLen);
UNUSED(responseBuff);
UNUSED(responseLen);
/* Manufacturer specific implementation ... */
/*
uint32_t idx;
uint8_t *pResBuff = responseBuff;
uint8_t *pEscape = ptrEscape;
for(idx = 0; idx < escapeLen; idx++)
{
*pResBuff = *pEscape;
pResBuff++;
pEscape++;
}
*responseLen = escapeLen;
*/
return SLOT_NO_ERROR;
}
/**
* @brief SC_Itf_SetClock function to define Clock Status request from the host.
* This is user implementable
* @param bClockCommand: Clock status from the host
* @retval status value
*/
uint8_t SC_Itf_SetClock(uint8_t bClockCommand)
{
/* bClockCommand
00h restarts Clock
01h Stops Clock in the state shown in the bClockStop
field of the PC_to_RDR_SetParameters command
and RDR_to_PC_Parameters message.*/
if (bClockCommand == 0U)
{
/* 00h restarts Clock : Since Clock is always running, PASS this command */
return SLOT_NO_ERROR;
}
else
{
if (bClockCommand == 1U)
{
return SLOTERROR_BAD_CLOCKCOMMAND;
}
}
return SLOTERROR_CMD_NOT_SUPPORTED;
}
/**
* @brief SC_Itf_XferBlock function from the host.
* This is user implementable
* @param ptrBlock : Pointer containing the data from host
* @param blockLen : length of block data for the data transfer
* @param expectedLen: expected length of data transfer
* @param CCID_BulkIn_Data: Pointer containing the CCID Bulk In Data Structure
* @retval status value
*/
uint8_t SC_Itf_XferBlock(uint8_t *ptrBlock, uint32_t blockLen, uint16_t expectedLen,
USBD_CCID_BulkIn_DataTypeDef *CCID_BulkIn_Data)
{
uint8_t ErrorCode = SLOT_NO_ERROR;
UNUSED(CCID_BulkIn_Data);
UNUSED(expectedLen);
UNUSED(blockLen);
UNUSED(ptrBlock);
if (ProtocolNUM_OUT == 0x00U)
{
/* Add your code here */
}
if (ProtocolNUM_OUT == 0x01U)
{
/* Add your code here */
}
if (ErrorCode != SLOT_NO_ERROR)
{
return ErrorCode;
}
return ErrorCode;
}
/**
* @brief SC_Itf_T0Apdu
Class Specific Request from the host to provide supported data rates
* This is Optional function & user implementable
* @param bmChanges : value specifying which parameter is valid in
* command among next bClassGetResponse, bClassEnvelope
* @param bClassGetResponse : Value to force the class byte of the
* header in a Get Response command.
* @param bClassEnvelope : Value to force the class byte of the header
* in a Envelope command.
* @retval status value
*/
uint8_t SC_Itf_T0Apdu(uint8_t bmChanges, uint8_t bClassGetResponse,
uint8_t bClassEnvelope)
{
UNUSED(bClassEnvelope);
UNUSED(bClassGetResponse);
/* User have to fill the pbuf with the GetDataRates data buffer */
if (bmChanges == 0U)
{
/* Bit cleared indicates that the associated field is not significant and
that default behaviour defined in CCID class descriptor is selected */
return SLOT_NO_ERROR;
}
return SLOTERROR_CMD_NOT_SUPPORTED;
}
/**
* @brief SC_Itf_Mechanical
Mechanical Function being requested by Host
* This is Optional function & user implementable
* @param bFunction : value corresponds to the mechanical function
* being requested by host
* @retval status value
*/
uint8_t SC_Itf_Mechanical(uint8_t bFunction)
{
UNUSED(bFunction);
return SLOTERROR_CMD_NOT_SUPPORTED;
}
/**
* @brief SC_Itf_SetDataRateAndClockFrequency
* Set the Clock and data Rate of the Interface
* This is Optional function & user implementable
* @param dwClockFrequency : value of clock in kHz requested by host
* @param dwDataRate : value of data rate requested by host
* @retval status value
*/
uint8_t SC_Itf_SetDataRateAndClockFrequency(uint32_t dwClockFrequency,
uint32_t dwDataRate)
{
/* User have to fill the pbuf with the GetDataRates data buffer */
if ((dwDataRate == USBD_CCID_DEFAULT_DATA_RATE) &&
(dwClockFrequency == USBD_CCID_DEFAULT_CLOCK_FREQ))
{
return SLOT_NO_ERROR;
}
return SLOTERROR_CMD_NOT_SUPPORTED;
}
/**
* @brief SC_Itf_Secure
* Process the Secure command
* This is Optional function & user implementable
* @param dwLength : length of data from the host
* @param bBWI : Block Waiting Timeout sent by host
* @param wLevelParameter : Parameters sent by host
* @param pbuf : buffer containing the data
* @param returnLen : Length of data expected to return
* @retval status value
*/
uint8_t SC_Itf_Secure(uint32_t dwLength, uint8_t bBWI, uint16_t wLevelParameter,
uint8_t *pbuf, uint32_t *returnLen)
{
UNUSED(pbuf);
UNUSED(wLevelParameter);
UNUSED(bBWI);
UNUSED(dwLength);
*returnLen = 0U;
return SLOTERROR_CMD_NOT_SUPPORTED;
}
/**
* @brief SC_SaveVoltage
Saves the voltage value to be saved for further usage
* @param voltage: voltage value to be saved for further usage
* @retval None
*/
static void SC_SaveVoltage(uint8_t voltage)
{
SC_Param.voltage = voltage;
return;
}
/**
* @brief Provides the value of SCState variable
* @param None
* @retval uint8_t SCState
*/
uint8_t SC_GetState(void)
{
return (uint8_t)SCState;
}
/**
* @brief Set the value of SCState variable to Off
* @param scState: value of SCState to be updated
* @retval None
*/
void SC_SetState(SC_State scState)
{
SCState = scState;
return;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CCID\Src\usbd_ccid_smartcard_template.c | /**
******************************************************************************
* @file usbd_ccid_smartcard_template.c
* @author MCD Application Team
* @brief This file provides all the Smartcard firmware functions.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup usbd_ccid_Smartcard
* @{
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_ccid_smartcard_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Directories & Files ID */
/*The following Directories & Files ID can take any of following Values and can
be used in the smartcard application */
/*
const uint8_t MasterRoot[2] = {0x3F, 0x00};
const uint8_t GSMDir[2] = {0x7F, 0x20};
const uint8_t ICCID[2] = {0x2F, 0xE2};
const uint8_t IMSI[2] = {0x6F, 0x07};
__IO uint8_t ICCID_Content[10] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t CHV1Status = 0U;
uint8_t CHV1[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};
__IO uint8_t IMSI_Content[9] = {0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
*/
/* F Table: Clock Rate Conversion Table from ISO/IEC 7816-3 */
/* static uint32_t F_Table[16] = {372, 372, 558, 744, 1116, 1488, 1860, 0, 0, 512, 768,
1024, 1536, 2048, 0, 0
}; */
/* D Table: Baud Rate Adjustment Factor Table from ISO/IEC 7816-3 */
static uint32_t D_Table[16] = {0, 1, 2, 4, 8, 16, 32, 64, 12, 20, 0, 0, 0, 0, 0, 0};
/* Global variables definition and initialization ----------------------------*/
SC_ATRTypeDef SC_A2R;
uint8_t SC_ATR_Table[40];
uint8_t ProtocolNUM_OUT;
/* Private function prototypes -----------------------------------------------*/
static void SC_Init(void);
static void SC_DeInit(void);
static void SC_AnswerReq(SC_State *SC_state, uint8_t *card, uint8_t length); /* Ask ATR */
static uint8_t SC_decode_Answer2reset(uint8_t *card); /* Decode ATR */
static void SC_SendData(SC_ADPU_CommandsTypeDef *SCADPU, SC_ADPU_ResponseTypeDef *SC_ResponseStatus);
/* static void SC_Reset(GPIO_PinState ResetState); */
/* Private functions ---------------------------------------------------------*/
/**
* @brief Handles all Smartcard states and serves to send and receive all
* communication data between Smartcard and reader.
* @param SCState: pointer to an SC_State enumeration that will contain the
* Smartcard state.
* @param SC_ADPU: pointer to an SC_ADPU_Commands structure that will be initialized.
* @param SC_Response: pointer to a SC_ADPU_Response structure which will be initialized.
* @retval None
*/
void SC_Handler(SC_State *SCState, SC_ADPU_CommandsTypeDef *SC_ADPU, SC_ADPU_ResponseTypeDef *SC_Response)
{
uint32_t i;
uint32_t j;
switch (*SCState)
{
case SC_POWER_ON:
if (SC_ADPU->Header.INS == SC_GET_A2R)
{
/* Smartcard initialization */
SC_Init();
/* Reset Data from SC buffer */
for (i = 0U; i < 40U; i++)
{
SC_ATR_Table[i] = 0;
}
/* Reset SC_A2R Structure */
SC_A2R.TS = 0U;
SC_A2R.T0 = 0U;
for (i = 0U; i < MAX_PROTOCOLLEVEL; i++)
{
for (j = 0U; j < MAX_INTERFACEBYTE; j++)
{
SC_A2R.T[i].InterfaceByte[j].Status = 0U;
SC_A2R.T[i].InterfaceByte[j].Value = 0U;
}
}
for (i = 0U; i < HIST_LENGTH; i++)
{
SC_A2R.Historical[i] = 0U;
}
SC_A2R.Tlength = 0U;
SC_A2R.Hlength = 0U;
/* Next State */
*SCState = SC_RESET_LOW;
}
break;
case SC_RESET_LOW:
if (SC_ADPU->Header.INS == SC_GET_A2R)
{
/* If card is detected then Power ON, Card Reset and wait for an answer) */
if (SC_Detect() != 0U)
{
while (((*SCState) != SC_POWER_OFF) && ((*SCState) != SC_ACTIVE))
{
SC_AnswerReq(SCState, &SC_ATR_Table[0], 40U); /* Check for answer to reset */
}
}
else
{
(*SCState) = SC_POWER_OFF;
}
}
break;
case SC_ACTIVE:
if (SC_ADPU->Header.INS == SC_GET_A2R)
{
uint8_t protocol = SC_decode_Answer2reset(&SC_ATR_Table[0]);
if (protocol == T0_PROTOCOL)
{
(*SCState) = SC_ACTIVE_ON_T0;
ProtocolNUM_OUT = T0_PROTOCOL;
}
else if (protocol == T1_PROTOCOL)
{
(*SCState) = SC_ACTIVE_ON_T1;
ProtocolNUM_OUT = T1_PROTOCOL;
}
else
{
(*SCState) = SC_POWER_OFF;
}
}
break;
case SC_ACTIVE_ON_T0:
/* process commands other than ATR */
SC_SendData(SC_ADPU, SC_Response);
break;
case SC_ACTIVE_ON_T1:
/* process commands other than ATR */
SC_SendData(SC_ADPU, SC_Response);
break;
case SC_POWER_OFF:
SC_DeInit(); /* Disable Smartcard interface */
break;
default:
(*SCState) = SC_POWER_OFF;
break;
}
}
/**
* @brief Enables or disables the power to the Smartcard.
* @param NewState: new state of the Smartcard power supply.
* This parameter can be: SC_ENABLED or SC_DISABLED.
* @retval None
*/
void SC_PowerCmd(SCPowerState NewState)
{
UNUSED(NewState);
/* enable or disable smartcard pin */
return;
}
/**
* @brief Sets or clears the Smartcard reset pin.
* @param ResetState: this parameter specifies the state of the Smartcard
* reset pin. BitVal must be one of the BitAction enum values:
* @arg Bit_RESET: to clear the port pin.
* @arg Bit_SET: to set the port pin.
* @retval None
*/
/* static void SC_Reset(GPIO_PinState ResetState)
{
UNUSED(ResetState);
return;
}
*/
/**
* @brief Resends the byte that failed to be received (by the Smartcard) correctly.
* @param None
* @retval None
*/
void SC_ParityErrorHandler(void)
{
/* Add your code here */
return;
}
/**
* @brief Configures the IO speed (BaudRate) communication.
* @param None
* @retval None
*/
void SC_PTSConfig(void)
{
/* Add your code here */
return;
}
/**
* @brief Manages the Smartcard transport layer: send APDU commands and receives
* the APDU response.
* @param SC_ADPU: pointer to a SC_ADPU_Commands structure which will be initialized.
* @param SC_Response: pointer to a SC_ADPU_Response structure which will be initialized.
* @retval None
*/
static void SC_SendData(SC_ADPU_CommandsTypeDef *SCADPU, SC_ADPU_ResponseTypeDef *SC_ResponseStatus)
{
uint8_t i;
uint8_t SC_Command[5];
uint8_t SC_DATA[LC_MAX];
UNUSED(SCADPU);
/* Reset response buffer */
for (i = 0U; i < LC_MAX; i++)
{
SC_ResponseStatus->Data[i] = 0U;
SC_DATA[i] = 0U;
}
/* User to add code here */
/* send command to ICC and get response status */
USBD_CCID_If_fops.Send_Process((uint8_t *)&SC_Command, (uint8_t *)&SC_DATA);
}
/**
* @brief SC_AnswerReq
Requests the reset answer from card.
* @param SC_state: pointer to an SC_State enumeration that will contain the Smartcard state.
* @param atr_buffer: pointer to a buffer which will contain the card ATR.
* @param length: maximum ATR length
* @retval None
*/
static void SC_AnswerReq(SC_State *SC_state, uint8_t *atr_buffer, uint8_t length)
{
UNUSED(length);
UNUSED(atr_buffer);
/* to be implemented by USER */
switch (*SC_state)
{
case SC_RESET_LOW:
/* Check response with reset low */
(*SC_state) = SC_ACTIVE;
break;
case SC_ACTIVE:
break;
case SC_RESET_HIGH:
/* Check response with reset high */
break;
case SC_POWER_OFF:
/* Close Connection if no answer received */
break;
default:
(*SC_state) = SC_RESET_LOW;
break;
}
return;
}
/**
* @brief SC_decode_Answer2reset
Decodes the Answer to reset received from card.
* @param card: pointer to the buffer containing the card ATR.
* @retval None
*/
static uint8_t SC_decode_Answer2reset(uint8_t *card)
{
uint32_t i = 0U;
uint32_t flag = 0U;
uint32_t protocol;
uint8_t index = 0U;
uint8_t level = 0U;
/******************************TS/T0 Decode************************************/
index++;
SC_A2R.TS = card[index]; /* Initial character */
index++;
SC_A2R.T0 = card[index]; /* Format character */
/*************************Historical Table Length Decode***********************/
SC_A2R.Hlength = SC_A2R.T0 & 0x0FU;
/******************************Protocol Level(1) Decode************************/
/* Check TD(1) if present */
if ((SC_A2R.T0 & 0x80U) == 0x80U)
{
flag = 1U;
}
/* Each bits in the T0 high nibble(b8 to b5) equal to 1 indicates the presence
of a further interface byte */
for (i = 0U; i < 4U; i++)
{
if ((((SC_A2R.T0 & 0xF0U) >> (4U + i)) & 0x1U) != 0U)
{
SC_A2R.T[level].InterfaceByte[i].Status = 1U;
index++;
SC_A2R.T[level].InterfaceByte[i].Value = card[index];
SC_A2R.Tlength++;
}
}
/*****************************T Decode*****************************************/
if (SC_A2R.T[level].InterfaceByte[3].Status == 1U)
{
/* Only the protocol(parameter T) present in TD(1) is detected
if two or more values of parameter T are present in TD(1), TD(2)..., so the
firmware should be updated to support them */
protocol = (uint8_t)(SC_A2R.T[level].InterfaceByte[SC_INTERFACEBYTE_TD].Value & 0x0FU);
}
else
{
protocol = 0U;
}
/* Protocol Level Increment */
/******************************Protocol Level(n>1) Decode**********************/
while (flag != 0U)
{
if ((SC_A2R.T[level].InterfaceByte[SC_INTERFACEBYTE_TD].Value & 0x80U) == 0x80U)
{
flag = 1U;
}
else
{
flag = 0U;
}
/* Each bits in the high nibble(b8 to b5) for the TD(i) equal to 1 indicates
the presence of a further interface byte */
for (i = 0U; i < 4U; i++)
{
if ((((SC_A2R.T[level].InterfaceByte[SC_INTERFACEBYTE_TD].Value & 0xF0U) >> (4U + i)) & 0x1U) != 0U)
{
SC_A2R.T[level + 1U].InterfaceByte[i].Status = 1U;
index++;
SC_A2R.T[level + 1U].InterfaceByte[i].Value = card[index];
SC_A2R.Tlength++;
}
}
level++;
}
for (i = 0U; i < SC_A2R.Hlength; i++)
{
SC_A2R.Historical[i] = card[i + 2U + SC_A2R.Tlength];
}
/*************************************TCK Decode*******************************/
SC_A2R.TCK = card[SC_A2R.Hlength + 2U + SC_A2R.Tlength];
return (uint8_t)protocol;
}
/**
* @brief Initializes all peripheral used for Smartcard interface.
* @param None
* @retval None
*/
static void SC_Init(void)
{
/*
Add your initialization code here
*/
return;
}
/**
* @brief Deinitializes all resources used by the Smartcard interface.
* @param None
* @retval None
*/
static void SC_DeInit(void)
{
/*
Add your deinitialization code here
*/
return;
}
/**
* @brief Configures the card power voltage.
* @param SC_Voltage: specifies the card power voltage.
* This parameter can be one of the following values:
* @arg SC_VOLTAGE_5V: 5V cards.
* @arg SC_VOLTAGE_3V: 3V cards.
* @retval None
*/
void SC_VoltageConfig(uint32_t SC_Voltage)
{
UNUSED(SC_Voltage);
/* Add your code here */
return;
}
/**
* @brief Configures GPIO hardware resources used for Samrtcard.
* @param None
* @retval None
*/
void SC_IOConfig(void)
{
/* Add your code here */
return;
}
/**
* @brief Detects whether the Smartcard is present or not.
* @param None.
* @retval 1 - Smartcard inserted
* 0 - Smartcard not inserted
*/
uint8_t SC_Detect(void)
{
uint8_t PIN_State = 0U;
/* Add your code here */
return PIN_State;
}
/**
* @brief Get the Right Value from the D_Table Index
* @param idx : Index to Read from the Table
* @retval Value read from the Table
*/
uint32_t SC_GetDTableValue(uint32_t idx)
{
return D_Table[idx];
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC\Inc\usbd_cdc.h | /**
******************************************************************************
* @file usbd_cdc.h
* @author MCD Application Team
* @brief header file for the usbd_cdc.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_CDC_H
#define __USB_CDC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_cdc
* @brief This file is the Header file for usbd_cdc.c
* @{
*/
/** @defgroup usbd_cdc_Exported_Defines
* @{
*/
#ifndef CDC_IN_EP
#define CDC_IN_EP 0x81U /* EP1 for data IN */
#endif /* CDC_IN_EP */
#ifndef CDC_OUT_EP
#define CDC_OUT_EP 0x01U /* EP1 for data OUT */
#endif /* CDC_OUT_EP */
#ifndef CDC_CMD_EP
#define CDC_CMD_EP 0x82U /* EP2 for CDC commands */
#endif /* CDC_CMD_EP */
#ifndef CDC_HS_BINTERVAL
#define CDC_HS_BINTERVAL 0x10U
#endif /* CDC_HS_BINTERVAL */
#ifndef CDC_FS_BINTERVAL
#define CDC_FS_BINTERVAL 0x10U
#endif /* CDC_FS_BINTERVAL */
/* CDC Endpoints parameters: you can fine tune these values depending on the needed baudrates and performance. */
#define CDC_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#define CDC_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define CDC_CMD_PACKET_SIZE 8U /* Control Endpoint Packet size */
#define USB_CDC_CONFIG_DESC_SIZ 67U
#define CDC_DATA_HS_IN_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE
#define CDC_DATA_HS_OUT_PACKET_SIZE CDC_DATA_HS_MAX_PACKET_SIZE
#define CDC_DATA_FS_IN_PACKET_SIZE CDC_DATA_FS_MAX_PACKET_SIZE
#define CDC_DATA_FS_OUT_PACKET_SIZE CDC_DATA_FS_MAX_PACKET_SIZE
#define CDC_REQ_MAX_DATA_SIZE 0x7U
/*---------------------------------------------------------------------*/
/* CDC definitions */
/*---------------------------------------------------------------------*/
#define CDC_SEND_ENCAPSULATED_COMMAND 0x00U
#define CDC_GET_ENCAPSULATED_RESPONSE 0x01U
#define CDC_SET_COMM_FEATURE 0x02U
#define CDC_GET_COMM_FEATURE 0x03U
#define CDC_CLEAR_COMM_FEATURE 0x04U
#define CDC_SET_LINE_CODING 0x20U
#define CDC_GET_LINE_CODING 0x21U
#define CDC_SET_CONTROL_LINE_STATE 0x22U
#define CDC_SEND_BREAK 0x23U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct
{
uint32_t bitrate;
uint8_t format;
uint8_t paritytype;
uint8_t datatype;
} USBD_CDC_LineCodingTypeDef;
typedef struct _USBD_CDC_Itf
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control)(uint8_t cmd, uint8_t *pbuf, uint16_t length);
int8_t (* Receive)(uint8_t *Buf, uint32_t *Len);
int8_t (* TransmitCplt)(uint8_t *Buf, uint32_t *Len, uint8_t epnum);
} USBD_CDC_ItfTypeDef;
typedef struct
{
uint32_t data[CDC_DATA_HS_MAX_PACKET_SIZE / 4U]; /* Force 32-bit alignment */
uint8_t CmdOpCode;
uint8_t CmdLength;
uint8_t *RxBuffer;
uint8_t *TxBuffer;
uint32_t RxLength;
uint32_t TxLength;
__IO uint32_t TxState;
__IO uint32_t RxState;
} USBD_CDC_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CDC;
#define USBD_CDC_CLASS &USBD_CDC
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_CDC_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ItfTypeDef *fops);
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff,
uint32_t length, uint8_t ClassId);
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId);
#else
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff,
uint32_t length);
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CDC_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff);
uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_CDC_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC\Inc\usbd_cdc_if_template.h | /**
******************************************************************************
* @file usbd_cdc_if_template.h
* @author MCD Application Team
* @brief Header for usbd_cdc_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_CDC_IF_TEMPLATE_H
#define __USBD_CDC_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
extern USBD_CDC_ItfTypeDef USBD_CDC_Template_fops;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CDC_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC\Src\usbd_cdc.c | /**
******************************************************************************
* @file usbd_cdc.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB CDC Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as CDC Device (and enumeration for each implemented memory interface)
* - OUT/IN data transfer
* - Command IN transfer (class requests management)
* - Error management
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* CDC Class Driver Description
* ===================================================================
* This driver manages the "Universal Serial Bus Class Definitions for Communications Devices
* Revision 1.2 November 16, 2007" and the sub-protocol specification of "Universal Serial Bus
* Communications Class Subclass Specification for PSTN Devices Revision 1.2 February 9, 2007"
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as CDC device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN)
* - Requests management (as described in section 6.2 in specification)
* - Abstract Control Model compliant
* - Union Functional collection (using 1 IN endpoint for control)
* - Data interface class
*
* These aspects may be enriched or modified for a specific user application.
*
* This driver doesn't implement the following aspects of the specification
* (but it is possible to manage these features with some modifications on this driver):
* - Any class-specific aspect relative to communication classes should be managed by user application.
* - All communication classes other than PSTN are not managed
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CDC
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CDC_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CDC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_CDC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_EP0_RxReady(USBD_HandleTypeDef *pdev);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_CDC_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc(uint16_t *length);
uint8_t *USBD_CDC_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
#ifndef USE_USBD_COMPOSITE
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Variables
* @{
*/
/* CDC interface class callbacks structure */
USBD_ClassTypeDef USBD_CDC =
{
USBD_CDC_Init,
USBD_CDC_DeInit,
USBD_CDC_Setup,
NULL, /* EP0_TxSent */
USBD_CDC_EP0_RxReady,
USBD_CDC_DataIn,
USBD_CDC_DataOut,
NULL,
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_CDC_GetHSCfgDesc,
USBD_CDC_GetFSCfgDesc,
USBD_CDC_GetOtherSpeedCfgDesc,
USBD_CDC_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB CDC device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_CfgDesc[USB_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_CDC_CONFIG_DESC_SIZ, /* wTotalLength */
0x00,
0x02, /* bNumInterfaces: 2 interfaces */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/*---------------------------------------------------------------------------*/
/* Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */
/* Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoint used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x02, /* bInterfaceSubClass: Abstract Control Model */
0x01, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header Func Desc */
0x10, /* bcdCDC: spec release number */
0x01,
/* Call Management Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x01, /* bDescriptorSubtype: Call Management Func Desc */
0x00, /* bmCapabilities: D0+D1 */
0x01, /* bDataInterface */
/* ACM Functional Descriptor */
0x04, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x02, /* bDescriptorSubtype: Abstract Control Management desc */
0x02, /* bmCapabilities */
/* Union Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union func desc */
0x00, /* bMasterInterface: Communication class interface */
0x01, /* bSlaveInterface0: Data Class Interface */
/* Endpoint 2 Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_CMD_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_CMD_PACKET_SIZE),
CDC_FS_BINTERVAL, /* bInterval */
/*---------------------------------------------------------------------------*/
/* Data class interface descriptor */
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
0x01, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Endpoint OUT Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
0x00, /* bInterval */
/* Endpoint IN Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
0x00 /* bInterval */
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t CDCInEpAdd = CDC_IN_EP;
static uint8_t CDCOutEpAdd = CDC_OUT_EP;
static uint8_t CDCCmdEpAdd = CDC_CMD_EP;
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Functions
* @{
*/
/**
* @brief USBD_CDC_Init
* Initialize the CDC interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_CDC_HandleTypeDef *hcdc;
hcdc = (USBD_CDC_HandleTypeDef *)USBD_malloc(sizeof(USBD_CDC_HandleTypeDef));
if (hcdc == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
(void)USBD_memset(hcdc, 0, sizeof(USBD_CDC_HandleTypeDef));
pdev->pClassDataCmsit[pdev->classId] = (void *)hcdc;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CDCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CDCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CDCCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CDCInEpAdd, USBD_EP_TYPE_BULK,
CDC_DATA_HS_IN_PACKET_SIZE);
pdev->ep_in[CDCInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CDCOutEpAdd, USBD_EP_TYPE_BULK,
CDC_DATA_HS_OUT_PACKET_SIZE);
pdev->ep_out[CDCOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CDC CMD Endpoint */
pdev->ep_in[CDCCmdEpAdd & 0xFU].bInterval = CDC_HS_BINTERVAL;
}
else
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CDCInEpAdd, USBD_EP_TYPE_BULK,
CDC_DATA_FS_IN_PACKET_SIZE);
pdev->ep_in[CDCInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CDCOutEpAdd, USBD_EP_TYPE_BULK,
CDC_DATA_FS_OUT_PACKET_SIZE);
pdev->ep_out[CDCOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CMD Endpoint */
pdev->ep_in[CDCCmdEpAdd & 0xFU].bInterval = CDC_FS_BINTERVAL;
}
/* Open Command IN EP */
(void)USBD_LL_OpenEP(pdev, CDCCmdEpAdd, USBD_EP_TYPE_INTR, CDC_CMD_PACKET_SIZE);
pdev->ep_in[CDCCmdEpAdd & 0xFU].is_used = 1U;
hcdc->RxBuffer = NULL;
/* Init physical Interface components */
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
/* Init Xfer states */
hcdc->TxState = 0U;
hcdc->RxState = 0U;
if (hcdc->RxBuffer == NULL)
{
return (uint8_t)USBD_EMEM;
}
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDCOutEpAdd, hcdc->RxBuffer,
CDC_DATA_HS_OUT_PACKET_SIZE);
}
else
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDCOutEpAdd, hcdc->RxBuffer,
CDC_DATA_FS_OUT_PACKET_SIZE);
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_Init
* DeInitialize the CDC layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this CDC class instance */
CDCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CDCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
CDCCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, CDCInEpAdd);
pdev->ep_in[CDCInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, CDCOutEpAdd);
pdev->ep_out[CDCOutEpAdd & 0xFU].is_used = 0U;
/* Close Command IN EP */
(void)USBD_LL_CloseEP(pdev, CDCCmdEpAdd);
pdev->ep_in[CDCCmdEpAdd & 0xFU].is_used = 0U;
pdev->ep_in[CDCCmdEpAdd & 0xFU].bInterval = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_Setup
* Handle the CDC specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CDC_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len;
uint8_t ifalt = 0U;
uint16_t status_info = 0U;
USBD_StatusTypeDef ret = USBD_OK;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
if (req->wLength != 0U)
{
if ((req->bmRequest & 0x80U) != 0U)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(req->bRequest,
(uint8_t *)hcdc->data,
req->wLength);
len = MIN(CDC_REQ_MAX_DATA_SIZE, req->wLength);
(void)USBD_CtlSendData(pdev, (uint8_t *)hcdc->data, len);
}
else
{
hcdc->CmdOpCode = req->bRequest;
hcdc->CmdLength = (uint8_t)MIN(req->wLength, USB_MAX_EP0_SIZE);
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)hcdc->data, hcdc->CmdLength);
}
}
else
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(req->bRequest,
(uint8_t *)req, 0U);
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, &ifalt, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_HandleTypeDef *hcdc;
PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if ((pdev->ep_in[epnum & 0xFU].total_length > 0U) &&
((pdev->ep_in[epnum & 0xFU].total_length % hpcd->IN_ep[epnum & 0xFU].maxpacket) == 0U))
{
/* Update the packet total length */
pdev->ep_in[epnum & 0xFU].total_length = 0U;
/* Send ZLP */
(void)USBD_LL_Transmit(pdev, epnum, NULL, 0U);
}
else
{
hcdc->TxState = 0U;
if (((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt != NULL)
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt(hcdc->TxBuffer, &hcdc->TxLength, epnum);
}
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Get the received data length */
hcdc->RxLength = USBD_LL_GetRxDataSize(pdev, epnum);
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application Xfer */
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->Receive(hcdc->RxBuffer, &hcdc->RxLength);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_EP0_RxReady
* Handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_CDC_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((pdev->pUserData[pdev->classId] != NULL) && (hcdc->CmdOpCode != 0xFFU))
{
((USBD_CDC_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(hcdc->CmdOpCode,
(uint8_t *)hcdc->data,
(uint16_t)hcdc->CmdLength);
hcdc->CmdOpCode = 0xFFU;
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_CDC_GetFSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t)sizeof(USBD_CDC_CfgDesc);
return USBD_CDC_CfgDesc;
}
/**
* @brief USBD_CDC_GetHSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_HS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_DATA_HS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_DATA_HS_MAX_PACKET_SIZE;
}
*length = (uint16_t)sizeof(USBD_CDC_CfgDesc);
return USBD_CDC_CfgDesc;
}
/**
* @brief USBD_CDC_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_CfgDesc, CDC_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t)sizeof(USBD_CDC_CfgDesc);
return USBD_CDC_CfgDesc;
}
/**
* @brief USBD_CDC_GetDeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CDC_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_DeviceQualifierDesc);
return USBD_CDC_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CDC_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_CDC_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_SetTxBuffer
* @param pdev: device instance
* @param pbuff: Tx Buffer
* @param length: length of data to be sent
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev,
uint8_t *pbuff, uint32_t length, uint8_t ClassId)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_SetTxBuffer(USBD_HandleTypeDef *pdev,
uint8_t *pbuff, uint32_t length)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->TxBuffer = pbuff;
hcdc->TxLength = length;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_SetRxBuffer
* @param pdev: device instance
* @param pbuff: Rx Buffer
* @retval status
*/
uint8_t USBD_CDC_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->RxBuffer = pbuff;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_TransmitPacket
* Transmit packet on IN endpoint
* @param pdev: device instance
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_TransmitPacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
USBD_StatusTypeDef ret = USBD_BUSY;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CDCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, ClassId);
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (hcdc->TxState == 0U)
{
/* Tx Transfer in progress */
hcdc->TxState = 1U;
/* Update the packet total length */
pdev->ep_in[CDCInEpAdd & 0xFU].total_length = hcdc->TxLength;
/* Transmit next packet */
(void)USBD_LL_Transmit(pdev, CDCInEpAdd, hcdc->TxBuffer, hcdc->TxLength);
ret = USBD_OK;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CDC_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CDCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDCOutEpAdd, hcdc->RxBuffer,
CDC_DATA_HS_OUT_PACKET_SIZE);
}
else
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, CDCOutEpAdd, hcdc->RxBuffer,
CDC_DATA_FS_OUT_PACKET_SIZE);
}
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC\Src\usbd_cdc_if_template.c | /**
******************************************************************************
* @file usbd_cdc_if_template.c
* @author MCD Application Team
* @brief Generic media access Layer.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_if_template.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CDC
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CDC_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_Private_FunctionPrototypes
* @{
*/
static int8_t TEMPLATE_Init(void);
static int8_t TEMPLATE_DeInit(void);
static int8_t TEMPLATE_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length);
static int8_t TEMPLATE_Receive(uint8_t *pbuf, uint32_t *Len);
static int8_t TEMPLATE_TransmitCplt(uint8_t *pbuf, uint32_t *Len, uint8_t epnum);
USBD_CDC_ItfTypeDef USBD_CDC_Template_fops =
{
TEMPLATE_Init,
TEMPLATE_DeInit,
TEMPLATE_Control,
TEMPLATE_Receive,
TEMPLATE_TransmitCplt
};
USBD_CDC_LineCodingTypeDef linecoding =
{
115200, /* baud rate*/
0x00, /* stop bits-1*/
0x00, /* parity - none*/
0x08 /* nb. of bits 8*/
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief TEMPLATE_Init
* Initializes the CDC media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Init(void)
{
/*
Add your initialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_DeInit
* DeInitializes the CDC media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_DeInit(void)
{
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_Control
* Manage the CDC class requests
* @param Cmd: Command code
* @param Buf: Buffer containing command data (request parameters)
* @param Len: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length)
{
UNUSED(length);
switch (cmd)
{
case CDC_SEND_ENCAPSULATED_COMMAND:
/* Add your code here */
break;
case CDC_GET_ENCAPSULATED_RESPONSE:
/* Add your code here */
break;
case CDC_SET_COMM_FEATURE:
/* Add your code here */
break;
case CDC_GET_COMM_FEATURE:
/* Add your code here */
break;
case CDC_CLEAR_COMM_FEATURE:
/* Add your code here */
break;
case CDC_SET_LINE_CODING:
linecoding.bitrate = (uint32_t)(pbuf[0] | (pbuf[1] << 8) | \
(pbuf[2] << 16) | (pbuf[3] << 24));
linecoding.format = pbuf[4];
linecoding.paritytype = pbuf[5];
linecoding.datatype = pbuf[6];
/* Add your code here */
break;
case CDC_GET_LINE_CODING:
pbuf[0] = (uint8_t)(linecoding.bitrate);
pbuf[1] = (uint8_t)(linecoding.bitrate >> 8);
pbuf[2] = (uint8_t)(linecoding.bitrate >> 16);
pbuf[3] = (uint8_t)(linecoding.bitrate >> 24);
pbuf[4] = linecoding.format;
pbuf[5] = linecoding.paritytype;
pbuf[6] = linecoding.datatype;
/* Add your code here */
break;
case CDC_SET_CONTROL_LINE_STATE:
/* Add your code here */
break;
case CDC_SEND_BREAK:
/* Add your code here */
break;
default:
break;
}
return (0);
}
/**
* @brief TEMPLATE_Receive
* Data received over USB OUT endpoint are sent over CDC interface
* through this function.
*
* @note
* This function will issue a NAK packet on any OUT packet received on
* USB endpoint until exiting this function. If you exit this function
* before transfer is complete on CDC interface (ie. using DMA controller)
* it will result in receiving more data while previous ones are still
* not sent.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Receive(uint8_t *Buf, uint32_t *Len)
{
UNUSED(Buf);
UNUSED(Len);
return (0);
}
/**
* @brief TEMPLATE_TransmitCplt
* Data transmitted callback
*
* @note
* This function is IN transfer complete callback used to inform user that
* the submitted Data is successfully sent over USB.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_TransmitCplt(uint8_t *Buf, uint32_t *Len, uint8_t epnum)
{
UNUSED(Buf);
UNUSED(Len);
UNUSED(epnum);
return (0);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM\Inc\usbd_cdc_ecm.h | /**
******************************************************************************
* @file usbd_cdc_ecm.h
* @author MCD Application Team
* @brief header file for the usbd_cdc_ecm.c file.
******************************************************************************
* @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 __USB_CDC_ECM_H
#define __USB_CDC_ECM_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_cdc_ecm
* @brief This file is the Header file for usbd_cdc_ecm.c
* @{
*/
/** @defgroup usbd_cdc_ecm_Exported_Defines
* @{
*/
/* Comment this define in order to disable the CDC ECM Notification pipe */
#ifndef CDC_ECM_IN_EP
#define CDC_ECM_IN_EP 0x81U /* EP1 for data IN */
#endif /* CDC_ECM_IN_EP */
#ifndef CDC_ECM_OUT_EP
#define CDC_ECM_OUT_EP 0x01U /* EP1 for data OUT */
#endif /* CDC_ECM_OUT_EP */
#ifndef CDC_ECM_CMD_EP
#define CDC_ECM_CMD_EP 0x82U /* EP2 for CDC ECM commands */
#endif /* CDC_ECM_CMD_EP */
#ifndef CDC_ECM_CMD_ITF_NBR
#define CDC_ECM_CMD_ITF_NBR 0x00U /* Command Interface Number 0 */
#endif /* CDC_ECM_CMD_ITF_NBR */
#ifndef CDC_ECM_COM_ITF_NBR
#define CDC_ECM_COM_ITF_NBR 0x01U /* Communication Interface Number 0 */
#endif /* CDC_ECM_CMD_ITF_NBR */
#ifndef CDC_ECM_HS_BINTERVAL
#define CDC_ECM_HS_BINTERVAL 0x10U
#endif /* CDC_ECM_HS_BINTERVAL */
#ifndef CDC_ECM_FS_BINTERVAL
#define CDC_ECM_FS_BINTERVAL 0x10U
#endif /* CDC_ECM_FS_BINTERVAL */
#ifndef USBD_SUPPORT_USER_STRING_DESC
#define USBD_SUPPORT_USER_STRING_DESC 1U
#endif /* USBD_SUPPORT_USER_STRING_DESC */
/* CDC_ECM Endpoints parameters: you can fine tune these values depending on the needed baudrates and performance. */
#define CDC_ECM_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#define CDC_ECM_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define CDC_ECM_CMD_PACKET_SIZE 16U /* Control Endpoint Packet size */
#define CDC_ECM_CONFIG_DESC_SIZ 79U
#define CDC_ECM_DATA_BUFFER_SIZE 2000U
#define CDC_ECM_DATA_HS_IN_PACKET_SIZE CDC_ECM_DATA_HS_MAX_PACKET_SIZE
#define CDC_ECM_DATA_HS_OUT_PACKET_SIZE CDC_ECM_DATA_HS_MAX_PACKET_SIZE
#define CDC_ECM_DATA_FS_IN_PACKET_SIZE CDC_ECM_DATA_FS_MAX_PACKET_SIZE
#define CDC_ECM_DATA_FS_OUT_PACKET_SIZE CDC_ECM_DATA_FS_MAX_PACKET_SIZE
/*---------------------------------------------------------------------*/
/* CDC_ECM definitions */
/*---------------------------------------------------------------------*/
#define CDC_ECM_SEND_ENCAPSULATED_COMMAND 0x00U
#define CDC_ECM_GET_ENCAPSULATED_RESPONSE 0x01U
#define CDC_ECM_SET_ETH_MULTICAST_FILTERS 0x40U
#define CDC_ECM_SET_ETH_PWRM_PATTERN_FILTER 0x41U
#define CDC_ECM_GET_ETH_PWRM_PATTERN_FILTER 0x42U
#define CDC_ECM_SET_ETH_PACKET_FILTER 0x43U
#define CDC_ECM_GET_ETH_STATISTIC 0x44U
#define CDC_ECM_NET_DISCONNECTED 0x00U
#define CDC_ECM_NET_CONNECTED 0x01U
/* Ethernet statistics definitions */
#define CDC_ECM_XMIT_OK_VAL CDC_ECM_ETH_STATS_VAL_ENABLED
#define CDC_ECM_XMIT_OK 0x01U
#define CDC_ECM_RVC_OK 0x02U
#define CDC_ECM_XMIT_ERROR 0x04U
#define CDC_ECM_RCV_ERROR 0x08U
#define CDC_ECM_RCV_NO_BUFFER 0x10U
#define CDC_ECM_DIRECTED_BYTES_XMIT 0x20U
#define CDC_ECM_DIRECTED_FRAMES_XMIT 0x40U
#define CDC_ECM_MULTICAST_BYTES_XMIT 0x80U
#define CDC_ECM_MULTICAST_FRAMES_XMIT 0x01U
#define CDC_ECM_BROADCAST_BYTES_XMIT 0x02U
#define CDC_ECM_BROADCAST_FRAMES_XMIT 0x04U
#define CDC_ECM_DIRECTED_BYTES_RCV 0x08U
#define CDC_ECM_DIRECTED_FRAMES_RCV 0x10U
#define CDC_ECM_MULTICAST_BYTES_RCV 0x20U
#define CDC_ECM_MULTICAST_FRAMES_RCV 0x40U
#define CDC_ECM_BROADCAST_BYTES_RCV 0x80U
#define CDC_ECM_BROADCAST_FRAMES_RCV 0x01U
#define CDC_ECM_RCV_CRC_ERROR 0x02U
#define CDC_ECM_TRANSMIT_QUEUE_LENGTH 0x04U
#define CDC_ECM_RCV_ERROR_ALIGNMENT 0x08U
#define CDC_ECM_XMIT_ONE_COLLISION 0x10U
#define CDC_ECM_XMIT_MORE_COLLISIONS 0x20U
#define CDC_ECM_XMIT_DEFERRED 0x40U
#define CDC_ECM_XMIT_MAX_COLLISIONS 0x80U
#define CDC_ECM_RCV_OVERRUN 0x40U
#define CDC_ECM_XMIT_UNDERRUN 0x40U
#define CDC_ECM_XMIT_HEARTBEAT_FAILURE 0x40U
#define CDC_ECM_XMIT_TIMES_CRS_LOST 0x40U
#define CDC_ECM_XMIT_LATE_COLLISIONS 0x40U
#define CDC_ECM_ETH_STATS_RESERVED 0xE0U
#define CDC_ECM_BMREQUEST_TYPE_ECM 0xA1U
/* MAC String index */
#define CDC_ECM_MAC_STRING_INDEX 6U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control)(uint8_t cmd, uint8_t *pbuf, uint16_t length);
int8_t (* Receive)(uint8_t *Buf, uint32_t *Len);
int8_t (* TransmitCplt)(uint8_t *Buf, uint32_t *Len, uint8_t epnum);
int8_t (* Process)(USBD_HandleTypeDef *pdev);
const uint8_t *pStrDesc;
} USBD_CDC_ECM_ItfTypeDef;
typedef struct
{
uint8_t bmRequest;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
uint8_t data[8];
} USBD_CDC_ECM_NotifTypeDef;
/*
* ECM Class specification revision 1.2
* Table 3: Ethernet Networking Functional Descriptor
*/
typedef struct
{
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t iMacAddress;
uint8_t bEthernetStatistics3;
uint8_t bEthernetStatistics2;
uint8_t bEthernetStatistics1;
uint8_t bEthernetStatistics0;
uint16_t wMaxSegmentSize;
uint16_t bNumberMCFiltes;
uint8_t bNumberPowerFiltes;
} __PACKED USBD_ECMFuncDescTypeDef;
typedef struct
{
uint32_t data[CDC_ECM_DATA_BUFFER_SIZE / 4U]; /* Force 32-bit alignment */
uint8_t CmdOpCode;
uint8_t CmdLength;
uint8_t Reserved1; /* Reserved Byte to force 4 bytes alignment of following fields */
uint8_t Reserved2; /* Reserved Byte to force 4 bytes alignment of following fields */
uint8_t *RxBuffer;
uint8_t *TxBuffer;
uint32_t RxLength;
uint32_t TxLength;
__IO uint32_t TxState;
__IO uint32_t RxState;
__IO uint32_t MaxPcktLen;
__IO uint32_t LinkStatus;
__IO uint32_t NotificationStatus;
USBD_CDC_ECM_NotifTypeDef Req;
} USBD_CDC_ECM_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CDC_ECM;
#define USBD_CDC_ECM_CLASS &USBD_CDC_ECM
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_CDC_ECM_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ECM_ItfTypeDef *fops);
uint8_t USBD_CDC_ECM_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff);
uint8_t USBD_CDC_ECM_ReceivePacket(USBD_HandleTypeDef *pdev);
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_ECM_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId);
uint8_t USBD_CDC_ECM_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff,
uint32_t length, uint8_t ClassId);
#else
uint8_t USBD_CDC_ECM_TransmitPacket(USBD_HandleTypeDef *pdev);
uint8_t USBD_CDC_ECM_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff,
uint32_t length);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CDC_ECM_SendNotification(USBD_HandleTypeDef *pdev,
USBD_CDC_NotifCodeTypeDef Notif,
uint16_t bVal, uint8_t *pData);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_CDC_ECM_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM\Inc\usbd_cdc_ecm_if_template.h | /**
******************************************************************************
* @file Inc/usbd_cdc_ecm_if_template.h
* @author MCD Application Team
* @brief Header for usbd_cdc_ecm_if_template.c file.
******************************************************************************
* @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 __USBD_CDC_ECM_IF_H
#define __USBD_CDC_ECM_IF_H
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_ecm.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Ensure this MAC address value is same as MAC_ADDRx declared in STM32xxx_conf.h */
#define CDC_ECM_MAC_STR_DESC (uint8_t *)"000202030000"
#define CDC_ECM_MAC_ADDR0 0x00U /* 01 */
#define CDC_ECM_MAC_ADDR1 0x02U /* 02 */
#define CDC_ECM_MAC_ADDR2 0x02U /* 03 */
#define CDC_ECM_MAC_ADDR3 0x03U /* 00 */
#define CDC_ECM_MAC_ADDR4 0x00U /* 00 */
#define CDC_ECM_MAC_ADDR5 0x00U /* 00 */
/* Max Number of Trials waiting for Tx ready */
#define CDC_ECM_MAX_TX_WAIT_TRIALS 1000000U
#define CDC_ECM_ETH_STATS_BYTE0 0U
/*(uint8_t)(CDC_ECM_XMIT_OK_VAL | CDC_ECM_RVC_OK_VAL | CDC_ECM_XMIT_ERROR_VAL | \
CDC_ECM_RCV_ERROR_VAL | CDC_ECM_RCV_NO_BUFFER_VAL | CDC_ECM_DIRECTED_BYTES_XMIT_VAL | \
CDC_ECM_DIRECTED_FRAMES_XMIT_VAL | CDC_ECM_MULTICAST_BYTES_XMIT_VAL) */
#define CDC_ECM_ETH_STATS_BYTE1 0U
/*(uint8_t)(CDC_ECM_MULTICAST_FRAMES_XMIT_VAL | CDC_ECM_BROADCAST_BYTES_XMIT_VAL | \
CDC_ECM_BROADCAST_FRAMES_XMIT_VAL | CDC_ECM_DIRECTED_BYTES_RCV_VAL | \
CDC_ECM_DIRECTED_FRAMES_RCV_VAL | CDC_ECM_MULTICAST_BYTES_RCV_VAL | \
CDC_ECM_MULTICAST_FRAMES_RCV_VAL | CDC_ECM_BROADCAST_BYTES_RCV_VAL) */
#define CDC_ECM_ETH_STATS_BYTE2 0U
/*(uint8_t)(CDC_ECM_BROADCAST_FRAMES_RCV_VAL | CDC_ECM_RCV_CRC_ERROR_VAL | \
CDC_ECM_TRANSMIT_QUEUE_LENGTH_VAL | CDC_ECM_RCV_ERROR_ALIGNMENT_VAL | \
CDC_ECM_XMIT_ONE_COLLISION_VAL | CDC_ECM_XMIT_MORE_COLLISIONS_VAL | \
CDC_ECM_XMIT_DEFERRED_VAL | CDC_ECM_XMIT_MAX_COLLISIONS_VAL) */
#define CDC_ECM_ETH_STATS_BYTE3 0U
/*(uint8_t)(CDC_ECM_RCV_OVERRUN_VAL | CDC_ECM_XMIT_UNDERRUN_VAL | CDC_ECM_XMIT_HEARTBEAT_FAILURE_VAL | \
CDC_ECM_XMIT_TIMES_CRS_LOST_VAL | CDC_ECM_XMIT_LATE_COLLISIONS_VAL | CDC_ECM_ETH_STATS_RESERVED) */
/* Ethernet Maximum Segment size, typically 1514 bytes */
#define CDC_ECM_ETH_MAX_SEGSZE 1514U
/* Number of Ethernet multicast filters */
#define CDC_ECM_ETH_NBR_MACFILTERS 0U
/* Number of wakeup power filters */
#define CDC_ECM_ETH_NBR_PWRFILTERS 0U
#define CDC_ECM_CONNECT_SPEED_UPSTREAM 0x004C4B40U /* 5Mbps */
#define CDC_ECM_CONNECT_SPEED_DOWNSTREAM 0x004C4B40U /* 5Mbps */
extern USBD_CDC_ECM_ItfTypeDef USBD_CDC_ECM_fops;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#endif /* __USBD_CDC_ECM_IF_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM\Src\usbd_cdc_ecm.c | /**
******************************************************************************
* @file usbd_cdc_ecm.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB CDC_ECM Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as CDC_ECM Device (and enumeration for each implemented memory interface)
* - OUT/IN data transfer
* - Command IN transfer (class requests management)
* - Error 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.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_ecm.h"
#include "usbd_ctlreq.h"
#ifndef __USBD_CDC_ECM_IF_H
#include "usbd_cdc_ecm_if_template.h"
#endif /* __USBD_CDC_ECM_IF_H */
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CDC_ECM
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CDC_ECM_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_ECM_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_ECM_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_ECM_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CDC_ECM_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_ECM_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_ECM_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_ECM_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_ECM_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_CDC_ECM_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_CDC_ECM_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_ECM_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_ECM_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_ECM_GetOtherSpeedCfgDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_CDC_ECM_USRStringDescriptor(USBD_HandleTypeDef *pdev,
uint8_t index, uint16_t *length);
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#ifndef USE_USBD_COMPOSITE
uint8_t *USBD_CDC_ECM_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
#ifndef USE_USBD_COMPOSITE
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_ECM_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint32_t ConnSpeedTab[2] = {CDC_ECM_CONNECT_SPEED_UPSTREAM,
CDC_ECM_CONNECT_SPEED_DOWNSTREAM
};
/**
* @}
*/
/** @defgroup USBD_CDC_ECM_Private_Variables
* @{
*/
/* CDC_ECM interface class callbacks structure */
USBD_ClassTypeDef USBD_CDC_ECM =
{
USBD_CDC_ECM_Init,
USBD_CDC_ECM_DeInit,
USBD_CDC_ECM_Setup,
NULL, /* EP0_TxSent, */
USBD_CDC_ECM_EP0_RxReady,
USBD_CDC_ECM_DataIn,
USBD_CDC_ECM_DataOut,
NULL,
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_CDC_ECM_GetHSCfgDesc,
USBD_CDC_ECM_GetFSCfgDesc,
USBD_CDC_ECM_GetOtherSpeedCfgDesc,
USBD_CDC_ECM_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
USBD_CDC_ECM_USRStringDescriptor,
#endif /* USBD_SUPPORT_USER_STRING_DESC */
};
#ifndef USE_USBD_COMPOSITE
/* USB CDC_ECM device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_ECM_CfgDesc[] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
LOBYTE(CDC_ECM_CONFIG_DESC_SIZ), /* wTotalLength: Total size of the Config descriptor */
HIBYTE(CDC_ECM_CONFIG_DESC_SIZ),
0x02, /* bNumInterfaces: 2 interfaces */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/*---------------------------------------------------------------------------*/
/* IAD descriptor */
0x08, /* bLength */
0x0B, /* bDescriptorType */
0x00, /* bFirstInterface */
0x02, /* bInterfaceCount */
0x02, /* bFunctionClass (Wireless Controller) */
0x06, /* bFunctionSubClass */
0x00, /* bFunctionProtocol */
0x00, /* iFunction */
/* Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
CDC_ECM_CMD_ITF_NBR, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoint used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x06, /* bInterfaceSubClass: Ethernet Control Model */
0x00, /* bInterfaceProtocol: No specific protocol required */
0x00, /* iInterface */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header functional descriptor */
0x10, /* bcd CDC_ECM : spec release number: 1.20 */
0x01,
/* Union Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union functional descriptor */
CDC_ECM_CMD_ITF_NBR, /* bMasterInterface: Communication class interface */
CDC_ECM_COM_ITF_NBR, /* bSlaveInterface0: Data Class Interface */
/* CDC_ECM Functional Descriptor */
0x0D, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x0F, /* Ethernet Networking functional descriptor subtype */
CDC_ECM_MAC_STRING_INDEX, /* Device's MAC string index */
CDC_ECM_ETH_STATS_BYTE3, /* Ethernet statistics byte 3 (bitmap) */
CDC_ECM_ETH_STATS_BYTE2, /* Ethernet statistics byte 2 (bitmap) */
CDC_ECM_ETH_STATS_BYTE1, /* Ethernet statistics byte 1 (bitmap) */
CDC_ECM_ETH_STATS_BYTE0, /* Ethernet statistics byte 0 (bitmap) */
LOBYTE(CDC_ECM_ETH_MAX_SEGSZE),
HIBYTE(CDC_ECM_ETH_MAX_SEGSZE), /* wMaxSegmentSize: Ethernet Maximum Segment size, typically 1514 bytes */
LOBYTE(CDC_ECM_ETH_NBR_MACFILTERS),
HIBYTE(CDC_ECM_ETH_NBR_MACFILTERS), /* wNumberMCFilters: the number of multicast filters */
CDC_ECM_ETH_NBR_PWRFILTERS, /* bNumberPowerFilters: the number of wakeup power filters */
/* Communication Endpoint Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_ECM_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_ECM_CMD_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_ECM_CMD_PACKET_SIZE),
CDC_ECM_FS_BINTERVAL, /* bInterval */
/*----------------------*/
/* Data class interface descriptor */
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
CDC_ECM_COM_ITF_NBR, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC_ECM */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Endpoint OUT Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_ECM_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_ECM_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_ECM_DATA_FS_MAX_PACKET_SIZE),
0x00, /* bInterval */
/* Endpoint IN Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_ECM_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_ECM_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_ECM_DATA_FS_MAX_PACKET_SIZE),
0x00 /* bInterval */
} ;
#endif /* USE_USBD_COMPOSITE */
static uint8_t ECMInEpAdd = CDC_ECM_IN_EP;
static uint8_t ECMOutEpAdd = CDC_ECM_OUT_EP;
static uint8_t ECMCmdEpAdd = CDC_ECM_CMD_EP;
/**
* @}
*/
/** @defgroup USBD_CDC_ECM_Private_Functions
* @{
*/
/**
* @brief USBD_CDC_ECM_Init
* Initialize the CDC_ECM interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_ECM_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_CDC_ECM_HandleTypeDef *hcdc;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
ECMOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
ECMCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
hcdc = (USBD_CDC_ECM_HandleTypeDef *)USBD_malloc(sizeof(USBD_CDC_ECM_HandleTypeDef));
if (hcdc == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
(void)USBD_memset(hcdc, 0, sizeof(USBD_CDC_ECM_HandleTypeDef));
pdev->pClassDataCmsit[pdev->classId] = (void *)hcdc;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, ECMInEpAdd, USBD_EP_TYPE_BULK,
CDC_ECM_DATA_HS_IN_PACKET_SIZE);
pdev->ep_in[ECMInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, ECMOutEpAdd, USBD_EP_TYPE_BULK,
CDC_ECM_DATA_HS_OUT_PACKET_SIZE);
pdev->ep_out[ECMOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CDC ECM CMD Endpoint */
pdev->ep_in[ECMCmdEpAdd & 0xFU].bInterval = CDC_ECM_HS_BINTERVAL;
}
else
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, ECMInEpAdd, USBD_EP_TYPE_BULK,
CDC_ECM_DATA_FS_IN_PACKET_SIZE);
pdev->ep_in[ECMInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, ECMOutEpAdd, USBD_EP_TYPE_BULK,
CDC_ECM_DATA_FS_OUT_PACKET_SIZE);
pdev->ep_out[ECMOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CDC ECM CMD Endpoint */
pdev->ep_in[ECMCmdEpAdd & 0xFU].bInterval = CDC_ECM_FS_BINTERVAL;
}
/* Open Command IN EP */
(void)USBD_LL_OpenEP(pdev, ECMCmdEpAdd, USBD_EP_TYPE_INTR, CDC_ECM_CMD_PACKET_SIZE);
pdev->ep_in[ECMCmdEpAdd & 0xFU].is_used = 1U;
hcdc->RxBuffer = NULL;
/* Init physical Interface components */
((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
/* Init Xfer states */
hcdc->TxState = 0U;
hcdc->RxState = 0U;
hcdc->RxLength = 0U;
hcdc->TxLength = 0U;
hcdc->LinkStatus = 0U;
hcdc->NotificationStatus = 0U;
hcdc->MaxPcktLen = (pdev->dev_speed == USBD_SPEED_HIGH) ? CDC_ECM_DATA_HS_MAX_PACKET_SIZE : \
CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
if (hcdc->RxBuffer == NULL)
{
return (uint8_t)USBD_EMEM;
}
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, ECMOutEpAdd, hcdc->RxBuffer, hcdc->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_DeInit
* DeInitialize the CDC_ECM layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_ECM_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
ECMOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
ECMCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, ECMInEpAdd);
pdev->ep_in[ECMInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, ECMOutEpAdd);
pdev->ep_out[ECMOutEpAdd & 0xFU].is_used = 0U;
/* Close Command IN EP */
(void)USBD_LL_CloseEP(pdev, ECMCmdEpAdd);
pdev->ep_in[ECMCmdEpAdd & 0xFU].is_used = 0U;
pdev->ep_in[ECMCmdEpAdd & 0xFU].bInterval = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_Setup
* Handle the CDC_ECM specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CDC_ECM_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
USBD_CDC_ECM_ItfTypeDef *EcmInterface = (USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint16_t len;
uint16_t status_info = 0U;
uint8_t ifalt = 0U;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS :
if (req->wLength != 0U)
{
if ((req->bmRequest & 0x80U) != 0U)
{
EcmInterface->Control(req->bRequest, (uint8_t *)hcdc->data, req->wLength);
len = MIN(CDC_ECM_DATA_BUFFER_SIZE, req->wLength);
(void)USBD_CtlSendData(pdev, (uint8_t *)hcdc->data, len);
}
else
{
hcdc->CmdOpCode = req->bRequest;
hcdc->CmdLength = (uint8_t)MIN(req->wLength, USB_MAX_EP0_SIZE);
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)hcdc->data, hcdc->CmdLength);
}
}
else
{
EcmInterface->Control(req->bRequest, (uint8_t *)req, 0U);
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, &ifalt, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_ECM_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_ECM_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (epnum == (ECMInEpAdd & 0x7FU))
{
if ((pdev->ep_in[epnum & 0xFU].total_length > 0U) &&
((pdev->ep_in[epnum & 0xFU].total_length % hpcd->IN_ep[epnum & 0xFU].maxpacket) == 0U))
{
/* Update the packet total length */
pdev->ep_in[epnum & 0xFU].total_length = 0U;
/* Send ZLP */
(void)USBD_LL_Transmit(pdev, epnum, NULL, 0U);
}
else
{
hcdc->TxState = 0U;
if (((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt != NULL)
{
((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt(hcdc->TxBuffer,
&hcdc->TxLength, epnum);
}
}
}
else if (epnum == (ECMCmdEpAdd & 0x7FU))
{
if (hcdc->NotificationStatus != 0U)
{
(void)USBD_CDC_ECM_SendNotification(pdev, CONNECTION_SPEED_CHANGE, 0U, (uint8_t *)ConnSpeedTab);
hcdc->NotificationStatus = 0U;
}
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_ECM_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t CurrPcktLen;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (epnum == ECMOutEpAdd)
{
/* Get the received data length */
CurrPcktLen = USBD_LL_GetRxDataSize(pdev, epnum);
/* Increment the frame length */
hcdc->RxLength += CurrPcktLen;
/* If the buffer size is less than max packet size: it is the last packet in current frame */
if ((CurrPcktLen < hcdc->MaxPcktLen) || (hcdc->RxLength >= CDC_ECM_ETH_MAX_SEGSZE))
{
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application Xfer */
/* Process data by application (ie. copy to app buffer or notify user)
hcdc->RxLength must be reset to zero at the end of the call of this function */
((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->Receive(hcdc->RxBuffer, &hcdc->RxLength);
}
else
{
/* Prepare Out endpoint to receive next packet in current/new frame */
(void)USBD_LL_PrepareReceive(pdev, ECMOutEpAdd,
(uint8_t *)(hcdc->RxBuffer + hcdc->RxLength),
hcdc->MaxPcktLen);
}
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_EP0_RxReady
* Handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_CDC_ECM_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((pdev->pUserData[pdev->classId] != NULL) && (hcdc->CmdOpCode != 0xFFU))
{
((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(hcdc->CmdOpCode,
(uint8_t *)hcdc->data,
(uint16_t)hcdc->CmdLength);
hcdc->CmdOpCode = 0xFFU;
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_CDC_ECM_GetFSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_ECM_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_ECM_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_CDC_ECM_CfgDesc);
return USBD_CDC_ECM_CfgDesc;
}
/**
* @brief USBD_CDC_ECM_GetHSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_ECM_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_ECM_HS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_ECM_DATA_HS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_ECM_DATA_HS_MAX_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_CDC_ECM_CfgDesc);
return USBD_CDC_ECM_CfgDesc;
}
/**
* @brief USBD_CDC_ECM_GetCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_ECM_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_ECM_CfgDesc, CDC_ECM_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_ECM_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_CDC_ECM_CfgDesc);
return USBD_CDC_ECM_CfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CDC_ECM_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CDC_ECM_DeviceQualifierDesc);
return USBD_CDC_ECM_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CDC_ECM_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_CDC_ECM_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_ECM_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_USRStringDescriptor
* Manages the transfer of user string descriptors.
* @param pdev: device instance
* @param index: descriptor index
* @param length : pointer data length
* @retval pointer to the descriptor table or NULL if the descriptor is not supported.
*/
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_CDC_ECM_USRStringDescriptor(USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length)
{
static uint8_t USBD_StrDesc[255];
/* Check if the requested string interface is supported */
if (index == CDC_ECM_MAC_STRING_INDEX)
{
USBD_GetString((uint8_t *)((USBD_CDC_ECM_ItfTypeDef *)pdev->pUserData[pdev->classId])->pStrDesc,
USBD_StrDesc,
length);
return USBD_StrDesc;
}
/* Not supported Interface Descriptor index */
else
{
return NULL;
}
}
#endif /* USBD_SUPPORT_USER_STRING_DESC */
/**
* @brief USBD_CDC_ECM_SetTxBuffer
* @param pdev: device instance
* @param pbuff: Tx Buffer
* @param length: Tx Buffer length
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_ECM_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff, uint32_t length, uint8_t ClassId)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_ECM_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff, uint32_t length)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->TxBuffer = pbuff;
hcdc->TxLength = length;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_SetRxBuffer
* @param pdev: device instance
* @param pbuff: Rx Buffer
* @retval status
*/
uint8_t USBD_CDC_ECM_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->RxBuffer = pbuff;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_TransmitPacket
* Transmit packet on IN endpoint
* @param pdev: device instance
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_ECM_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_ECM_TransmitPacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
USBD_StatusTypeDef ret = USBD_BUSY;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, ClassId);
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (hcdc->TxState == 0U)
{
/* Tx Transfer in progress */
hcdc->TxState = 1U;
/* Update the packet total length */
pdev->ep_in[ECMInEpAdd & 0xFU].total_length = hcdc->TxLength;
/* Transmit next packet */
(void)USBD_LL_Transmit(pdev, ECMInEpAdd, hcdc->TxBuffer, hcdc->TxLength);
ret = USBD_OK;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_ECM_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CDC_ECM_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, ECMOutEpAdd, hcdc->RxBuffer, hcdc->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_ECM_SendNotification
* Transmit Notification packet on CMD IN interrupt endpoint
* @param pdev: device instance
* Notif: value of the notification type (from CDC_ECM_Notification_TypeDef enumeration list)
* bVal: value of the notification switch (ie. 0x00 or 0x01 for Network Connection notification)
* pData: pointer to data buffer (ie. upstream and downstream connection speed values)
* @retval status
*/
uint8_t USBD_CDC_ECM_SendNotification(USBD_HandleTypeDef *pdev,
USBD_CDC_NotifCodeTypeDef Notif,
uint16_t bVal, uint8_t *pData)
{
uint32_t Idx;
uint32_t ReqSize = 0U;
USBD_CDC_ECM_HandleTypeDef *hcdc = (USBD_CDC_ECM_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
ECMCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Initialize the request fields */
(hcdc->Req).bmRequest = CDC_ECM_BMREQUEST_TYPE_ECM;
(hcdc->Req).bRequest = (uint8_t)Notif;
switch ((hcdc->Req).bRequest)
{
case NETWORK_CONNECTION:
(hcdc->Req).wValue = bVal;
(hcdc->Req).wIndex = CDC_ECM_CMD_ITF_NBR;
(hcdc->Req).wLength = 0U;
for (Idx = 0U; Idx < 8U; Idx++)
{
(hcdc->Req).data[Idx] = 0U;
}
ReqSize = 8U;
break;
case RESPONSE_AVAILABLE:
(hcdc->Req).wValue = 0U;
(hcdc->Req).wIndex = CDC_ECM_CMD_ITF_NBR;
(hcdc->Req).wLength = 0U;
for (Idx = 0U; Idx < 8U; Idx++)
{
(hcdc->Req).data[Idx] = 0U;
}
ReqSize = 8U;
break;
case CONNECTION_SPEED_CHANGE:
(hcdc->Req).wValue = 0U;
(hcdc->Req).wIndex = CDC_ECM_CMD_ITF_NBR;
(hcdc->Req).wLength = 0x0008U;
ReqSize = 16U;
/* Check pointer to data buffer */
if (pData != NULL)
{
for (Idx = 0U; Idx < 8U; Idx++)
{
(hcdc->Req).data[Idx] = pData[Idx];
}
}
break;
default:
ret = USBD_FAIL;
break;
}
/* Transmit notification packet */
if (ReqSize != 0U)
{
(void)USBD_LL_Transmit(pdev, ECMCmdEpAdd, (uint8_t *)&hcdc->Req, ReqSize);
}
return (uint8_t)ret;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_ECM\Src\usbd_cdc_ecm_if_template.c | /**
******************************************************************************
* @file Src/usbd_cdc_ecm_if_template.c
* @author MCD Application Team
* @brief Source file for USBD CDC_ECM interface
******************************************************************************
* @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 "usbd_cdc_ecm_if_template.h"
/*
Include here LwIP files if used
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Received Data over USB are stored in this buffer */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* ( __ICCARM__ ) */
__ALIGN_BEGIN static uint8_t UserRxBuffer[CDC_ECM_ETH_MAX_SEGSZE + 100]__ALIGN_END;
/* Transmitted Data over CDC_ECM (CDC_ECM interface) are stored in this buffer */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* ( __ICCARM__ ) */
__ALIGN_BEGIN static uint8_t UserTxBuffer[CDC_ECM_ETH_MAX_SEGSZE + 100]__ALIGN_END;
static uint8_t CDC_ECMInitialized = 0U;
/* USB handler declaration */
extern USBD_HandleTypeDef USBD_Device;
/* Private function prototypes -----------------------------------------------*/
static int8_t CDC_ECM_Itf_Init(void);
static int8_t CDC_ECM_Itf_DeInit(void);
static int8_t CDC_ECM_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length);
static int8_t CDC_ECM_Itf_Receive(uint8_t *pbuf, uint32_t *Len);
static int8_t CDC_ECM_Itf_TransmitCplt(uint8_t *pbuf, uint32_t *Len, uint8_t epnum);
static int8_t CDC_ECM_Itf_Process(USBD_HandleTypeDef *pdev);
USBD_CDC_ECM_ItfTypeDef USBD_CDC_ECM_fops =
{
CDC_ECM_Itf_Init,
CDC_ECM_Itf_DeInit,
CDC_ECM_Itf_Control,
CDC_ECM_Itf_Receive,
CDC_ECM_Itf_TransmitCplt,
CDC_ECM_Itf_Process,
(uint8_t *)CDC_ECM_MAC_STR_DESC,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief CDC_ECM_Itf_Init
* Initializes the CDC_ECM media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_Init(void)
{
if (CDC_ECMInitialized == 0U)
{
/*
Initialize the TCP/IP stack here
*/
CDC_ECMInitialized = 1U;
}
/* Set Application Buffers */
#ifdef USE_USBD_COMPOSITE
(void)USBD_CDC_ECM_SetTxBuffer(&USBD_Device, UserTxBuffer, 0U, 0U);
#else
(void)USBD_CDC_ECM_SetTxBuffer(&USBD_Device, UserTxBuffer, 0U);
#endif /* USE_USBD_COMPOSITE */
(void)USBD_CDC_ECM_SetRxBuffer(&USBD_Device, UserRxBuffer);
return (0);
}
/**
* @brief CDC_ECM_Itf_DeInit
* DeInitializes the CDC_ECM media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_DeInit(void)
{
#ifdef USE_USBD_COMPOSITE
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
/* Notify application layer that link is down */
hcdc_cdc_ecm->LinkStatus = 0U;
return (0);
}
/**
* @brief CDC_ECM_Itf_Control
* Manage the CDC_ECM class requests
* @param Cmd: Command code
* @param Buf: Buffer containing command data (request parameters)
* @param Len: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length)
{
#ifdef USE_USBD_COMPOSITE
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
switch (cmd)
{
case CDC_ECM_SEND_ENCAPSULATED_COMMAND:
/* Add your code here */
break;
case CDC_ECM_GET_ENCAPSULATED_RESPONSE:
/* Add your code here */
break;
case CDC_ECM_SET_ETH_MULTICAST_FILTERS:
/* Add your code here */
break;
case CDC_ECM_SET_ETH_PWRM_PATTERN_FILTER:
/* Add your code here */
break;
case CDC_ECM_GET_ETH_PWRM_PATTERN_FILTER:
/* Add your code here */
break;
case CDC_ECM_SET_ETH_PACKET_FILTER:
/* Check if this is the first time we enter */
if (hcdc_cdc_ecm->LinkStatus == 0U)
{
/*
Setup the Link up at TCP/IP level
*/
hcdc_cdc_ecm->LinkStatus = 1U;
/* Modification for MacOS which doesn't send SetInterface before receiving INs */
if (hcdc_cdc_ecm->NotificationStatus == 0U)
{
/* Send notification: NETWORK_CONNECTION Event */
(void)USBD_CDC_ECM_SendNotification(&USBD_Device, NETWORK_CONNECTION,
CDC_ECM_NET_CONNECTED, NULL);
/* Prepare for sending Connection Speed Change notification */
hcdc_cdc_ecm->NotificationStatus = 1U;
}
}
/* Add your code here */
break;
case CDC_ECM_GET_ETH_STATISTIC:
/* Add your code here */
break;
default:
break;
}
UNUSED(length);
UNUSED(pbuf);
return (0);
}
/**
* @brief CDC_ECM_Itf_Receive
* Data received over USB OUT endpoint are sent over CDC_ECM interface
* through this function.
* @param Buf: Buffer of data to be transmitted
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_Receive(uint8_t *Buf, uint32_t *Len)
{
/* Get the CDC_ECM handler pointer */
#ifdef USE_USBD_COMPOSITE
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
/* Call Eth buffer processing */
hcdc_cdc_ecm->RxState = 1U;
UNUSED(Len);
UNUSED(Buf);
return (0);
}
/**
* @brief CDC_ECM_Itf_TransmitCplt
* Data transmitted callback
*
* @note
* This function is IN transfer complete callback used to inform user that
* the submitted Data is successfully sent over USB.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_TransmitCplt(uint8_t *Buf, uint32_t *Len, uint8_t epnum)
{
UNUSED(Buf);
UNUSED(Len);
UNUSED(epnum);
return (0);
}
/**
* @brief CDC_ECM_Itf_Process
* Data received over USB OUT endpoint are sent over CDC_ECM interface
* through this function.
* @param pdef: pointer to the USB Device Handle
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_ECM_Itf_Process(USBD_HandleTypeDef *pdev)
{
/* Get the CDC_ECM handler pointer */
#ifdef USE_USBD_COMPOSITE
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *)(pdev->pClassDataCmsit[pdev->classId]);
#else
USBD_CDC_ECM_HandleTypeDef *hcdc_cdc_ecm = (USBD_CDC_ECM_HandleTypeDef *)(pdev->pClassData);
#endif /* USE_USBD_COMPOSITE */
if (hcdc_cdc_ecm == NULL)
{
return (-1);
}
if (hcdc_cdc_ecm->LinkStatus != 0U)
{
/*
Read a received packet from the Ethernet buffers and send it
to the lwIP for handling
Call here the TCP/IP background tasks.
*/
}
return (0);
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS\Inc\usbd_cdc_rndis.h | /**
******************************************************************************
* @file usbd_cdc_rndis.h
* @author MCD Application Team
* @brief header file for the usbd_cdc_rndis.c file.
******************************************************************************
* @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 __USB_CDC_RNDIS_H
#define __USB_CDC_RNDIS_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_cdc_rndis
* @brief This file is the Header file for usbd_cdc_rndis.c
* @{
*/
/** @defgroup usbd_cdc_rndis_Exported_Defines
* @{
*/
#ifndef CDC_RNDIS_IN_EP
#define CDC_RNDIS_IN_EP 0x81U /* EP1 for data IN */
#endif /* CDC_RNDIS_IN_EP */
#ifndef CDC_RNDIS_OUT_EP
#define CDC_RNDIS_OUT_EP 0x01U /* EP1 for data OUT */
#endif /* CDC_RNDIS_OUT_EP */
#ifndef CDC_RNDIS_CMD_EP
#define CDC_RNDIS_CMD_EP 0x82U /* EP2 for CDC_RNDIS commands */
#endif /* CDC_RNDIS_CMD_EP */
#ifndef CDC_RNDIS_CMD_ITF_NBR
#define CDC_RNDIS_CMD_ITF_NBR 0x00U /* Command Interface Number 0 */
#endif /* CDC_RNDIS_CMD_ITF_NBR */
#ifndef CDC_RNDIS_COM_ITF_NBR
#define CDC_RNDIS_COM_ITF_NBR 0x01U /* Communication Interface Number 0 */
#endif /* CDC_RNDIS_CMD_ITF_NBR */
#ifndef CDC_RNDIS_HS_BINTERVAL
#define CDC_RNDIS_HS_BINTERVAL 0x10U
#endif /* CDC_RNDIS_HS_BINTERVAL */
#ifndef CDC_RNDIS_FS_BINTERVAL
#define CDC_RNDIS_FS_BINTERVAL 0x10U
#endif /* CDC_RNDIS_FS_BINTERVAL */
/* CDC_RNDIS Endpoints parameters: you can fine tune these values
depending on the needed baudrates and performance. */
#define CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#define CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define CDC_RNDIS_CMD_PACKET_SIZE 16U /* Control Endpoint Packet size */
#define CDC_RNDIS_CONFIG_DESC_SIZ 75U
#define CDC_RNDIS_DATA_HS_IN_PACKET_SIZE CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE
#define CDC_RNDIS_DATA_HS_OUT_PACKET_SIZE CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE
#define CDC_RNDIS_DATA_FS_IN_PACKET_SIZE CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE
#define CDC_RNDIS_DATA_FS_OUT_PACKET_SIZE CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE
/*---------------------------------------------------------------------*/
/* CDC_RNDIS definitions */
/*---------------------------------------------------------------------*/
/** Implemented CDC_RNDIS Version Major */
#define CDC_RNDIS_VERSION_MAJOR 0x01U
/* Implemented CDC_RNDIS Version Minor */
#define CDC_RNDIS_VERSION_MINOR 0x00U
/* Maximum size in bytes of a CDC_RNDIS control message
which can be sent or received */
#define CDC_RNDIS_MESSAGE_BUFFER_SIZE 128U
/* Maximum size in bytes of an Ethernet frame
according to the Ethernet standard */
#define CDC_RNDIS_ETH_FRAME_SIZE_MAX 1536U
/* Maximum size allocated for buffer
inside Query messages structures */
#define CDC_RNDIS_MAX_INFO_BUFF_SZ 200U
#define CDC_RNDIS_MAX_DATA_SZE 2000U
/* Notification request value for a CDC_RNDIS
Response Available notification */
#define CDC_RNDIS_NOTIFICATION_RESP_AVAILABLE 0x00000001UL
#define CDC_RNDIS_PACKET_MSG_ID 0x00000001UL
#define CDC_RNDIS_INITIALIZE_MSG_ID 0x00000002UL
#define CDC_RNDIS_HALT_MSG_ID 0x00000003UL
#define CDC_RNDIS_QUERY_MSG_ID 0x00000004UL
#define CDC_RNDIS_SET_MSG_ID 0x00000005UL
#define CDC_RNDIS_RESET_MSG_ID 0x00000006UL
#define CDC_RNDIS_INDICATE_STATUS_MSG_ID 0x00000007UL
#define CDC_RNDIS_KEEPALIVE_MSG_ID 0x00000008UL
#define CDC_RNDIS_INITIALIZE_CMPLT_ID 0x80000002UL
#define CDC_RNDIS_QUERY_CMPLT_ID 0x80000004UL
#define CDC_RNDIS_SET_CMPLT_ID 0x80000005UL
#define CDC_RNDIS_RESET_CMPLT_ID 0x80000006UL
#define CDC_RNDIS_KEEPALIVE_CMPLT_ID 0x80000008UL
#define CDC_RNDIS_STATUS_SUCCESS 0x00000000UL
#define CDC_RNDIS_STATUS_FAILURE 0xC0000001UL
#define CDC_RNDIS_STATUS_INVALID_DATA 0xC0010015UL
#define CDC_RNDIS_STATUS_NOT_SUPPORTED 0xC00000BBUL
#define CDC_RNDIS_STATUS_MEDIA_CONNECT 0x4001000BUL
#define CDC_RNDIS_STATUS_MEDIA_DISCONNECT 0x4001000CUL
/** Media state */
#define CDC_RNDIS_MEDIA_STATE_CONNECTED 0x00000000UL
#define CDC_RNDIS_MEDIA_STATE_DISCONNECTED 0x00000001UL
/** Media types */
#define CDC_RNDIS_MEDIUM_802_3 0x00000000UL
#define CDC_RNDIS_DF_CONNECTIONLESS 0x00000001UL
#define CDC_RNDIS_DF_CONNECTION_ORIENTED 0x00000002UL
/** Hardware status of the underlying NIC */
#define CDC_RNDIS_HW_STS_READY 0x00000000UL
#define CDC_RNDIS_HW_STS_INITIALIZING 0x00000001UL
#define CDC_RNDIS_HW_STS_RESET 0x00000002UL
#define CDC_RNDIS_HW_STS_CLOSING 0x00000003UL
#define CDC_RNDIS_HW_STS_NOT_READY 0x00000004UL
/** Packet filter */
#define CDC_RNDIS_PACKET_DIRECTED 0x00000001UL
#define CDC_RNDIS_PACKET_MULTICAST 0x00000002UL
#define CDC_RNDIS_PACKET_ALL_MULTICAST 0x00000004UL
#define CDC_RNDIS_PACKET_BROADCAST 0x00000008UL
#define CDC_RNDIS_PACKET_SOURCE_ROUTING 0x00000010UL
#define CDC_RNDIS_PACKET_PROMISCUOUS 0x00000020UL
#define CDC_RNDIS_PACKET_SMT 0x00000040UL
#define CDC_RNDIS_PACKET_ALL_LOCAL 0x00000080UL
#define CDC_RNDIS_PACKET_GROUP 0x00001000UL
#define CDC_RNDIS_PACKET_ALL_FUNCTIONAL 0x00002000UL
#define CDC_RNDIS_PACKET_FUNCTIONAL 0x00004000UL
#define CDC_RNDIS_PACKET_MAC_FRAME 0x00008000UL
#define OID_GEN_SUPPORTED_LIST 0x00010101UL
#define OID_GEN_HARDWARE_STATUS 0x00010102UL
#define OID_GEN_MEDIA_SUPPORTED 0x00010103UL
#define OID_GEN_MEDIA_IN_USE 0x00010104UL
#define OID_GEN_MAXIMUM_FRAME_SIZE 0x00010106UL
#define OID_GEN_MAXIMUM_TOTAL_SIZE 0x00010111UL
#define OID_GEN_LINK_SPEED 0x00010107UL
#define OID_GEN_TRANSMIT_BLOCK_SIZE 0x0001010AUL
#define OID_GEN_RECEIVE_BLOCK_SIZE 0x0001010BUL
#define OID_GEN_VENDOR_ID 0x0001010CUL
#define OID_GEN_VENDOR_DESCRIPTION 0x0001010DUL
#define OID_GEN_CURRENT_PACKET_FILTER 0x0001010EUL
#define OID_GEN_MEDIA_CONNECT_STATUS 0x00010114UL
#define OID_GEN_MAXIMUM_SEND_PACKETS 0x00010115UL
#define OID_GEN_PHYSICAL_MEDIUM 0x00010202UL
#define OID_GEN_XMIT_OK 0x00020101UL
#define OID_GEN_RCV_OK 0x00020102UL
#define OID_GEN_XMIT_ERROR 0x00020103UL
#define OID_GEN_RCV_ERROR 0x00020104UL
#define OID_GEN_RCV_NO_BUFFER 0x00020105UL
#define OID_GEN_CDC_RNDIS_CONFIG_PARAMETER 0x0001021BUL
#define OID_802_3_PERMANENT_ADDRESS 0x01010101UL
#define OID_802_3_CURRENT_ADDRESS 0x01010102UL
#define OID_802_3_MULTICAST_LIST 0x01010103UL
#define OID_802_3_MAXIMUM_LIST_SIZE 0x01010104UL
#define OID_802_3_RCV_ERROR_ALIGNMENT 0x01020101UL
#define OID_802_3_XMIT_ONE_COLLISION 0x01020102UL
#define OID_802_3_XMIT_MORE_COLLISIONS 0x01020103UL
#define CDC_RNDIS_SEND_ENCAPSULATED_COMMAND 0x00U
#define CDC_RNDIS_GET_ENCAPSULATED_RESPONSE 0x01U
#define CDC_RNDIS_NET_DISCONNECTED 0x00U
#define CDC_RNDIS_NET_CONNECTED 0x01U
#define CDC_RNDIS_BMREQUEST_TYPE_RNDIS 0xA1U
#define CDC_RNDIS_PCKTMSG_DATAOFFSET_OFFSET 8U
/* MAC String index */
#define CDC_RNDIS_MAC_STRING_INDEX 6U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct _USBD_CDC_RNDIS_Itf
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control)(uint8_t cmd, uint8_t *pbuf, uint16_t length);
int8_t (* Receive)(uint8_t *Buf, uint32_t *Len);
int8_t (* TransmitCplt)(uint8_t *Buf, uint32_t *Len, uint8_t epnum);
int8_t (* Process)(USBD_HandleTypeDef *pdev);
uint8_t *pStrDesc;
} USBD_CDC_RNDIS_ItfTypeDef;
/* CDC_RNDIS State values */
typedef enum
{
CDC_RNDIS_STATE_UNINITIALIZED = 0,
CDC_RNDIS_STATE_BUS_INITIALIZED = 1,
CDC_RNDIS_STATE_INITIALIZED = 2,
CDC_RNDIS_STATE_DATA_INITIALIZED = 3
} USBD_CDC_RNDIS_StateTypeDef;
typedef struct
{
uint8_t bmRequest;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
uint8_t data[8];
} USBD_CDC_RNDIS_NotifTypeDef;
typedef struct
{
uint32_t data[CDC_RNDIS_MAX_DATA_SZE / 4U]; /* Force 32-bit alignment */
uint8_t CmdOpCode;
uint8_t CmdLength;
uint8_t ResponseRdy; /* Indicates if the Device Response to an CDC_RNDIS msg is ready */
uint8_t Reserved1; /* Reserved Byte to force 4 bytes alignment of following fields */
uint8_t *RxBuffer;
uint8_t *TxBuffer;
uint32_t RxLength;
uint32_t TxLength;
USBD_CDC_RNDIS_NotifTypeDef Req;
USBD_CDC_RNDIS_StateTypeDef State;
__IO uint32_t TxState;
__IO uint32_t RxState;
__IO uint32_t MaxPcktLen;
__IO uint32_t LinkStatus;
__IO uint32_t NotificationStatus;
__IO uint32_t PacketFilter;
} USBD_CDC_RNDIS_HandleTypeDef;
/* Messages Sent by the Host ---------------------*/
/* Type define for a CDC_RNDIS Initialize command message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t MajorVersion;
uint32_t MinorVersion;
uint32_t MaxTransferSize;
} USBD_CDC_RNDIS_InitMsgTypeDef;
/* Type define for a CDC_RNDIS Halt Message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
} USBD_CDC_RNDIS_HaltMsgTypeDef;
/* Type define for a CDC_RNDIS Query command message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t RequestId;
uint32_t Oid;
uint32_t InfoBufLength;
uint32_t InfoBufOffset;
uint32_t DeviceVcHandle;
uint32_t InfoBuf[CDC_RNDIS_MAX_INFO_BUFF_SZ];
} USBD_CDC_RNDIS_QueryMsgTypeDef;
/* Type define for a CDC_RNDIS Set command message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Oid;
uint32_t InfoBufLength;
uint32_t InfoBufOffset;
uint32_t DeviceVcHandle;
uint32_t InfoBuf[CDC_RNDIS_MAX_INFO_BUFF_SZ];
} USBD_CDC_RNDIS_SetMsgTypeDef;
/* Type define for a CDC_RNDIS Reset message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t Reserved;
} USBD_CDC_RNDIS_ResetMsgTypeDef;
/* Type define for a CDC_RNDIS Keepalive command message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
} USBD_CDC_RNDIS_KpAliveMsgTypeDef;
/* Messages Sent by the Device ---------------------*/
/* Type define for a CDC_RNDIS Initialize complete response message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Status;
uint32_t MajorVersion;
uint32_t MinorVersion;
uint32_t DeviceFlags;
uint32_t Medium;
uint32_t MaxPacketsPerTransfer;
uint32_t MaxTransferSize;
uint32_t PacketAlignmentFactor;
uint32_t AFListOffset;
uint32_t AFListSize;
} USBD_CDC_RNDIS_InitCpltMsgTypeDef;
/* Type define for a CDC_RNDIS Query complete response message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Status;
uint32_t InfoBufLength;
uint32_t InfoBufOffset;
uint32_t InfoBuf[CDC_RNDIS_MAX_INFO_BUFF_SZ];
} USBD_CDC_RNDIS_QueryCpltMsgTypeDef;
/* Type define for a CDC_RNDIS Set complete response message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Status;
} USBD_CDC_RNDIS_SetCpltMsgTypeDef;
/* Type define for a CDC_RNDIS Reset complete message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t Status;
uint32_t AddrReset;
} USBD_CDC_RNDIS_ResetCpltMsgTypeDef;
/* Type define for CDC_RNDIS struct to indicate a change
in the status of the device */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t Status;
uint32_t StsBufLength;
uint32_t StsBufOffset;
} USBD_CDC_RNDIS_StsChangeMsgTypeDef;
/* Type define for a CDC_RNDIS Keepalive complete message */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Status;
} USBD_CDC_RNDIS_KpAliveCpltMsgTypeDef;
/* Messages Sent by both Host and Device ---------------------*/
/* Type define for a CDC_RNDIS packet message, used to encapsulate
Ethernet packets sent to and from the adapter */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t DataOffset;
uint32_t DataLength;
uint32_t OOBDataOffset;
uint32_t OOBDataLength;
uint32_t NumOOBDataElements;
uint32_t PerPacketInfoOffset;
uint32_t PerPacketInfoLength;
uint32_t VcHandle;
uint32_t Reserved;
} USBD_CDC_RNDIS_PacketMsgTypeDef;
/* Miscellaneous types used for parsing ---------------------*/
/* The common part for all CDC_RNDIS messages Complete response */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
uint32_t ReqId;
uint32_t Status;
} USBD_CDC_RNDIS_CommonCpltMsgTypeDef;
/* Type define for a single parameter structure */
typedef struct
{
uint32_t ParamNameOffset;
uint32_t ParamNameLength;
uint32_t ParamType;
uint32_t ParamValueOffset;
uint32_t ParamValueLength;
} USBD_CDC_RNDIS_ParamStructTypeDef;
/* Type define of a single CDC_RNDIS OOB data record */
typedef struct
{
uint32_t Size;
uint32_t Type;
uint32_t ClassInfoType;
uint32_t OOBData[sizeof(uint32_t)];
} USBD_CDC_RNDIS_OOBPacketTypeDef;
/* Type define for notification structure */
typedef struct
{
uint32_t notification;
uint32_t reserved;
} USBD_CDC_RNDIS_NotifStructTypeDef;
/* This structure will be used to store the type, the size and ID for any
received message from the control endpoint */
typedef struct
{
uint32_t MsgType;
uint32_t MsgLength;
} USBD_CDC_RNDIS_CtrlMsgTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CDC_RNDIS;
#define USBD_CDC_RNDIS_CLASS &USBD_CDC_RNDIS
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_CDC_RNDIS_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff);
uint8_t USBD_CDC_RNDIS_ReceivePacket(USBD_HandleTypeDef *pdev);
uint8_t USBD_CDC_RNDIS_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_ItfTypeDef *fops);
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_RNDIS_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId);
uint8_t USBD_CDC_RNDIS_SetTxBuffer(USBD_HandleTypeDef *pdev,
uint8_t *pbuff, uint32_t length, uint8_t ClassId);
#else
uint8_t USBD_CDC_RNDIS_TransmitPacket(USBD_HandleTypeDef *pdev);
uint8_t USBD_CDC_RNDIS_SetTxBuffer(USBD_HandleTypeDef *pdev,
uint8_t *pbuff, uint32_t length);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CDC_RNDIS_SendNotification(USBD_HandleTypeDef *pdev,
USBD_CDC_NotifCodeTypeDef Notif,
uint16_t bVal, uint8_t *pData);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_CDC_RNDIS_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS\Inc\usbd_cdc_rndis_if_template.h | /**
******************************************************************************
* @file usbd_cdc_rndis_if_template.h
* @author MCD Application Team
* @brief Header for usbd_cdc_rndis_if.c file.
******************************************************************************
* @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 __USBD_CDC_RNDIS_IF_H
#define __USBD_CDC_RNDIS_IF_H
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_rndis.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Ensure this MAC address value is same as MAC_ADDRx declared in STM32xxx_conf.h */
#define CDC_RNDIS_MAC_STR_DESC (uint8_t *)"000202030000"
#define CDC_RNDIS_MAC_ADDR0 0x00U /* 01 */
#define CDC_RNDIS_MAC_ADDR1 0x02U /* 02 */
#define CDC_RNDIS_MAC_ADDR2 0x02U /* 03 */
#define CDC_RNDIS_MAC_ADDR3 0x03U /* 00 */
#define CDC_RNDIS_MAC_ADDR4 0x00U /* 00 */
#define CDC_RNDIS_MAC_ADDR5 0x00U /* 00 */
#define USBD_CDC_RNDIS_VENDOR_DESC "STMicroelectronics"
#define USBD_CDC_RNDIS_LINK_SPEED 100000U /* 10Mbps */
#define USBD_CDC_RNDIS_VID 0x0483U
/* Max Number of Trials waiting for Tx ready */
#define CDC_RNDIS_MAX_TX_WAIT_TRIALS 1000000U
/* Ethernet Maximum Segment size, typically 1514 bytes */
#define CDC_RNDIS_ETH_MAX_SEGSZE 1514U
#define CDC_RNDIS_CONNECT_SPEED_UPSTREAM 0x1E000000U
#define CDC_RNDIS_CONNECT_SPEED_DOWNSTREAM 0x1E000000U
extern USBD_CDC_RNDIS_ItfTypeDef USBD_CDC_RNDIS_fops;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#endif /* __USBD_CDC_RNDIS_IF_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS\Src\usbd_cdc_rndis.c | /**
******************************************************************************
* @file usbd_cdc_rndis.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB CDC_RNDIS Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as CDC_RNDIS Device (and enumeration for each implemented memory interface)
* - OUT/IN data transfer
* - Command IN transfer (class requests management)
* - Error 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
*
* ===================================================================
* CDC_RNDIS Class Driver Description
* ===================================================================
* This driver manages the "Universal Serial Bus Class Definitions for Communications Devices
* Revision 1.2 November 16, 2007" and the sub-protocol specification of "Universal Serial Bus
* Communications Class Subclass Specification for PSTN Devices Revision 1.2 February 9, 2007"
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as CDC device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN)
* - Requests management (as described in section 6.2 in specification)
* - Abstract Control Model compliant
* - Union Functional collection (using 1 IN endpoint for control)
* - Data interface class
*
* These aspects may be enriched or modified for a specific user application.
*
* This driver doesn't implement the following aspects of the specification
* (but it is possible to manage these features with some modifications on this driver):
* - Any class-specific aspect relative to communication classes should be managed by user application.
* - All communication classes other than PSTN are not managed
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc_rndis.h"
#include "usbd_ctlreq.h"
#ifndef __USBD_CDC_RNDIS_IF_H
#include "usbd_cdc_rndis_if_template.h"
#endif /* __USBD_CDC_RNDIS_IF_H */
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CDC_RNDIS
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CDC_RNDIS_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_RNDIS_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_RNDIS_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CDC_RNDIS_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CDC_RNDIS_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_RNDIS_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CDC_RNDIS_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req);
static uint8_t USBD_CDC_RNDIS_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_RNDIS_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CDC_RNDIS_EP0_RxReady(USBD_HandleTypeDef *pdev);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_CDC_RNDIS_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_RNDIS_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_RNDIS_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_CDC_RNDIS_GetOtherSpeedCfgDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_CDC_RNDIS_USRStringDescriptor(USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length);
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#ifndef USE_USBD_COMPOSITE
uint8_t *USBD_CDC_RNDIS_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/* CDC_RNDIS Internal messages parsing and construction functions */
static uint8_t USBD_CDC_RNDIS_MsgParsing(USBD_HandleTypeDef *pdev, uint8_t *RxBuff);
static uint8_t USBD_CDC_RNDIS_ProcessInitMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_InitMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessHaltMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_HaltMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessKeepAliveMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_KpAliveMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessQueryMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_QueryMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessSetMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_SetMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessResetMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_ResetMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessPacketMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_PacketMsgTypeDef *Msg);
static uint8_t USBD_CDC_RNDIS_ProcessUnsupportedMsg(USBD_HandleTypeDef *pdev, USBD_CDC_RNDIS_CtrlMsgTypeDef *Msg);
/* USB Standard Device Descriptor */
#ifndef USE_USBD_COMPOSITE
__ALIGN_BEGIN static uint8_t USBD_CDC_RNDIS_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t MAC_StrDesc[6] = {CDC_RNDIS_MAC_ADDR0, CDC_RNDIS_MAC_ADDR1, CDC_RNDIS_MAC_ADDR2,
CDC_RNDIS_MAC_ADDR3, CDC_RNDIS_MAC_ADDR4, CDC_RNDIS_MAC_ADDR5
};
static uint32_t ConnSpeedTab[2] = {CDC_RNDIS_CONNECT_SPEED_UPSTREAM,
CDC_RNDIS_CONNECT_SPEED_DOWNSTREAM
};
static uint8_t EmptyResponse = 0x00U;
/**
* @}
*/
/** @defgroup USBD_CDC_RNDIS_Private_Variables
* @{
*/
/* CDC_RNDIS interface class callbacks structure */
USBD_ClassTypeDef USBD_CDC_RNDIS =
{
USBD_CDC_RNDIS_Init,
USBD_CDC_RNDIS_DeInit,
USBD_CDC_RNDIS_Setup,
NULL, /* EP0_TxSent, */
USBD_CDC_RNDIS_EP0_RxReady,
USBD_CDC_RNDIS_DataIn,
USBD_CDC_RNDIS_DataOut,
NULL,
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_CDC_RNDIS_GetHSCfgDesc,
USBD_CDC_RNDIS_GetFSCfgDesc,
USBD_CDC_RNDIS_GetOtherSpeedCfgDesc,
USBD_CDC_RNDIS_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
USBD_CDC_RNDIS_USRStringDescriptor,
#endif /* USBD_SUPPORT_USER_STRING_DESC */
};
#ifndef USE_USBD_COMPOSITE
/* USB CDC device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CDC_RNDIS_CfgDesc[] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
LOBYTE(CDC_RNDIS_CONFIG_DESC_SIZ), /* wTotalLength: Total size of the Config descriptor */
HIBYTE(CDC_RNDIS_CONFIG_DESC_SIZ),
0x02, /* bNumInterfaces: 2 interfaces */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/*---------------------------------------------------------------------------*/
/* IAD descriptor */
0x08, /* bLength */
0x0B, /* bDescriptorType */
0x00, /* bFirstInterface */
0x02, /* bInterfaceCount */
0xE0, /* bFunctionClass (Wireless Controller) */
0x01, /* bFunctionSubClass */
0x03, /* bFunctionProtocol */
0x00, /* iFunction */
/*---------------------------------------------------------------------------*/
/* Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
CDC_RNDIS_CMD_ITF_NBR, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoint used */
0x02, /* bInterfaceClass: Communication Interface Class */
0x02, /* bInterfaceSubClass:Abstract Control Model */
0xFF, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface */
/* Header Functional Descriptor */
0x05, /* bLength: Endpoint Descriptor size */
0x24, /* bDescriptorType: CS_INTERFACE */
0x00, /* bDescriptorSubtype: Header functional descriptor */
0x10, /* bcdCDC: spec release number: 1.20 */
0x01,
/* Call Management Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x01, /* bDescriptorSubtype: Call Management Func Desc */
0x00, /* bmCapabilities: D0+D1 */
CDC_RNDIS_COM_ITF_NBR, /* bDataInterface: 1 */
/* ACM Functional Descriptor */
0x04, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x02, /* bDescriptorSubtype: Abstract Control Management desc */
0x00, /* bmCapabilities */
/* Union Functional Descriptor */
0x05, /* bFunctionLength */
0x24, /* bDescriptorType: CS_INTERFACE */
0x06, /* bDescriptorSubtype: Union functional descriptor */
CDC_RNDIS_CMD_ITF_NBR, /* bMasterInterface: Communication class interface */
CDC_RNDIS_COM_ITF_NBR, /* bSlaveInterface0: Data Class Interface */
/* Notification Endpoint Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_RNDIS_CMD_EP, /* bEndpointAddress */
0x03, /* bmAttributes: Interrupt */
LOBYTE(CDC_RNDIS_CMD_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_RNDIS_CMD_PACKET_SIZE),
CDC_RNDIS_FS_BINTERVAL, /* bInterval */
/*---------------------------------------------------------------------------*/
/* Data class interface descriptor */
0x09, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: */
CDC_RNDIS_COM_ITF_NBR, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: Two endpoints used */
0x0A, /* bInterfaceClass: CDC */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Endpoint OUT Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_RNDIS_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize: */
HIBYTE(CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE),
0x00, /* bInterval */
/* Endpoint IN Descriptor */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
CDC_RNDIS_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE),
0x00 /* bInterval */
} ;
#endif /* USE_USBD_COMPOSITE */
static uint8_t RNDISInEpAdd = CDC_RNDIS_IN_EP;
static uint8_t RNDISOutEpAdd = CDC_RNDIS_OUT_EP;
static uint8_t RNDISCmdEpAdd = CDC_RNDIS_CMD_EP;
static const uint32_t CDC_RNDIS_SupportedOIDs[] =
{
OID_GEN_SUPPORTED_LIST,
OID_GEN_HARDWARE_STATUS,
OID_GEN_MEDIA_SUPPORTED,
OID_GEN_MEDIA_IN_USE,
OID_GEN_MAXIMUM_FRAME_SIZE,
OID_GEN_LINK_SPEED,
OID_GEN_TRANSMIT_BLOCK_SIZE,
OID_GEN_RECEIVE_BLOCK_SIZE,
OID_GEN_VENDOR_ID,
OID_GEN_VENDOR_DESCRIPTION,
OID_GEN_CURRENT_PACKET_FILTER,
OID_GEN_MAXIMUM_TOTAL_SIZE,
OID_GEN_MEDIA_CONNECT_STATUS,
OID_GEN_MAXIMUM_SEND_PACKETS,
OID_802_3_PERMANENT_ADDRESS,
OID_802_3_CURRENT_ADDRESS,
OID_802_3_MULTICAST_LIST,
OID_802_3_MAXIMUM_LIST_SIZE,
OID_802_3_RCV_ERROR_ALIGNMENT,
OID_802_3_XMIT_ONE_COLLISION,
OID_802_3_XMIT_MORE_COLLISIONS,
};
/**
* @}
*/
/** @defgroup USBD_CDC_RNDIS_Private_Functions
* @{
*/
/**
* @brief USBD_CDC_RNDIS_Init
* Initialize the CDC CDC_RNDIS interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_CDC_RNDIS_HandleTypeDef *hcdc;
hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)USBD_malloc(sizeof(USBD_CDC_RNDIS_HandleTypeDef));
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
RNDISOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
RNDISCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
(void)USBD_memset(hcdc, 0, sizeof(USBD_CDC_RNDIS_HandleTypeDef));
pdev->pClassDataCmsit[pdev->classId] = (void *)hcdc;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, RNDISInEpAdd, USBD_EP_TYPE_BULK,
CDC_RNDIS_DATA_HS_IN_PACKET_SIZE);
pdev->ep_in[RNDISInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, RNDISOutEpAdd, USBD_EP_TYPE_BULK,
CDC_RNDIS_DATA_HS_OUT_PACKET_SIZE);
pdev->ep_out[RNDISOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CDC RNDIS CMD Endpoint */
pdev->ep_in[RNDISCmdEpAdd & 0xFU].bInterval = CDC_RNDIS_HS_BINTERVAL;
}
else
{
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, RNDISInEpAdd, USBD_EP_TYPE_BULK,
CDC_RNDIS_DATA_FS_IN_PACKET_SIZE);
pdev->ep_in[RNDISInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, RNDISOutEpAdd, USBD_EP_TYPE_BULK,
CDC_RNDIS_DATA_FS_OUT_PACKET_SIZE);
pdev->ep_out[RNDISOutEpAdd & 0xFU].is_used = 1U;
/* Set bInterval for CDC RNDIS CMD Endpoint */
pdev->ep_in[RNDISCmdEpAdd & 0xFU].bInterval = CDC_RNDIS_FS_BINTERVAL;
}
/* Open Command IN EP */
(void)USBD_LL_OpenEP(pdev, RNDISCmdEpAdd, USBD_EP_TYPE_INTR, CDC_RNDIS_CMD_PACKET_SIZE);
pdev->ep_in[RNDISCmdEpAdd & 0xFU].is_used = 1U;
hcdc->RxBuffer = NULL;
/* Init physical Interface components */
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
/* Init the CDC_RNDIS state */
hcdc->State = CDC_RNDIS_STATE_BUS_INITIALIZED;
/* Init Xfer states */
hcdc->TxState = 0U;
hcdc->RxState = 0U;
hcdc->RxLength = 0U;
hcdc->TxLength = 0U;
hcdc->LinkStatus = 0U;
hcdc->NotificationStatus = 0U;
hcdc->MaxPcktLen = (pdev->dev_speed == USBD_SPEED_HIGH) ? CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE : \
CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
if (hcdc->RxBuffer == NULL)
{
return (uint8_t)USBD_EMEM;
}
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, RNDISOutEpAdd,
hcdc->RxBuffer, hcdc->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_DeInit
* DeInitialize the CDC layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
RNDISOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
RNDISCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, RNDISInEpAdd);
pdev->ep_in[RNDISInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, RNDISOutEpAdd);
pdev->ep_out[RNDISOutEpAdd & 0xFU].is_used = 0U;
/* Close Command IN EP */
(void)USBD_LL_CloseEP(pdev, RNDISCmdEpAdd);
pdev->ep_in[RNDISCmdEpAdd & 0xFU].is_used = 0U;
pdev->ep_in[RNDISCmdEpAdd & 0xFU].bInterval = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_Setup
* Handle the CDC specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_CDC_RNDIS_CtrlMsgTypeDef *Msg;
uint8_t ifalt = 0U;
uint16_t status_info = 0U;
USBD_StatusTypeDef ret = USBD_OK;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
Msg = (USBD_CDC_RNDIS_CtrlMsgTypeDef *)(void *)hcdc->data;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS :
if (req->wLength != 0U)
{
/* Control Request Data from Device to Host, send data prepared by device */
if ((req->bmRequest & 0x80U) != 0U)
{
/* Update opcode and length */
hcdc->CmdOpCode = req->bRequest;
hcdc->CmdLength = (uint8_t)req->wLength;
if (hcdc->CmdOpCode == CDC_RNDIS_GET_ENCAPSULATED_RESPONSE)
{
/* Data of Response Message has already been prepared by USBD_CDC_RNDIS_MsgParsing.
Just check that length is corresponding to right expected value */
if (req->wLength != Msg->MsgLength)
{
}
}
/* Allow application layer to pre-process data or add own processing before sending response */
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(req->bRequest,
(uint8_t *)hcdc->data,
req->wLength);
/* Check if Response is ready */
if (hcdc->ResponseRdy != 0U)
{
/* Clear Response Ready flag */
hcdc->ResponseRdy = 0U;
/* Send data on control endpoint */
(void)USBD_CtlSendData(pdev, (uint8_t *)hcdc->data,
MIN(CDC_RNDIS_MAX_DATA_SZE, Msg->MsgLength));
}
else
{
/* CDC_RNDIS Specification says: If for some reason the device receives a GET ENCAPSULATED RESPONSE
and is unable to respond with a valid data on the Control endpoint,
then it should return a one-byte packet set to 0x00, rather than
stalling the Control endpoint */
(void)USBD_CtlSendData(pdev, &EmptyResponse, 1U);
}
}
/* Control Request Data from Host to Device: Prepare reception of control data stage */
else
{
hcdc->CmdOpCode = req->bRequest;
hcdc->CmdLength = (uint8_t)MIN(CDC_RNDIS_MAX_INFO_BUFF_SZ, req->wLength);
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)hcdc->data, hcdc->CmdLength);
}
}
/* No Data control request: there is no such request for CDC_RNDIS protocol,
so let application layer manage this case */
else
{
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->Control(req->bRequest,
(uint8_t *)req, 0U);
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, &ifalt, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_RNDIS_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc;
PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef *)pdev->pData;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (epnum == (RNDISInEpAdd & 0x7FU))
{
if ((pdev->ep_in[epnum & 0xFU].total_length > 0U) &&
((pdev->ep_in[epnum & 0xFU].total_length % hpcd->IN_ep[epnum & 0xFU].maxpacket) == 0U))
{
/* Update the packet total length */
pdev->ep_in[epnum & 0xFU].total_length = 0U;
/* Send ZLP */
(void)USBD_LL_Transmit(pdev, epnum, NULL, 0U);
}
else
{
hcdc->TxState = 0U;
if (((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt != NULL)
{
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->TransmitCplt(hcdc->TxBuffer, \
&hcdc->TxLength, epnum);
}
}
}
else if (epnum == (RNDISCmdEpAdd & 0x7FU))
{
if (hcdc->NotificationStatus != 0U)
{
(void)USBD_CDC_RNDIS_SendNotification(pdev, CONNECTION_SPEED_CHANGE,
0U, (uint8_t *)ConnSpeedTab);
hcdc->NotificationStatus = 0U;
}
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc;
uint32_t CurrPcktLen;
#ifdef USE_USBD_COMPOSITE /* Get the Endpoints addresses allocated for this class instance */
RNDISOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (epnum == RNDISOutEpAdd)
{
/* Get the received data length */
CurrPcktLen = USBD_LL_GetRxDataSize(pdev, epnum);
/* Increment the frame length */
hcdc->RxLength += CurrPcktLen;
/* If the buffer size is less than max packet size: it is the last packet in current frame */
if ((CurrPcktLen < hcdc->MaxPcktLen) ||
(hcdc->RxLength >= (CDC_RNDIS_ETH_MAX_SEGSZE + sizeof(USBD_CDC_RNDIS_PacketMsgTypeDef))))
{
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application Xfer */
/* Call data packet message parsing and processing function */
(void)USBD_CDC_RNDIS_ProcessPacketMsg(pdev, (USBD_CDC_RNDIS_PacketMsgTypeDef *)(void *)hcdc->RxBuffer);
}
else
{
/* Prepare Out endpoint to receive next packet in current/new frame */
(void)USBD_LL_PrepareReceive(pdev, RNDISOutEpAdd,
(uint8_t *)(hcdc->RxBuffer + hcdc->RxLength),
hcdc->MaxPcktLen);
}
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_EP0_RxReady
* Handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((pdev->pUserData[pdev->classId] != NULL) && (hcdc->CmdOpCode != 0xFFU))
{
/* Check if the received command is SendEncapsulated command */
if (hcdc->CmdOpCode == CDC_RNDIS_SEND_ENCAPSULATED_COMMAND)
{
/* Process Received CDC_RNDIS Control Message */
(void)USBD_CDC_RNDIS_MsgParsing(pdev, (uint8_t *)(hcdc->data));
/* Reset the command opcode for next processing */
hcdc->CmdOpCode = 0xFFU;
}
else
{
/* Reset the command opcode for next processing */
hcdc->CmdOpCode = 0xFFU;
/* Ignore the command and return fail */
return (uint8_t)USBD_FAIL;
}
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_CDC_RNDIS_GetFSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_RNDIS_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_RNDIS_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t)(sizeof(USBD_CDC_RNDIS_CfgDesc));
return USBD_CDC_RNDIS_CfgDesc;
}
/**
* @brief USBD_CDC_RNDIS_GetHSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_RNDIS_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_RNDIS_HS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE;
}
*length = (uint16_t)(sizeof(USBD_CDC_RNDIS_CfgDesc));
return USBD_CDC_RNDIS_CfgDesc;
}
/**
* @brief USBD_CDC_RNDIS_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CDC_RNDIS_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_CMD_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_OUT_EP);
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CDC_RNDIS_CfgDesc, CDC_RNDIS_IN_EP);
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = CDC_RNDIS_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
}
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
}
*length = (uint16_t)(sizeof(USBD_CDC_RNDIS_CfgDesc));
return USBD_CDC_RNDIS_CfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CDC_RNDIS_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)(sizeof(USBD_CDC_RNDIS_DeviceQualifierDesc));
return USBD_CDC_RNDIS_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CDC_RNDIS_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_CDC_RNDIS_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_USRStringDescriptor
* Manages the transfer of user string descriptors.
* @param pdev: device instance
* @param index: descriptor index
* @param length : pointer data length
* @retval pointer to the descriptor table or NULL if the descriptor is not supported.
*/
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_CDC_RNDIS_USRStringDescriptor(USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length)
{
static uint8_t USBD_StrDesc[255];
/* Check if the requested string interface is supported */
if (index == CDC_RNDIS_MAC_STRING_INDEX)
{
USBD_GetString((uint8_t *)((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->pStrDesc, USBD_StrDesc,
length);
return USBD_StrDesc;
}
/* Not supported Interface Descriptor index */
else
{
return NULL;
}
}
#endif /* USBD_SUPPORT_USER_STRING_DESC */
/**
* @brief USBD_CDC_RNDIS_SetTxBuffer
* @param pdev: device instance
* @param pbuff: Tx Buffer
* @param length: Tx Buffer length
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_RNDIS_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff, uint32_t length, uint8_t ClassId)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_RNDIS_SetTxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff, uint32_t length)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->TxBuffer = pbuff;
hcdc->TxLength = length;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_SetRxBuffer
* @param pdev: device instance
* @param pbuff: Rx Buffer
* @retval status
*/
uint8_t USBD_CDC_RNDIS_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc->RxBuffer = pbuff;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_TransmitPacket
* Transmit packet on IN endpoint
* @param pdev: device instance
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CDC_RNDIS_TransmitPacket(USBD_HandleTypeDef *pdev, uint8_t ClassId)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CDC_RNDIS_TransmitPacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
USBD_CDC_RNDIS_PacketMsgTypeDef *PacketMsg;
USBD_StatusTypeDef ret = USBD_BUSY;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, ClassId);
#endif /* USE_USBD_COMPOSITE */
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
PacketMsg = (USBD_CDC_RNDIS_PacketMsgTypeDef *)(void *)hcdc->TxBuffer;
if (hcdc->TxState == 0U)
{
/* Tx Transfer in progress */
hcdc->TxState = 1U;
/* Format the packet information */
PacketMsg->MsgType = CDC_RNDIS_PACKET_MSG_ID;
PacketMsg->MsgLength = hcdc->TxLength;
PacketMsg->DataOffset = sizeof(USBD_CDC_RNDIS_PacketMsgTypeDef) - CDC_RNDIS_PCKTMSG_DATAOFFSET_OFFSET;
PacketMsg->DataLength = hcdc->TxLength - sizeof(USBD_CDC_RNDIS_PacketMsgTypeDef);
PacketMsg->OOBDataOffset = 0U;
PacketMsg->OOBDataLength = 0U;
PacketMsg->NumOOBDataElements = 0U;
PacketMsg->PerPacketInfoOffset = 0U;
PacketMsg->PerPacketInfoLength = 0U;
PacketMsg->VcHandle = 0U;
PacketMsg->Reserved = 0U;
/* Update the packet total length */
pdev->ep_in[RNDISInEpAdd & 0xFU].total_length = hcdc->TxLength;
/* Transmit next packet */
(void)USBD_LL_Transmit(pdev, RNDISInEpAdd, hcdc->TxBuffer, hcdc->TxLength);
ret = USBD_OK;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CDC_RNDIS_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CDC_RNDIS_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_CDC_RNDIS_HandleTypeDef *hcdc;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, RNDISOutEpAdd,
hcdc->RxBuffer, hcdc->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_SendNotification
* Transmit Notification packet on CMD IN interrupt endpoint
* @param pdev: device instance
* Notif: value of the notification type (from CDC_RNDIS_Notification_TypeDef enumeration list)
* bVal: value of the notification switch (ie. 0x00 or 0x01 for Network Connection notification)
* pData: pointer to data buffer (ie. upstream and downstream connection speed values)
* @retval status
*/
uint8_t USBD_CDC_RNDIS_SendNotification(USBD_HandleTypeDef *pdev,
USBD_CDC_NotifCodeTypeDef Notif,
uint16_t bVal, uint8_t *pData)
{
uint32_t Idx;
uint16_t ReqSize = 0U;
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
UNUSED(bVal);
UNUSED(pData);
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
RNDISCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Initialize the request fields */
(hcdc->Req).bmRequest = CDC_RNDIS_BMREQUEST_TYPE_RNDIS;
(hcdc->Req).bRequest = (uint8_t)Notif;
switch (Notif)
{
case RESPONSE_AVAILABLE:
(hcdc->Req).wValue = 0U;
(hcdc->Req).wIndex = CDC_RNDIS_CMD_ITF_NBR;
(hcdc->Req).wLength = 0U;
for (Idx = 0U; Idx < 8U; Idx++)
{
(hcdc->Req).data[Idx] = 0U;
}
ReqSize = 8U;
break;
default:
ret = USBD_FAIL;
break;
}
/* Transmit notification packet */
if (ReqSize != 0U)
{
(void)USBD_LL_Transmit(pdev, RNDISCmdEpAdd, (uint8_t *)&hcdc->Req, ReqSize);
}
return (uint8_t)ret;
}
/* ----------------------------- CDC_RNDIS Messages processing functions ----------------------- */
/**
* @brief USBD_CDC_RNDIS_MsgParsing
* Parse received message and process it depending on its nature.
* @param pdev: USB Device Handle pointer
* @param RxBuff: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_MsgParsing(USBD_HandleTypeDef *pdev, uint8_t *RxBuff)
{
USBD_CDC_RNDIS_CtrlMsgTypeDef *Msg = (USBD_CDC_RNDIS_CtrlMsgTypeDef *)(void *)RxBuff;
static uint8_t ret = (uint8_t)USBD_OK;
/* Check message type */
switch (Msg->MsgType)
{
/* CDC_RNDIS Initialize message */
case CDC_RNDIS_INITIALIZE_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessInitMsg(pdev, (USBD_CDC_RNDIS_InitMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS Halt message */
case CDC_RNDIS_HALT_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessHaltMsg(pdev, (USBD_CDC_RNDIS_HaltMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS Query message */
case CDC_RNDIS_QUERY_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessQueryMsg(pdev, (USBD_CDC_RNDIS_QueryMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS Set message */
case CDC_RNDIS_SET_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessSetMsg(pdev, (USBD_CDC_RNDIS_SetMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS Reset message */
case CDC_RNDIS_RESET_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessResetMsg(pdev, (USBD_CDC_RNDIS_ResetMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS Keep-Alive message */
case CDC_RNDIS_KEEPALIVE_MSG_ID:
ret = USBD_CDC_RNDIS_ProcessKeepAliveMsg(pdev, (USBD_CDC_RNDIS_KpAliveMsgTypeDef *)(void *)Msg);
break;
/* CDC_RNDIS unsupported message */
default:
ret = USBD_CDC_RNDIS_ProcessUnsupportedMsg(pdev, (USBD_CDC_RNDIS_CtrlMsgTypeDef *)(void *)Msg);
break;
}
return ret;
}
/**
* @brief USBD_CDC_RNDIS_ProcessInitMsg
* Parse, extract data and check correctness of CDC_RNDIS INIT_MSG command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessInitMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_InitMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Get and format the Msg input */
USBD_CDC_RNDIS_InitMsgTypeDef *InitMessage = (USBD_CDC_RNDIS_InitMsgTypeDef *)Msg;
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_InitCpltMsgTypeDef *InitResponse = (USBD_CDC_RNDIS_InitCpltMsgTypeDef *)(void *)Msg;
/* Store the Message Request ID */
uint32_t ReqId = InitMessage->ReqId;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Check correctness of the message (MsgType already checked by entry to this function) */
if ((InitMessage->MsgLength != sizeof(USBD_CDC_RNDIS_InitMsgTypeDef)) || \
(InitMessage->MajorVersion < CDC_RNDIS_VERSION_MAJOR))
{
InitResponse->Status = CDC_RNDIS_STATUS_FAILURE;
}
else
{
InitResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
}
/* Setup the response buffer content */
InitResponse->MsgType = CDC_RNDIS_INITIALIZE_CMPLT_ID;
InitResponse->MsgLength = sizeof(USBD_CDC_RNDIS_InitCpltMsgTypeDef);
InitResponse->ReqId = ReqId;
InitResponse->MajorVersion = CDC_RNDIS_VERSION_MAJOR;
InitResponse->MinorVersion = CDC_RNDIS_VERSION_MINOR;
InitResponse->DeviceFlags = CDC_RNDIS_DF_CONNECTIONLESS;
InitResponse->Medium = CDC_RNDIS_MEDIUM_802_3;
InitResponse->MaxPacketsPerTransfer = 1U;
InitResponse->MaxTransferSize = (sizeof(USBD_CDC_RNDIS_PacketMsgTypeDef) + CDC_RNDIS_ETH_FRAME_SIZE_MAX);
InitResponse->PacketAlignmentFactor = 2U; /* Not needed as single packet by transfer set */
InitResponse->AFListOffset = 0U; /* Reserved for connection-oriented devices. Set value to zero. */
InitResponse->AFListSize = 0U; /* Reserved for connection-oriented devices. Set value to zero. */
/* Set CDC_RNDIS state to INITIALIZED */
hcdc->State = CDC_RNDIS_STATE_INITIALIZED;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessHaltMsg
* Parse, extract data and check correctness of CDC_RNDIS Halt command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessHaltMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_HaltMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Set CDC_RNDIS state to INITIALIZED */
hcdc->State = CDC_RNDIS_STATE_UNINITIALIZED;
/* No response required for this message, so no notification (RESPONSE_AVAILABLE) is sent */
UNUSED(Msg);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessKeepAliveMsg
* Parse, extract data and check correctness of CDC_RNDIS KeepAlive command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessKeepAliveMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_KpAliveMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_KpAliveCpltMsgTypeDef *InitResponse = (USBD_CDC_RNDIS_KpAliveCpltMsgTypeDef *)(void *)Msg;
/* Store the Message Request ID */
uint32_t ReqId = Msg->ReqId;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Check correctness of the message (MsgType already checked by entry to this function) */
if (Msg->MsgLength != sizeof(USBD_CDC_RNDIS_KpAliveMsgTypeDef))
{
InitResponse->Status = CDC_RNDIS_STATUS_FAILURE;
}
else
{
InitResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
}
/* Setup the response buffer content */
InitResponse->MsgType = CDC_RNDIS_KEEPALIVE_CMPLT_ID;
InitResponse->MsgLength = sizeof(USBD_CDC_RNDIS_KpAliveCpltMsgTypeDef);
InitResponse->ReqId = ReqId;
InitResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessQueryMsg
* Parse, extract data and check correctness of CDC_RNDIS Query command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessQueryMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_QueryMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_QueryCpltMsgTypeDef *QueryResponse = (USBD_CDC_RNDIS_QueryCpltMsgTypeDef *)(void *)Msg;
/* Store the Message Request ID */
uint32_t ReqId = Msg->RequestId;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Process the OID depending on its code */
switch (Msg->Oid)
{
case OID_GEN_SUPPORTED_LIST:
QueryResponse->InfoBufLength = sizeof(CDC_RNDIS_SupportedOIDs);
(void)USBD_memcpy(QueryResponse->InfoBuf, CDC_RNDIS_SupportedOIDs,
sizeof(CDC_RNDIS_SupportedOIDs));
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_HARDWARE_STATUS:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = CDC_RNDIS_HW_STS_READY;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_MEDIA_SUPPORTED:
case OID_GEN_MEDIA_IN_USE:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = CDC_RNDIS_MEDIUM_802_3;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_VENDOR_ID:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = USBD_CDC_RNDIS_VID;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_MAXIMUM_FRAME_SIZE:
case OID_GEN_TRANSMIT_BLOCK_SIZE:
case OID_GEN_RECEIVE_BLOCK_SIZE:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = CDC_RNDIS_ETH_FRAME_SIZE_MAX;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_VENDOR_DESCRIPTION:
QueryResponse->InfoBufLength = (strlen(USBD_CDC_RNDIS_VENDOR_DESC) + 1U);
(void)USBD_memcpy(QueryResponse->InfoBuf, USBD_CDC_RNDIS_VENDOR_DESC,
strlen(USBD_CDC_RNDIS_VENDOR_DESC));
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_MEDIA_CONNECT_STATUS:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = CDC_RNDIS_MEDIA_STATE_CONNECTED;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_MAXIMUM_SEND_PACKETS:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = 1U;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_LINK_SPEED:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = USBD_CDC_RNDIS_LINK_SPEED;
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_802_3_PERMANENT_ADDRESS:
case OID_802_3_CURRENT_ADDRESS:
QueryResponse->InfoBufLength = 6U;
(void)USBD_memcpy(QueryResponse->InfoBuf, MAC_StrDesc, 6);
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_802_3_MAXIMUM_LIST_SIZE:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = 1U; /* Only one multicast address supported */
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_CURRENT_PACKET_FILTER:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = 0xFFFFFFU; /* USBD_CDC_RNDIS_DEVICE.packetFilter; */
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_802_3_RCV_ERROR_ALIGNMENT:
case OID_802_3_XMIT_ONE_COLLISION:
case OID_802_3_XMIT_MORE_COLLISIONS:
QueryResponse->InfoBufLength = sizeof(uint32_t);
QueryResponse->InfoBuf[0] = 0U; /* Unused OIDs, return zero */
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_GEN_MAXIMUM_TOTAL_SIZE:
QueryResponse->InfoBufLength = sizeof(uint32_t);
/* Indicate maximum overall buffer (Ethernet frame and CDC_RNDIS header) the adapter can handle */
QueryResponse->InfoBuf[0] = (CDC_RNDIS_MESSAGE_BUFFER_SIZE + CDC_RNDIS_ETH_FRAME_SIZE_MAX);
QueryResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
default:
/* Unknown or unsupported OID */
QueryResponse->InfoBufLength = 0U;
QueryResponse->Status = CDC_RNDIS_STATUS_FAILURE;
break;
}
/* Setup the response buffer content */
QueryResponse->MsgType = CDC_RNDIS_QUERY_CMPLT_ID;
QueryResponse->MsgLength = QueryResponse->InfoBufLength + 24U;
QueryResponse->ReqId = ReqId;
QueryResponse->InfoBufOffset = 16U;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessSetMsg
* Parse, extract data and check correctness of CDC_RNDIS Set Message command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessSetMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_SetMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Get and format the Msg input */
USBD_CDC_RNDIS_SetMsgTypeDef *SetMessage = (USBD_CDC_RNDIS_SetMsgTypeDef *)Msg;
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_SetCpltMsgTypeDef *SetResponse = (USBD_CDC_RNDIS_SetCpltMsgTypeDef *)(void *)Msg;
/* Store the Message Request ID */
uint32_t ReqId = SetMessage->ReqId;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (SetMessage->Oid)
{
case OID_GEN_CURRENT_PACKET_FILTER:
/* Setup the packet filter value */
hcdc->PacketFilter = SetMessage->InfoBuf[0];
SetResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
case OID_802_3_MULTICAST_LIST:
/* List of multicast addresses on a miniport adapter */
SetResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
break;
default:
/* Report an error */
SetResponse->Status = CDC_RNDIS_STATUS_FAILURE;
break;
}
/* Prepare response buffer */
SetResponse->MsgType = CDC_RNDIS_SET_CMPLT_ID;
SetResponse->MsgLength = sizeof(USBD_CDC_RNDIS_SetCpltMsgTypeDef);
SetResponse->ReqId = ReqId;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessResetMsg
* Parse, extract data and check correctness of CDC_RNDIS Set Message command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessResetMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_ResetMsgTypeDef *Msg)
{
/* Get and format the Msg input */
USBD_CDC_RNDIS_ResetMsgTypeDef *ResetMessage = (USBD_CDC_RNDIS_ResetMsgTypeDef *)Msg;
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_ResetCpltMsgTypeDef *ResetResponse = (USBD_CDC_RNDIS_ResetCpltMsgTypeDef *)(void *)Msg;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((ResetMessage->MsgLength != sizeof(USBD_CDC_RNDIS_ResetMsgTypeDef)) || \
(ResetMessage->Reserved != 0U))
{
ResetResponse->Status = CDC_RNDIS_STATUS_FAILURE;
}
else
{
ResetResponse->Status = CDC_RNDIS_STATUS_SUCCESS;
}
/* Prepare response buffer */
ResetResponse->MsgType = CDC_RNDIS_RESET_CMPLT_ID;
ResetResponse->MsgLength = sizeof(USBD_CDC_RNDIS_ResetCpltMsgTypeDef);
ResetResponse->AddrReset = 0U;
/* Set CDC_RNDIS state to INITIALIZED */
hcdc->State = CDC_RNDIS_STATE_BUS_INITIALIZED;
hcdc->LinkStatus = 0U;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessPacketMsg
* Parse, extract data and check correctness of CDC_RNDIS Data Packet.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from Packet
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessPacketMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_PacketMsgTypeDef *Msg)
{
uint32_t tmp1;
uint32_t tmp2;
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Get and format the Msg input */
USBD_CDC_RNDIS_PacketMsgTypeDef *PacketMsg = (USBD_CDC_RNDIS_PacketMsgTypeDef *)Msg;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Check correctness of the message */
if ((PacketMsg->MsgType != CDC_RNDIS_PACKET_MSG_ID))
{
return (uint8_t)USBD_FAIL;
}
/* Point to the payload and update the message length */
/* Use temporary storage variables to comply with MISRA-C 2012 rule of (+) operand allowed types */
tmp1 = (uint32_t)PacketMsg;
tmp2 = (uint32_t)(PacketMsg->DataOffset);
hcdc->RxBuffer = (uint8_t *)(tmp1 + tmp2 + CDC_RNDIS_PCKTMSG_DATAOFFSET_OFFSET);
hcdc->RxLength = PacketMsg->DataLength;
/* Process data by application */
((USBD_CDC_RNDIS_ItfTypeDef *)pdev->pUserData[pdev->classId])->Receive(hcdc->RxBuffer, &hcdc->RxLength);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CDC_RNDIS_ProcessUnsupportedMsg
* Parse, extract data and check correctness of CDC_RNDIS KeepAlive command.
* @param pdev: USB Device Handle pointer
* @param Msg: Pointer to the message data extracted from SendEncapsulated command
* @retval status
*/
static uint8_t USBD_CDC_RNDIS_ProcessUnsupportedMsg(USBD_HandleTypeDef *pdev,
USBD_CDC_RNDIS_CtrlMsgTypeDef *Msg)
{
/* Get the CDC_RNDIS handle pointer */
USBD_CDC_RNDIS_HandleTypeDef *hcdc = (USBD_CDC_RNDIS_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Use same Msg input buffer as response buffer */
USBD_CDC_RNDIS_StsChangeMsgTypeDef *Response = (USBD_CDC_RNDIS_StsChangeMsgTypeDef *)(void *)Msg;
if (hcdc == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Setup the response buffer content */
Response->MsgType = CDC_RNDIS_INDICATE_STATUS_MSG_ID;
Response->MsgLength = sizeof(USBD_CDC_RNDIS_StsChangeMsgTypeDef);
Response->Status = CDC_RNDIS_STATUS_NOT_SUPPORTED;
Response->StsBufLength = 0U;
Response->StsBufOffset = 20U;
/* Set Response Ready field in order to send response during next control request */
hcdc->ResponseRdy = 1U;
/* Send Notification on Interrupt EP to inform Host that response is ready */
(void)USBD_CDC_RNDIS_SendNotification(pdev, RESPONSE_AVAILABLE, 0U, NULL);
UNUSED(Msg);
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS | D://workCode//uploadProject\stm32_mw_usb_device\Class\CDC_RNDIS\Src\usbd_cdc_rndis_if_template.c | /**
******************************************************************************
* @file usbd_cdc_rndis_if_template.c
* @author MCD Application Team
* @brief Source file for USBD CDC_RNDIS interface template
******************************************************************************
* @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 TCP/IP stack header files */
/*
#include "lwip/opt.h"
#include "lwip/init.h"
#include "lwip/dhcp.h"
#include "lwip/netif.h"
#include "lwip/timeouts.h"
#include "netif/etharp.h"
#include "http_cgi_ssi.h"
#include "ethernetif.h"
*/
#include "usbd_cdc_rndis_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Received Data over USB are stored in this buffer */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t UserRxBuffer[CDC_RNDIS_ETH_MAX_SEGSZE + 100] __ALIGN_END;
/* Transmitted Data over CDC_RNDIS (CDC_RNDIS interface) are stored in this buffer */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN static uint8_t UserTxBuffer[CDC_RNDIS_ETH_MAX_SEGSZE + 100] __ALIGN_END;
static uint8_t CDC_RNDISInitialized = 0U;
/* USB handler declaration */
extern USBD_HandleTypeDef USBD_Device;
/* Private function prototypes -----------------------------------------------*/
static int8_t CDC_RNDIS_Itf_Init(void);
static int8_t CDC_RNDIS_Itf_DeInit(void);
static int8_t CDC_RNDIS_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length);
static int8_t CDC_RNDIS_Itf_Receive(uint8_t *pbuf, uint32_t *Len);
static int8_t CDC_RNDIS_Itf_TransmitCplt(uint8_t *pbuf, uint32_t *Len, uint8_t epnum);
static int8_t CDC_RNDIS_Itf_Process(USBD_HandleTypeDef *pdev);
USBD_CDC_RNDIS_ItfTypeDef USBD_CDC_RNDIS_fops =
{
CDC_RNDIS_Itf_Init,
CDC_RNDIS_Itf_DeInit,
CDC_RNDIS_Itf_Control,
CDC_RNDIS_Itf_Receive,
CDC_RNDIS_Itf_TransmitCplt,
CDC_RNDIS_Itf_Process,
(uint8_t *)CDC_RNDIS_MAC_STR_DESC,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief CDC_RNDIS_Itf_Init
* Initializes the CDC_RNDIS media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_Init(void)
{
if (CDC_RNDISInitialized == 0U)
{
/*
Initialize the LwIP stack
Add your code here
*/
CDC_RNDISInitialized = 1U;
}
/* Set Application Buffers */
#ifdef USE_USBD_COMPOSITE
(void)USBD_CDC_RNDIS_SetTxBuffer(&USBD_Device, UserTxBuffer, 0U, 0U);
#else
(void)USBD_CDC_RNDIS_SetTxBuffer(&USBD_Device, UserTxBuffer, 0U);
#endif /* USE_USBD_COMPOSITE */
(void)USBD_CDC_RNDIS_SetRxBuffer(&USBD_Device, UserRxBuffer);
return (0);
}
/**
* @brief CDC_RNDIS_Itf_DeInit
* DeInitializes the CDC_RNDIS media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_DeInit(void)
{
#ifdef USE_USBD_COMPOSITE
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
/*
Add your code here
*/
/* Notify application layer that link is down */
hcdc_cdc_rndis->LinkStatus = 0U;
return (0);
}
/**
* @brief CDC_RNDIS_Itf_Control
* Manage the CDC_RNDIS class requests
* @param Cmd: Command code
* @param Buf: Buffer containing command data (request parameters)
* @param Len: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length)
{
#ifdef USE_USBD_COMPOSITE
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
switch (cmd)
{
case CDC_RNDIS_SEND_ENCAPSULATED_COMMAND:
/* Add your code here */
break;
case CDC_RNDIS_GET_ENCAPSULATED_RESPONSE:
/* Check if this is the first time we enter */
if (hcdc_cdc_rndis->LinkStatus == 0U)
{
/* Setup the Link up at TCP/IP stack level */
hcdc_cdc_rndis->LinkStatus = 1U;
/*
Add your code here
*/
}
/* Add your code here */
break;
default:
/* Add your code here */
break;
}
UNUSED(length);
UNUSED(pbuf);
return (0);
}
/**
* @brief CDC_RNDIS_Itf_Receive
* Data received over USB OUT endpoint are sent over CDC_RNDIS interface
* through this function.
* @param Buf: Buffer of data to be transmitted
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_Receive(uint8_t *Buf, uint32_t *Len)
{
/* Get the CDC_RNDIS handler pointer */
#ifdef USE_USBD_COMPOSITE
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *) \
(USBD_Device.pClassDataCmsit[USBD_Device.classId]);
#else
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *)(USBD_Device.pClassData);
#endif /* USE_USBD_COMPOSITE */
/* Call Eth buffer processing */
hcdc_cdc_rndis->RxState = 1U;
UNUSED(Buf);
UNUSED(Len);
return (0);
}
/**
* @brief CDC_RNDIS_Itf_TransmitCplt
* Data transmitted callback
*
* @note
* This function is IN transfer complete callback used to inform user that
* the submitted Data is successfully sent over USB.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @param epnum: EP number
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_TransmitCplt(uint8_t *Buf, uint32_t *Len, uint8_t epnum)
{
UNUSED(Buf);
UNUSED(Len);
UNUSED(epnum);
return (0);
}
/**
* @brief CDC_RNDIS_Itf_Process
* Data received over USB OUT endpoint are sent over CDC_RNDIS interface
* through this function.
* @param pdef: pointer to the USB Device Handle
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t CDC_RNDIS_Itf_Process(USBD_HandleTypeDef *pdev)
{
/* Get the CDC_RNDIS handler pointer */
#ifdef USE_USBD_COMPOSITE
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *)(pdev->pClassDataCmsit[pdev->classId]);
#else
USBD_CDC_RNDIS_HandleTypeDef *hcdc_cdc_rndis = (USBD_CDC_RNDIS_HandleTypeDef *)(pdev->pClassData);
#endif /* USE_USBD_COMPOSITE */
if (hcdc_cdc_rndis == NULL)
{
return (-1);
}
if (hcdc_cdc_rndis->LinkStatus != 0U)
{
/*
Add your code here
Read a received packet from the Ethernet buffers and send it
to the lwIP for handling
*/
}
return (0);
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CompositeBuilder | D://workCode//uploadProject\stm32_mw_usb_device\Class\CompositeBuilder\Inc\usbd_composite_builder.h | /**
******************************************************************************
* @file usbd_composite_builder.h
* @author MCD Application Team
* @brief Header for the usbd_composite_builder.c file
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_COMPOSITE_BUILDER_H__
#define __USBD_COMPOSITE_BUILDER_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
#if USBD_CMPSIT_ACTIVATE_HID == 1U
#include "usbd_hid.h"
#endif /* USBD_CMPSIT_ACTIVATE_HID */
#if USBD_CMPSIT_ACTIVATE_MSC == 1U
#include "usbd_msc.h"
#endif /* USBD_CMPSIT_ACTIVATE_MSC */
#if USBD_CMPSIT_ACTIVATE_CDC == 1U
#include "usbd_cdc.h"
#endif /* USBD_CMPSIT_ACTIVATE_CDC */
#if USBD_CMPSIT_ACTIVATE_DFU == 1U
#include "usbd_dfu.h"
#endif /* USBD_CMPSIT_ACTIVATE_DFU */
#if USBD_CMPSIT_ACTIVATE_RNDIS == 1U
#include "usbd_cdc_rndis.h"
#endif /* USBD_CMPSIT_ACTIVATE_RNDIS */
#if USBD_CMPSIT_ACTIVATE_CDC_ECM == 1U
#include "usbd_cdc_ecm.h"
#ifndef __USBD_CDC_ECM_IF_H
#include "usbd_cdc_ecm_if_template.h"
#endif /* __USBD_CDC_ECM_IF_H */
#endif /* USBD_CMPSIT_ACTIVATE_CDC_ECM */
#if USBD_CMPSIT_ACTIVATE_AUDIO == 1
#include "usbd_audio.h"
#endif /* USBD_CMPSIT_ACTIVATE_AUDIO */
#if USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1
#include "usbd_customhid.h"
#endif /* USBD_CMPSIT_ACTIVATE_CUSTOMHID */
#if USBD_CMPSIT_ACTIVATE_VIDEO == 1
#include "usbd_video.h"
#endif /* USBD_CMPSIT_ACTIVATE_VIDEO */
#if USBD_CMPSIT_ACTIVATE_PRINTER == 1
#include "usbd_printer.h"
#endif /* USBD_CMPSIT_ACTIVATE_PRINTER */
#if USBD_CMPSIT_ACTIVATE_CCID == 1U
#include "usbd_ccid.h"
#endif /* USBD_CMPSIT_ACTIVATE_CCID */
#if USBD_CMPSIT_ACTIVATE_MTP == 1U
#include "usbd_mtp.h"
#endif /* USBD_CMPSIT_ACTIVATE_MTP */
/* Private defines -----------------------------------------------------------*/
/* By default all classes are deactivated, in order to activate a class
define its value to zero */
#ifndef USBD_CMPSIT_ACTIVATE_HID
#define USBD_CMPSIT_ACTIVATE_HID 0U
#endif /* USBD_CMPSIT_ACTIVATE_HID */
#ifndef USBD_CMPSIT_ACTIVATE_MSC
#define USBD_CMPSIT_ACTIVATE_MSC 0U
#endif /* USBD_CMPSIT_ACTIVATE_MSC */
#ifndef USBD_CMPSIT_ACTIVATE_DFU
#define USBD_CMPSIT_ACTIVATE_DFU 0U
#endif /* USBD_CMPSIT_ACTIVATE_DFU */
#ifndef USBD_CMPSIT_ACTIVATE_CDC
#define USBD_CMPSIT_ACTIVATE_CDC 0U
#endif /* USBD_CMPSIT_ACTIVATE_CDC */
#ifndef USBD_CMPSIT_ACTIVATE_CDC_ECM
#define USBD_CMPSIT_ACTIVATE_CDC_ECM 0U
#endif /* USBD_CMPSIT_ACTIVATE_CDC_ECM */
#ifndef USBD_CMPSIT_ACTIVATE_RNDIS
#define USBD_CMPSIT_ACTIVATE_RNDIS 0U
#endif /* USBD_CMPSIT_ACTIVATE_RNDIS */
#ifndef USBD_CMPSIT_ACTIVATE_AUDIO
#define USBD_CMPSIT_ACTIVATE_AUDIO 0U
#endif /* USBD_CMPSIT_ACTIVATE_AUDIO */
#ifndef USBD_CMPSIT_ACTIVATE_CUSTOMHID
#define USBD_CMPSIT_ACTIVATE_CUSTOMHID 0U
#endif /* USBD_CMPSIT_ACTIVATE_CUSTOMHID */
#ifndef USBD_CMPSIT_ACTIVATE_VIDEO
#define USBD_CMPSIT_ACTIVATE_VIDEO 0U
#endif /* USBD_CMPSIT_ACTIVATE_VIDEO */
#ifndef USBD_CMPSIT_ACTIVATE_PRINTER
#define USBD_CMPSIT_ACTIVATE_PRINTER 0U
#endif /* USBD_CMPSIT_ACTIVATE_PRINTER */
#ifndef USBD_CMPSIT_ACTIVATE_CCID
#define USBD_CMPSIT_ACTIVATE_CCID 0U
#endif /* USBD_CMPSIT_ACTIVATE_CCID */
#ifndef USBD_CMPSIT_ACTIVATE_MTP
#define USBD_CMPSIT_ACTIVATE_MTP 0U
#endif /* USBD_CMPSIT_ACTIVATE_MTP */
/* This is the maximum supported configuration descriptor size
User may define this value in usbd_conf.h in order to optimize footprint */
#ifndef USBD_CMPST_MAX_CONFDESC_SZ
#define USBD_CMPST_MAX_CONFDESC_SZ 300U
#endif /* USBD_CMPST_MAX_CONFDESC_SZ */
#ifndef USBD_CONFIG_STR_DESC_IDX
#define USBD_CONFIG_STR_DESC_IDX 4U
#endif /* USBD_CONFIG_STR_DESC_IDX */
/* Exported types ------------------------------------------------------------*/
/* USB Iad descriptors structure */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bFirstInterface;
uint8_t bInterfaceCount;
uint8_t bFunctionClass;
uint8_t bFunctionSubClass;
uint8_t bFunctionProtocol;
uint8_t iFunction;
} USBD_IadDescTypeDef;
/* USB interface descriptors structure */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} USBD_IfDescTypeDef;
#if (USBD_CMPSIT_ACTIVATE_CDC == 1) || (USBD_CMPSIT_ACTIVATE_RNDIS == 1) || (USBD_CMPSIT_ACTIVATE_CDC_ECM == 1)
typedef struct
{
/*
* CDC Class specification revision 1.2
* Table 15: Class-Specific Descriptor Header Format
*/
/* Header Functional Descriptor */
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdCDC;
} __PACKED USBD_CDCHeaderFuncDescTypeDef;
typedef struct
{
/* Call Management Functional Descriptor */
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
uint8_t bDataInterface;
} USBD_CDCCallMgmFuncDescTypeDef;
typedef struct
{
/* ACM Functional Descriptor */
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
} USBD_CDCACMFuncDescTypeDef;
typedef struct
{
/*
* CDC Class specification revision 1.2
* Table 16: Union Interface Functional Descriptor
*/
/* Union Functional Descriptor */
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bMasterInterface;
uint8_t bSlaveInterface;
} USBD_CDCUnionFuncDescTypeDef;
#endif /* (USBD_CMPSIT_ACTIVATE_CDC == 1) || (USBD_CMPSIT_ACTIVATE_RNDIS == 1) || (USBD_CMPSIT_ACTIVATE_CDC_ECM == 1)*/
extern USBD_ClassTypeDef USBD_CMPSIT;
/* Exported functions prototypes ---------------------------------------------*/
uint8_t USBD_CMPSIT_AddToConfDesc(USBD_HandleTypeDef *pdev);
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CMPSIT_AddClass(USBD_HandleTypeDef *pdev,
USBD_ClassTypeDef *pclass,
USBD_CompositeClassTypeDef class,
uint8_t cfgidx);
uint32_t USBD_CMPSIT_SetClassID(USBD_HandleTypeDef *pdev,
USBD_CompositeClassTypeDef Class,
uint32_t Instance);
uint32_t USBD_CMPSIT_GetClassID(USBD_HandleTypeDef *pdev,
USBD_CompositeClassTypeDef Class,
uint32_t Instance);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CMPST_ClearConfDesc(USBD_HandleTypeDef *pdev);
/* Private macro -----------------------------------------------------------*/
#define __USBD_CMPSIT_SET_EP(epadd, eptype, epsize, HSinterval, FSinterval) \
do { \
/* Append Endpoint descriptor to Configuration descriptor */ \
pEpDesc = ((USBD_EpDescTypeDef*)((uint32_t)pConf + *Sze)); \
pEpDesc->bLength = (uint8_t)sizeof(USBD_EpDescTypeDef); \
pEpDesc->bDescriptorType = USB_DESC_TYPE_ENDPOINT; \
pEpDesc->bEndpointAddress = (epadd); \
pEpDesc->bmAttributes = (eptype); \
pEpDesc->wMaxPacketSize = (uint16_t)(epsize); \
if(speed == (uint8_t)USBD_SPEED_HIGH) \
{ \
pEpDesc->bInterval = HSinterval; \
} \
else \
{ \
pEpDesc->bInterval = FSinterval; \
} \
*Sze += (uint32_t)sizeof(USBD_EpDescTypeDef); \
} while(0)
#define __USBD_CMPSIT_SET_IF(ifnum, alt, eps, class, subclass, protocol, istring) \
do { \
/* Interface Descriptor */ \
pIfDesc = ((USBD_IfDescTypeDef*)((uint32_t)pConf + *Sze)); \
pIfDesc->bLength = (uint8_t)sizeof(USBD_IfDescTypeDef); \
pIfDesc->bDescriptorType = USB_DESC_TYPE_INTERFACE; \
pIfDesc->bInterfaceNumber = ifnum; \
pIfDesc->bAlternateSetting = alt; \
pIfDesc->bNumEndpoints = eps; \
pIfDesc->bInterfaceClass = class; \
pIfDesc->bInterfaceSubClass = subclass; \
pIfDesc->bInterfaceProtocol = protocol; \
pIfDesc->iInterface = istring; \
*Sze += (uint32_t)sizeof(USBD_IfDescTypeDef); \
} while(0)
#ifdef __cplusplus
}
#endif
#endif /* __USBD_COMPOSITE_BUILDER_H__ */
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CompositeBuilder | D://workCode//uploadProject\stm32_mw_usb_device\Class\CompositeBuilder\Src\usbd_composite_builder.c | /**
******************************************************************************
* @file usbd_composite_builder.c
* @author MCD Application Team
* @brief This file provides all the composite builder functions.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
* @verbatim
*
* ===================================================================
* Composite Builder Description
* ===================================================================
*
* The composite builder builds the configuration descriptors based on
* the selection of classes by user.
* It includes all USB Device classes in order to instantiate their
* descriptors, but for better management, it is possible to optimize
* footprint by removing unused classes. It is possible to do so by
* commenting the relative define in usbd_conf.h.
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- None
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_composite_builder.h"
#ifdef USE_USBD_COMPOSITE
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup CMPSIT_CORE
* @brief Mass storage core module
* @{
*/
/** @defgroup CMPSIT_CORE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup CMPSIT_CORE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup CMPSIT_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup CMPSIT_CORE_Private_FunctionPrototypes
* @{
*/
/* uint8_t USBD_CMPSIT_Init (USBD_HandleTypeDef *pdev,
uint8_t cfgidx); */ /* Function not used for the moment */
/* uint8_t USBD_CMPSIT_DeInit (USBD_HandleTypeDef *pdev,
uint8_t cfgidx); */ /* Function not used for the moment */
uint8_t *USBD_CMPSIT_GetFSCfgDesc(uint16_t *length);
#ifdef USE_USB_HS
uint8_t *USBD_CMPSIT_GetHSCfgDesc(uint16_t *length);
#endif /* USE_USB_HS */
uint8_t *USBD_CMPSIT_GetOtherSpeedCfgDesc(uint16_t *length);
uint8_t *USBD_CMPSIT_GetDeviceQualifierDescriptor(uint16_t *length);
static uint8_t USBD_CMPSIT_FindFreeIFNbr(USBD_HandleTypeDef *pdev);
static void USBD_CMPSIT_AddConfDesc(uint32_t Conf, __IO uint32_t *pSze);
static void USBD_CMPSIT_AssignEp(USBD_HandleTypeDef *pdev, uint8_t Add, uint8_t Type, uint32_t Sze);
#if USBD_CMPSIT_ACTIVATE_HID == 1U
static void USBD_CMPSIT_HIDMouseDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_HID == 1U */
#if USBD_CMPSIT_ACTIVATE_MSC == 1U
static void USBD_CMPSIT_MSCDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_MSC == 1U */
#if USBD_CMPSIT_ACTIVATE_CDC == 1U
static void USBD_CMPSIT_CDCDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_CDC == 1U */
#if USBD_CMPSIT_ACTIVATE_DFU == 1U
static void USBD_CMPSIT_DFUDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_DFU == 1U */
#if USBD_CMPSIT_ACTIVATE_RNDIS == 1U
static void USBD_CMPSIT_RNDISDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_RNDIS == 1U */
#if USBD_CMPSIT_ACTIVATE_CDC_ECM == 1U
static void USBD_CMPSIT_CDC_ECMDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_CDC_ECM == 1U */
#if USBD_CMPSIT_ACTIVATE_AUDIO == 1U
static void USBD_CMPSIT_AUDIODesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_AUDIO == 1U */
#if USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1
static void USBD_CMPSIT_CUSTOMHIDDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1U */
#if USBD_CMPSIT_ACTIVATE_VIDEO == 1U
static void USBD_CMPSIT_VIDEODesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_VIDEO == 1U */
#if USBD_CMPSIT_ACTIVATE_PRINTER == 1U
static void USBD_CMPSIT_PRNTDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_PRINTER == 1U */
#if USBD_CMPSIT_ACTIVATE_CCID == 1U
static void USBD_CMPSIT_CCIDDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_CCID == 1U */
#if USBD_CMPSIT_ACTIVATE_MTP == 1U
static void USBD_CMPSIT_MTPDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed);
#endif /* USBD_CMPSIT_ACTIVATE_MTP == 1U */
/**
* @}
*/
/** @defgroup CMPSIT_CORE_Private_Variables
* @{
*/
/* This structure is used only for the Configuration descriptors and Device Qualifier */
USBD_ClassTypeDef USBD_CMPSIT =
{
NULL, /* Init, */
NULL, /* DeInit, */
NULL, /* Setup, */
NULL, /* EP0_TxSent, */
NULL, /* EP0_RxReady, */
NULL, /* DataIn, */
NULL, /* DataOut, */
NULL, /* SOF, */
NULL,
NULL,
#ifdef USE_USB_HS
USBD_CMPSIT_GetHSCfgDesc,
#else
NULL,
#endif /* USE_USB_HS */
USBD_CMPSIT_GetFSCfgDesc,
USBD_CMPSIT_GetOtherSpeedCfgDesc,
USBD_CMPSIT_GetDeviceQualifierDescriptor,
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
NULL,
#endif /* USBD_SUPPORT_USER_STRING_DESC */
};
/* The generic configuration descriptor buffer that will be filled by builder
Size of the buffer is the maximum possible configuration descriptor size. */
__ALIGN_BEGIN static uint8_t USBD_CMPSIT_FSCfgDesc[USBD_CMPST_MAX_CONFDESC_SZ] __ALIGN_END = {0};
static uint8_t *pCmpstFSConfDesc = USBD_CMPSIT_FSCfgDesc;
/* Variable that dynamically holds the current size of the configuration descriptor */
static __IO uint32_t CurrFSConfDescSz = 0U;
#ifdef USE_USB_HS
__ALIGN_BEGIN static uint8_t USBD_CMPSIT_HSCfgDesc[USBD_CMPST_MAX_CONFDESC_SZ] __ALIGN_END = {0};
static uint8_t *pCmpstHSConfDesc = USBD_CMPSIT_HSCfgDesc;
/* Variable that dynamically holds the current size of the configuration descriptor */
static __IO uint32_t CurrHSConfDescSz = 0U;
#endif /* USE_USB_HS */
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CMPSIT_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC, /* bLength */
USB_DESC_TYPE_DEVICE_QUALIFIER, /* bDescriptorType */
0x00, /* bcdDevice low */
0x02, /* bcdDevice high */
0xEF, /* Class */
0x02, /* SubClass */
0x01, /* Protocol */
0x40, /* bMaxPacketSize0 */
0x01, /* bNumConfigurations */
0x00, /* bReserved */
};
/**
* @}
*/
/** @defgroup CMPSIT_CORE_Private_Functions
* @{
*/
/**
* @brief USBD_CMPSIT_AddClass
* Register a class in the class builder
* @param pdev: device instance
* @param pclass: pointer to the class structure to be added
* @param class: type of the class to be added (from USBD_CompositeClassTypeDef)
* @param cfgidx: configuration index
* @retval status
*/
uint8_t USBD_CMPSIT_AddClass(USBD_HandleTypeDef *pdev,
USBD_ClassTypeDef *pclass,
USBD_CompositeClassTypeDef class,
uint8_t cfgidx)
{
if ((pdev->classId < USBD_MAX_SUPPORTED_CLASS) && (pdev->tclasslist[pdev->classId].Active == 0U))
{
/* Store the class parameters in the global tab */
pdev->pClass[pdev->classId] = pclass;
pdev->tclasslist[pdev->classId].ClassId = pdev->classId;
pdev->tclasslist[pdev->classId].Active = 1U;
pdev->tclasslist[pdev->classId].ClassType = class;
/* Call configuration descriptor builder and endpoint configuration builder */
if (USBD_CMPSIT_AddToConfDesc(pdev) != (uint8_t)USBD_OK)
{
return (uint8_t)USBD_FAIL;
}
}
UNUSED(cfgidx);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CMPSIT_AddToConfDesc
* Add a new class to the configuration descriptor
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CMPSIT_AddToConfDesc(USBD_HandleTypeDef *pdev)
{
uint8_t idxIf = 0U;
uint8_t iEp = 0U;
/* For the first class instance, start building the config descriptor common part */
if (pdev->classId == 0U)
{
/* Add configuration and IAD descriptors */
USBD_CMPSIT_AddConfDesc((uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz);
#ifdef USE_USB_HS
USBD_CMPSIT_AddConfDesc((uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz);
#endif /* USE_USB_HS */
}
switch (pdev->tclasslist[pdev->classId].ClassType)
{
#if USBD_CMPSIT_ACTIVATE_HID == 1
case CLASS_TYPE_HID:
/* Setup Max packet sizes (for HID, no dependency on USB Speed, both HS/FS have same packet size) */
pdev->tclasslist[pdev->classId].CurrPcktSze = HID_EPIN_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 1U; /* EP1_IN */
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
/* Assign IN Endpoint */
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor */
USBD_CMPSIT_HIDMouseDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_HIDMouseDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_HID */
#if USBD_CMPSIT_ACTIVATE_MSC == 1
case CLASS_TYPE_MSC:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = MSC_MAX_FS_PACKET;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 2U; /* EP1_IN, EP1_OUT */
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor */
USBD_CMPSIT_MSCDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_MSCDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_MSC */
#if USBD_CMPSIT_ACTIVATE_CDC == 1
case CLASS_TYPE_CDC:
/* Setup default Max packet size for FS device */
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_DATA_FS_MAX_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 2U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
pdev->tclasslist[pdev->classId].Ifs[1] = (uint8_t)(idxIf + 1U);
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 3U;
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set the second IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[2];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, CDC_CMD_PACKET_SIZE);
/* Configure and Append the Descriptor */
USBD_CMPSIT_CDCDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_CDCDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_CDC */
#if USBD_CMPSIT_ACTIVATE_DFU == 1
case CLASS_TYPE_DFU:
/* Setup Max packet sizes (for DFU, no dependency on USB Speed, both HS/FS have same packet size) */
pdev->tclasslist[pdev->classId].CurrPcktSze = 64U;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 0U; /* only EP0 is used */
/* Configure and Append the Descriptor */
USBD_CMPSIT_DFUDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_DFUDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_DFU */
#if USBD_CMPSIT_ACTIVATE_RNDIS == 1
case CLASS_TYPE_RNDIS:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_RNDIS_DATA_FS_MAX_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 2U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
pdev->tclasslist[pdev->classId].Ifs[1] = (uint8_t)(idxIf + 1U);
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 3U;
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set the second IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[2];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, CDC_RNDIS_CMD_PACKET_SIZE);
/* Configure and Append the Descriptor */
USBD_CMPSIT_RNDISDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_RNDISDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_RNDIS */
#if USBD_CMPSIT_ACTIVATE_CDC_ECM == 1
case CLASS_TYPE_ECM:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_ECM_DATA_FS_MAX_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 2U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
pdev->tclasslist[pdev->classId].Ifs[1] = (uint8_t)(idxIf + 1U);
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 3U; /* EP1_IN, EP1_OUT,CMD_EP2 */
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set the second IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[2];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, CDC_ECM_CMD_PACKET_SIZE);
/* Configure and Append the Descriptor */
USBD_CMPSIT_CDC_ECMDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_CDC_ECMDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_CDC_ECM */
#if USBD_CMPSIT_ACTIVATE_AUDIO == 1
case CLASS_TYPE_AUDIO:
/* Setup Max packet sizes*/
pdev->tclasslist[pdev->classId].CurrPcktSze = USBD_AUDIO_GetEpPcktSze(pdev, 0U, 0U);
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 2U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
pdev->tclasslist[pdev->classId].Ifs[1] = (uint8_t)(idxIf + 1U);
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 1U; /* EP1_OUT*/
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
/* Assign OUT Endpoint */
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_ISOC, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor (only FS mode supported) */
USBD_CMPSIT_AUDIODesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
break;
#endif /* USBD_CMPSIT_ACTIVATE_AUDIO */
#if USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1
case CLASS_TYPE_CHID:
/* Setup Max packet sizes */
pdev->tclasslist[pdev->classId].CurrPcktSze = CUSTOM_HID_EPOUT_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 2U; /* EP1_IN, EP1_OUT */
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor */
USBD_CMPSIT_CUSTOMHIDDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_CUSTOMHIDDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_CUSTOMHID */
#if USBD_CMPSIT_ACTIVATE_VIDEO == 1
case CLASS_TYPE_VIDEO:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = UVC_ISO_FS_MPS;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 2U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
pdev->tclasslist[pdev->classId].Ifs[1] = (uint8_t)(idxIf + 1U);
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 1U; /* EP1_IN */
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
/* Assign IN Endpoint */
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_ISOC, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor */
USBD_CMPSIT_VIDEODesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_VIDEODesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_VIDEO */
#if USBD_CMPSIT_ACTIVATE_PRINTER == 1
case CLASS_TYPE_PRINTER:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = PRNT_DATA_FS_MAX_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 2U;
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Configure and Append the Descriptor */
USBD_CMPSIT_PRNTDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_PRNTDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_PRINTER */
#if USBD_CMPSIT_ACTIVATE_CCID == 1
case CLASS_TYPE_CCID:
/* Setup default Max packet size */
pdev->tclasslist[pdev->classId].CurrPcktSze = CCID_DATA_FS_MAX_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 3U;
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set the second IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[2];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, CCID_CMD_PACKET_SIZE);
/* Configure and Append the Descriptor */
USBD_CMPSIT_CCIDDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_CCIDDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_CCID */
#if USBD_CMPSIT_ACTIVATE_MTP == 1
case CLASS_TYPE_MTP:
/* Setup default Max packet sizes */
pdev->tclasslist[pdev->classId].CurrPcktSze = MTP_DATA_MAX_FS_PACKET_SIZE;
/* Find the first available interface slot and Assign number of interfaces */
idxIf = USBD_CMPSIT_FindFreeIFNbr(pdev);
pdev->tclasslist[pdev->classId].NumIf = 1U;
pdev->tclasslist[pdev->classId].Ifs[0] = idxIf;
/* Assign endpoint numbers */
pdev->tclasslist[pdev->classId].NumEps = 3U;
/* Set IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[0];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set OUT endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[1];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_BULK, pdev->tclasslist[pdev->classId].CurrPcktSze);
/* Set the second IN endpoint slot */
iEp = pdev->tclasslist[pdev->classId].EpAdd[2];
USBD_CMPSIT_AssignEp(pdev, iEp, USBD_EP_TYPE_INTR, MTP_CMD_PACKET_SIZE);
/* Configure and Append the Descriptor */
USBD_CMPSIT_MTPDesc(pdev, (uint32_t)pCmpstFSConfDesc, &CurrFSConfDescSz, (uint8_t)USBD_SPEED_FULL);
#ifdef USE_USB_HS
USBD_CMPSIT_MTPDesc(pdev, (uint32_t)pCmpstHSConfDesc, &CurrHSConfDescSz, (uint8_t)USBD_SPEED_HIGH);
#endif /* USE_USB_HS */
break;
#endif /* USBD_CMPSIT_ACTIVATE_MTP */
default:
UNUSED(idxIf);
UNUSED(iEp);
UNUSED(USBD_CMPSIT_FindFreeIFNbr);
UNUSED(USBD_CMPSIT_AssignEp);
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CMPSIT_GetFSCfgDesc
* return configuration descriptor for both FS and HS modes
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CMPSIT_GetFSCfgDesc(uint16_t *length)
{
*length = (uint16_t)CurrFSConfDescSz;
return USBD_CMPSIT_FSCfgDesc;
}
#ifdef USE_USB_HS
/**
* @brief USBD_CMPSIT_GetHSCfgDesc
* return configuration descriptor for both FS and HS modes
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CMPSIT_GetHSCfgDesc(uint16_t *length)
{
*length = (uint16_t)CurrHSConfDescSz;
return USBD_CMPSIT_HSCfgDesc;
}
#endif /* USE_USB_HS */
/**
* @brief USBD_CMPSIT_GetOtherSpeedCfgDesc
* return other speed configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CMPSIT_GetOtherSpeedCfgDesc(uint16_t *length)
{
*length = (uint16_t)CurrFSConfDescSz;
return USBD_CMPSIT_FSCfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_CMPSIT_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)(sizeof(USBD_CMPSIT_DeviceQualifierDesc));
return USBD_CMPSIT_DeviceQualifierDesc;
}
/**
* @brief USBD_CMPSIT_FindFreeIFNbr
* Find the first interface available slot
* @param pdev: device instance
* @retval The interface number to be used
*/
static uint8_t USBD_CMPSIT_FindFreeIFNbr(USBD_HandleTypeDef *pdev)
{
uint32_t idx = 0U;
/* Unroll all already activated classes */
for (uint32_t i = 0U; i < pdev->NumClasses; i++)
{
/* Unroll each class interfaces */
for (uint32_t j = 0U; j < pdev->tclasslist[i].NumIf; j++)
{
/* Increment the interface counter index */
idx++;
}
}
/* Return the first available interface slot */
return (uint8_t)idx;
}
/**
* @brief USBD_CMPSIT_AddToConfDesc
* Add a new class to the configuration descriptor
* @param pdev: device instance
* @retval none
*/
static void USBD_CMPSIT_AddConfDesc(uint32_t Conf, __IO uint32_t *pSze)
{
/* Intermediate variable to comply with MISRA-C Rule 11.3 */
USBD_ConfigDescTypeDef *ptr = (USBD_ConfigDescTypeDef *)Conf;
ptr->bLength = (uint8_t)sizeof(USBD_ConfigDescTypeDef);
ptr->bDescriptorType = USB_DESC_TYPE_CONFIGURATION;
ptr->wTotalLength = 0U;
ptr->bNumInterfaces = 0U;
ptr->bConfigurationValue = 1U;
ptr->iConfiguration = USBD_CONFIG_STR_DESC_IDX;
#if (USBD_SELF_POWERED == 1U)
ptr->bmAttributes = 0xC0U; /* bmAttributes: Self Powered according to user configuration */
#else
ptr->bmAttributes = 0x80U; /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
ptr->bMaxPower = USBD_MAX_POWER;
*pSze += sizeof(USBD_ConfigDescTypeDef);
}
/**
* @brief USBD_CMPSIT_AssignEp
* Assign and endpoint
* @param pdev: device instance
* @param Add: Endpoint address
* @param Type: Endpoint type
* @param Sze: Endpoint max packet size
* @retval none
*/
static void USBD_CMPSIT_AssignEp(USBD_HandleTypeDef *pdev, uint8_t Add, uint8_t Type, uint32_t Sze)
{
uint32_t idx = 0U;
/* Find the first available endpoint slot */
while (((idx < (pdev->tclasslist[pdev->classId]).NumEps) && \
((pdev->tclasslist[pdev->classId].Eps[idx].is_used) != 0U)))
{
/* Increment the index */
idx++;
}
/* Configure the endpoint */
pdev->tclasslist[pdev->classId].Eps[idx].add = Add;
pdev->tclasslist[pdev->classId].Eps[idx].type = Type;
pdev->tclasslist[pdev->classId].Eps[idx].size = (uint8_t)Sze;
pdev->tclasslist[pdev->classId].Eps[idx].is_used = 1U;
}
#if USBD_CMPSIT_ACTIVATE_HID == 1
/**
* @brief USBD_CMPSIT_HIDMouseDesc
* Configure and Append the HID Mouse Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_HIDMouseDesc(USBD_HandleTypeDef *pdev, uint32_t pConf,
__IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_HIDDescTypeDef *pHidMouseDesc;
/* Append HID Interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, \
(uint8_t)(pdev->tclasslist[pdev->classId].NumEps), 0x03U, 0x01U, 0x02U, 0U);
/* Append HID Functional descriptor to Configuration descriptor */
pHidMouseDesc = ((USBD_HIDDescTypeDef *)(pConf + *Sze));
pHidMouseDesc->bLength = (uint8_t)sizeof(USBD_HIDDescTypeDef);
pHidMouseDesc->bDescriptorType = HID_DESCRIPTOR_TYPE;
pHidMouseDesc->bcdHID = 0x0111U;
pHidMouseDesc->bCountryCode = 0x00U;
pHidMouseDesc->bNumDescriptors = 0x01U;
pHidMouseDesc->bHIDDescriptorType = 0x22U;
pHidMouseDesc->wItemLength = HID_MOUSE_REPORT_DESC_SIZE;
*Sze += (uint32_t)sizeof(USBD_HIDDescTypeDef);
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[0].add, USBD_EP_TYPE_INTR, HID_EPIN_SIZE, \
HID_HS_BINTERVAL, HID_FS_BINTERVAL);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_HID == 1 */
#if USBD_CMPSIT_ACTIVATE_MSC == 1
/**
* @brief USBD_CMPSIT_MSCDesc
* Configure and Append the MSC Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_MSCDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
USBD_IfDescTypeDef *pIfDesc;
USBD_EpDescTypeDef *pEpDesc;
/* Append MSC Interface descriptor */
__USBD_CMPSIT_SET_IF((pdev->tclasslist[pdev->classId].Ifs[0]), (0U), \
(uint8_t)(pdev->tclasslist[pdev->classId].NumEps), (0x08U), (0x06U), (0x50U), (0U));
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = MSC_MAX_HS_PACKET;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_MSC == 1 */
#if USBD_CMPSIT_ACTIVATE_CDC == 1
/**
* @brief USBD_CMPSIT_MSCDesc
* Configure and Append the HID Mouse Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_CDCDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_CDCHeaderFuncDescTypeDef *pHeadDesc;
static USBD_CDCCallMgmFuncDescTypeDef *pCallMgmDesc;
static USBD_CDCACMFuncDescTypeDef *pACMDesc;
static USBD_CDCUnionFuncDescTypeDef *pUnionDesc;
#if USBD_COMPOSITE_USE_IAD == 1
static USBD_IadDescTypeDef *pIadDesc;
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
#if USBD_COMPOSITE_USE_IAD == 1
pIadDesc = ((USBD_IadDescTypeDef *)(pConf + *Sze));
pIadDesc->bLength = (uint8_t)sizeof(USBD_IadDescTypeDef);
pIadDesc->bDescriptorType = USB_DESC_TYPE_IAD; /* IAD descriptor */
pIadDesc->bFirstInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pIadDesc->bInterfaceCount = 2U; /* 2 interfaces */
pIadDesc->bFunctionClass = 0x02U;
pIadDesc->bFunctionSubClass = 0x02U;
pIadDesc->bFunctionProtocol = 0x01U;
pIadDesc->iFunction = 0U; /* String Index */
*Sze += (uint32_t)sizeof(USBD_IadDescTypeDef);
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
/* Control Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 1U, 0x02, 0x02U, 0x01U, 0U);
/* Control interface headers */
pHeadDesc = ((USBD_CDCHeaderFuncDescTypeDef *)((uint32_t)pConf + *Sze));
/* Header Functional Descriptor*/
pHeadDesc->bLength = 0x05U;
pHeadDesc->bDescriptorType = 0x24U;
pHeadDesc->bDescriptorSubtype = 0x00U;
pHeadDesc->bcdCDC = 0x0110U;
*Sze += (uint32_t)sizeof(USBD_CDCHeaderFuncDescTypeDef);
/* Call Management Functional Descriptor */
pCallMgmDesc = ((USBD_CDCCallMgmFuncDescTypeDef *)((uint32_t)pConf + *Sze));
pCallMgmDesc->bLength = 0x05U;
pCallMgmDesc->bDescriptorType = 0x24U;
pCallMgmDesc->bDescriptorSubtype = 0x01U;
pCallMgmDesc->bmCapabilities = 0x00U;
pCallMgmDesc->bDataInterface = pdev->tclasslist[pdev->classId].Ifs[1];
*Sze += (uint32_t)sizeof(USBD_CDCCallMgmFuncDescTypeDef);
/* ACM Functional Descriptor*/
pACMDesc = ((USBD_CDCACMFuncDescTypeDef *)((uint32_t)pConf + *Sze));
pACMDesc->bLength = 0x04U;
pACMDesc->bDescriptorType = 0x24U;
pACMDesc->bDescriptorSubtype = 0x02U;
pACMDesc->bmCapabilities = 0x02U;
*Sze += (uint32_t)sizeof(USBD_CDCACMFuncDescTypeDef);
/* Union Functional Descriptor*/
pUnionDesc = ((USBD_CDCUnionFuncDescTypeDef *)((uint32_t)pConf + *Sze));
pUnionDesc->bLength = 0x05U;
pUnionDesc->bDescriptorType = 0x24U;
pUnionDesc->bDescriptorSubtype = 0x06U;
pUnionDesc->bMasterInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pUnionDesc->bSlaveInterface = pdev->tclasslist[pdev->classId].Ifs[1];
*Sze += (uint32_t)sizeof(USBD_CDCUnionFuncDescTypeDef);
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[2].add, \
USBD_EP_TYPE_INTR, CDC_CMD_PACKET_SIZE, CDC_HS_BINTERVAL, CDC_FS_BINTERVAL);
/* Data Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0U, 2U, 0x0A, 0U, 0U, 0U);
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_DATA_HS_MAX_PACKET_SIZE;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 2U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_CDC == 1 */
#if USBD_CMPSIT_ACTIVATE_DFU == 1
/**
* @brief USBD_CMPSIT_DFUDesc
* Configure and Append the DFU Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_DFUDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_DFUFuncDescTypeDef *pDFUFuncDesc;
uint32_t idx;
UNUSED(speed);
for (idx = 0U; idx < USBD_DFU_MAX_ITF_NUM; idx++)
{
/* Append DFU Interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], (uint8_t)idx, 0U, 0xFEU, 0x01U, 0x02U, \
(uint8_t)USBD_IDX_INTERFACE_STR + 1U + (uint8_t)idx);
}
/* Append DFU Functional descriptor to Configuration descriptor */
pDFUFuncDesc = ((USBD_DFUFuncDescTypeDef *)(pConf + *Sze));
pDFUFuncDesc->bLength = (uint8_t)sizeof(USBD_DFUFuncDescTypeDef);
pDFUFuncDesc->bDescriptorType = DFU_DESCRIPTOR_TYPE;
pDFUFuncDesc->bmAttributes = USBD_DFU_BM_ATTRIBUTES;
pDFUFuncDesc->wDetachTimeout = USBD_DFU_DETACH_TIMEOUT;
pDFUFuncDesc->wTransferSze = USBD_DFU_XFER_SIZE;
pDFUFuncDesc->bcdDFUVersion = 0x011AU;
*Sze += (uint32_t)sizeof(USBD_DFUFuncDescTypeDef);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
UNUSED(idx);
}
#endif /* USBD_CMPSIT_ACTIVATE_DFU == 1 */
#if USBD_CMPSIT_ACTIVATE_CDC_ECM == 1
/**
* @brief USBD_CMPSIT_CDC_ECMDesc
* Configure and Append the CDC_ECM Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_CDC_ECMDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_ECMFuncDescTypeDef *pFuncDesc;
static USBD_IadDescTypeDef *pIadDesc;
static USBD_CDCHeaderFuncDescTypeDef *pHeadDesc;
static USBD_CDCUnionFuncDescTypeDef *pUnionDesc;
#if USBD_COMPOSITE_USE_IAD == 1
pIadDesc = ((USBD_IadDescTypeDef *)(pConf + *Sze));
pIadDesc->bLength = (uint8_t)sizeof(USBD_IadDescTypeDef);
pIadDesc->bDescriptorType = USB_DESC_TYPE_IAD; /* IAD descriptor */
pIadDesc->bFirstInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pIadDesc->bInterfaceCount = 2U; /* 2 interfaces */
pIadDesc->bFunctionClass = 0x02U;
pIadDesc->bFunctionSubClass = 0x06U;
pIadDesc->bFunctionProtocol = 0x00U;
pIadDesc->iFunction = 0U; /* String Index */
*Sze += (uint32_t)sizeof(USBD_IadDescTypeDef);
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
/* Append ECM Interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 1U, 0x02U, 0x06U, 0U, 0U);
/* Append ECM header functional descriptor to Configuration descriptor */
pHeadDesc = ((USBD_CDCHeaderFuncDescTypeDef *)(pConf + *Sze));
pHeadDesc->bLength = (uint8_t)sizeof(USBD_CDCHeaderFuncDescTypeDef);
pHeadDesc->bDescriptorType = USBD_FUNC_DESCRIPTOR_TYPE;
pHeadDesc->bDescriptorSubtype = 0x00U;
pHeadDesc->bcdCDC = 0x1000U;
*Sze += (uint32_t)sizeof(USBD_CDCHeaderFuncDescTypeDef);
/* Append ECM functional descriptor to Configuration descriptor */
pFuncDesc = ((USBD_ECMFuncDescTypeDef *)(pConf + *Sze));
pFuncDesc->bFunctionLength = (uint8_t)sizeof(USBD_ECMFuncDescTypeDef);
pFuncDesc->bDescriptorType = USBD_FUNC_DESCRIPTOR_TYPE;
pFuncDesc->bDescriptorSubType = USBD_DESC_SUBTYPE_ACM;
pFuncDesc->iMacAddress = CDC_ECM_MAC_STRING_INDEX;
pFuncDesc->bEthernetStatistics3 = CDC_ECM_ETH_STATS_BYTE3;
pFuncDesc->bEthernetStatistics2 = CDC_ECM_ETH_STATS_BYTE2;
pFuncDesc->bEthernetStatistics1 = CDC_ECM_ETH_STATS_BYTE1;
pFuncDesc->bEthernetStatistics0 = CDC_ECM_ETH_STATS_BYTE0;
pFuncDesc->wMaxSegmentSize = CDC_ECM_ETH_MAX_SEGSZE;
pFuncDesc->bNumberMCFiltes = CDC_ECM_ETH_NBR_MACFILTERS;
pFuncDesc->bNumberPowerFiltes = CDC_ECM_ETH_NBR_PWRFILTERS;
*Sze += (uint32_t)sizeof(USBD_ECMFuncDescTypeDef);
/* Append ECM Union functional descriptor to Configuration descriptor */
pUnionDesc = ((USBD_CDCUnionFuncDescTypeDef *)(pConf + *Sze));
pUnionDesc->bLength = (uint8_t)sizeof(USBD_CDCUnionFuncDescTypeDef);
pUnionDesc->bDescriptorType = 0x24U;
pUnionDesc->bDescriptorSubtype = 0x06U;
pUnionDesc->bMasterInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pUnionDesc->bSlaveInterface = pdev->tclasslist[pdev->classId].Ifs[1];
*Sze += (uint32_t)sizeof(USBD_CDCUnionFuncDescTypeDef);
/* Append ECM Communication IN Endpoint Descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[2].add, USBD_EP_TYPE_INTR, CDC_ECM_CMD_PACKET_SIZE, \
CDC_ECM_HS_BINTERVAL, CDC_ECM_FS_BINTERVAL);
/* Append ECM Data class interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0U, 2U, 0x0AU, 0U, 0U, 0U);
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_ECM_DATA_HS_MAX_PACKET_SIZE;
}
/* Append ECM OUT Endpoint Descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (CDC_ECM_HS_BINTERVAL), (CDC_ECM_FS_BINTERVAL));
/* Append ECM IN Endpoint Descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (CDC_ECM_HS_BINTERVAL), (CDC_ECM_FS_BINTERVAL));
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 2U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_CDC_ECM */
#if USBD_CMPSIT_ACTIVATE_AUDIO == 1
/**
* @brief USBD_CMPSIT_AUDIODesc
* Configure and Append the AUDIO Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_AUDIODesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_IadDescTypeDef *pIadDesc;
UNUSED(speed);
/* Append AUDIO Interface descriptor to Configuration descriptor */
USBD_SpeakerIfDescTypeDef *pSpIfDesc;
USBD_SpeakerInDescTypeDef *pSpInDesc;
USBD_SpeakerFeatureDescTypeDef *pSpFDesc;
USBD_SpeakerOutDescTypeDef *pSpOutDesc;
USBD_SpeakerStreamIfDescTypeDef *pSpStrDesc;
USBD_SpeakerIIIFormatIfDescTypeDef *pSpIIIDesc;
USBD_SpeakerEndDescTypeDef *pSpEpDesc;
USBD_SpeakerEndStDescTypeDef *pSpEpStDesc;
#if USBD_COMPOSITE_USE_IAD == 1
pIadDesc = ((USBD_IadDescTypeDef *)(pConf + *Sze));
pIadDesc->bLength = (uint8_t)sizeof(USBD_IadDescTypeDef);
pIadDesc->bDescriptorType = USB_DESC_TYPE_IAD; /* IAD descriptor */
pIadDesc->bFirstInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pIadDesc->bInterfaceCount = 2U; /* 2 interfaces */
pIadDesc->bFunctionClass = USB_DEVICE_CLASS_AUDIO;
pIadDesc->bFunctionSubClass = AUDIO_SUBCLASS_AUDIOCONTROL;
pIadDesc->bFunctionProtocol = AUDIO_PROTOCOL_UNDEFINED;
pIadDesc->iFunction = 0U; /* String Index */
*Sze += (uint32_t)sizeof(USBD_IadDescTypeDef);
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
/* Append AUDIO Interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 0U, USB_DEVICE_CLASS_AUDIO, \
AUDIO_SUBCLASS_AUDIOCONTROL, AUDIO_PROTOCOL_UNDEFINED, 0U);
/* Append AUDIO USB Speaker Class-specific AC Interface descriptor to Configuration descriptor */
pSpIfDesc = ((USBD_SpeakerIfDescTypeDef *)(pConf + *Sze));
pSpIfDesc->bLength = (uint8_t)sizeof(USBD_IfDescTypeDef);
pSpIfDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpIfDesc->bDescriptorSubtype = AUDIO_CONTROL_HEADER;
pSpIfDesc->bcdADC = 0x0100U;
pSpIfDesc->wTotalLength = 0x0027U;
pSpIfDesc->bInCollection = 0x01U;
pSpIfDesc->baInterfaceNr = 0x01U;
*Sze += (uint32_t)sizeof(USBD_IfDescTypeDef);
/* Append USB Speaker Input Terminal Descriptor to Configuration descriptor*/
pSpInDesc = ((USBD_SpeakerInDescTypeDef *)(pConf + *Sze));
pSpInDesc->bLength = (uint8_t)sizeof(USBD_SpeakerInDescTypeDef);
pSpInDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpInDesc->bDescriptorSubtype = AUDIO_CONTROL_INPUT_TERMINAL;
pSpInDesc->bTerminalID = 0x01U;
pSpInDesc->wTerminalType = 0x0101U;
pSpInDesc->bAssocTerminal = 0x00U;
pSpInDesc->bNrChannels = 0x01U;
pSpInDesc->wChannelConfig = 0x0000U;
pSpInDesc->iChannelNames = 0x00U;
pSpInDesc->iTerminal = 0x00U;
*Sze += (uint32_t)sizeof(USBD_SpeakerInDescTypeDef);
/*Append USB Speaker Audio Feature Unit Descriptor to Configuration descriptor */
pSpFDesc = ((USBD_SpeakerFeatureDescTypeDef *)(pConf + *Sze));
pSpFDesc->bLength = (uint8_t)sizeof(USBD_SpeakerFeatureDescTypeDef);
pSpFDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpFDesc->bDescriptorSubtype = AUDIO_CONTROL_FEATURE_UNIT;
pSpFDesc->bUnitID = AUDIO_OUT_STREAMING_CTRL;
pSpFDesc->bSourceID = 0x01U;
pSpFDesc->bControlSize = 0x01U;
pSpFDesc->bmaControls = AUDIO_CONTROL_MUTE;
pSpFDesc->iTerminal = 0x00U;
*Sze += (uint32_t)sizeof(USBD_SpeakerFeatureDescTypeDef);
/*Append USB Speaker Output Terminal Descriptor to Configuration descriptor*/
pSpOutDesc = ((USBD_SpeakerOutDescTypeDef *)(pConf + *Sze));
pSpOutDesc->bLength = (uint8_t)sizeof(USBD_SpeakerOutDescTypeDef);
pSpOutDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpOutDesc->bDescriptorSubtype = AUDIO_CONTROL_OUTPUT_TERMINAL;
pSpOutDesc->bTerminalID = 0x03U;
pSpOutDesc->wTerminalType = 0x0301U;
pSpOutDesc->bAssocTerminal = 0x00U;
pSpOutDesc->bSourceID = 0x02U;
pSpOutDesc->iTerminal = 0x00U;
*Sze += (uint32_t)sizeof(USBD_SpeakerOutDescTypeDef);
/* USB Speaker Standard AS Interface Descriptor - Audio Streaming Zero Bandwidth */
/* Interface 1, Alternate Setting 0*/
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0U, 0U, USB_DEVICE_CLASS_AUDIO, \
AUDIO_SUBCLASS_AUDIOSTREAMING, AUDIO_PROTOCOL_UNDEFINED, 0U);
/* USB Speaker Standard AS Interface Descriptor -Audio Streaming Operational */
/* Interface 1, Alternate Setting 1*/
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0x01U, 0x01U, USB_DEVICE_CLASS_AUDIO, \
AUDIO_SUBCLASS_AUDIOSTREAMING, AUDIO_PROTOCOL_UNDEFINED, 0U);
/* USB Speaker Audio Streaming Interface Descriptor */
pSpStrDesc = ((USBD_SpeakerStreamIfDescTypeDef *)(pConf + *Sze));
pSpStrDesc->bLength = (uint8_t)sizeof(USBD_SpeakerStreamIfDescTypeDef);
pSpStrDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpStrDesc->bDescriptorSubtype = AUDIO_STREAMING_GENERAL;
pSpStrDesc->bTerminalLink = 0x01U;
pSpStrDesc->bDelay = 0x01U;
pSpStrDesc->wFormatTag = 0x0001U;
*Sze += (uint32_t)sizeof(USBD_SpeakerStreamIfDescTypeDef);
/* USB Speaker Audio Type III Format Interface Descriptor */
pSpIIIDesc = ((USBD_SpeakerIIIFormatIfDescTypeDef *)(pConf + *Sze));
pSpIIIDesc->bLength = (uint8_t)sizeof(USBD_SpeakerIIIFormatIfDescTypeDef);
pSpIIIDesc->bDescriptorType = AUDIO_INTERFACE_DESCRIPTOR_TYPE;
pSpIIIDesc->bDescriptorSubtype = AUDIO_STREAMING_FORMAT_TYPE;
pSpIIIDesc->bFormatType = AUDIO_FORMAT_TYPE_I;
pSpIIIDesc->bNrChannels = 0x02U;
pSpIIIDesc->bSubFrameSize = 0x02U;
pSpIIIDesc->bBitResolution = 16U;
pSpIIIDesc->bSamFreqType = 1U;
pSpIIIDesc->tSamFreq2 = 0x80U;
pSpIIIDesc->tSamFreq1 = 0xBBU;
pSpIIIDesc->tSamFreq0 = 0x00U;
*Sze += (uint32_t)sizeof(USBD_SpeakerIIIFormatIfDescTypeDef);
/* Endpoint 1 - Standard Descriptor */
pSpEpDesc = ((USBD_SpeakerEndDescTypeDef *)(pConf + *Sze));
pSpEpDesc->bLength = 0x09U;
pSpEpDesc->bDescriptorType = USB_DESC_TYPE_ENDPOINT;
pSpEpDesc->bEndpointAddress = pdev->tclasslist[pdev->classId].Eps[0].add;
pSpEpDesc->bmAttributes = USBD_EP_TYPE_ISOC;
pSpEpDesc->wMaxPacketSize = (uint16_t)USBD_AUDIO_GetEpPcktSze(pdev, 0U, 0U);
pSpEpDesc->bInterval = 0x01U;
pSpEpDesc->bRefresh = 0x00U;
pSpEpDesc->bSynchAddress = 0x00U;
*Sze += 0x09U;
/* Endpoint - Audio Streaming Descriptor*/
pSpEpStDesc = ((USBD_SpeakerEndStDescTypeDef *)(pConf + *Sze));
pSpEpStDesc->bLength = (uint8_t)sizeof(USBD_SpeakerEndStDescTypeDef);
pSpEpStDesc->bDescriptorType = AUDIO_ENDPOINT_DESCRIPTOR_TYPE;
pSpEpStDesc->bDescriptor = AUDIO_ENDPOINT_GENERAL;
pSpEpStDesc->bmAttributes = 0x00U;
pSpEpStDesc->bLockDelayUnits = 0x00U;
pSpEpStDesc->wLockDelay = 0x0000U;
*Sze += (uint32_t)sizeof(USBD_SpeakerEndStDescTypeDef);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 2U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_AUDIO */
#if USBD_CMPSIT_ACTIVATE_RNDIS == 1
/**
* @brief USBD_CMPSIT_MSCDesc
* Configure and Append the CDC_RNDIS Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_RNDISDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_CDCHeaderFuncDescTypeDef *pHeadDesc;
static USBD_CDCCallMgmFuncDescTypeDef *pCallMgmDesc;
static USBD_CDCACMFuncDescTypeDef *pACMDesc;
static USBD_CDCUnionFuncDescTypeDef *pUnionDesc;
static USBD_IadDescTypeDef *pIadDesc;
#if USBD_COMPOSITE_USE_IAD == 1
pIadDesc = ((USBD_IadDescTypeDef *)(pConf + *Sze));
pIadDesc->bLength = (uint8_t)sizeof(USBD_IadDescTypeDef);
pIadDesc->bDescriptorType = USB_DESC_TYPE_IAD; /* IAD descriptor */
pIadDesc->bFirstInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pIadDesc->bInterfaceCount = 2U; /* 2 interfaces */
pIadDesc->bFunctionClass = 0xE0U;
pIadDesc->bFunctionSubClass = 0x01U;
pIadDesc->bFunctionProtocol = 0x03U;
pIadDesc->iFunction = 0U; /* String Index */
*Sze += (uint32_t)sizeof(USBD_IadDescTypeDef);
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
/* Control Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 1U, 0x02, 0x02, 0xFF, 0U);
/* Control interface headers */
pHeadDesc = ((USBD_CDCHeaderFuncDescTypeDef *)(pConf + *Sze));
/* Header Functional Descriptor*/
pHeadDesc->bLength = (uint8_t)sizeof(USBD_CDCHeaderFuncDescTypeDef);
pHeadDesc->bDescriptorType = 0x24U;
pHeadDesc->bDescriptorSubtype = 0x00U;
pHeadDesc->bcdCDC = 0x0110U;
*Sze += (uint32_t)sizeof(USBD_CDCHeaderFuncDescTypeDef);
/* Call Management Functional Descriptor*/
pCallMgmDesc = ((USBD_CDCCallMgmFuncDescTypeDef *)(pConf + *Sze));
pCallMgmDesc->bLength = (uint8_t)sizeof(USBD_CDCCallMgmFuncDescTypeDef);
pCallMgmDesc->bDescriptorType = 0x24U;
pCallMgmDesc->bDescriptorSubtype = 0x01U;
pCallMgmDesc->bmCapabilities = 0x00U;
pCallMgmDesc->bDataInterface = pdev->tclasslist[pdev->classId].Ifs[1];
*Sze += (uint32_t)sizeof(USBD_CDCCallMgmFuncDescTypeDef);
/* ACM Functional Descriptor*/
pACMDesc = ((USBD_CDCACMFuncDescTypeDef *)(pConf + *Sze));
pACMDesc->bLength = (uint8_t)sizeof(USBD_CDCACMFuncDescTypeDef);
pACMDesc->bDescriptorType = 0x24U;
pACMDesc->bDescriptorSubtype = 0x02U;
pACMDesc->bmCapabilities = 0x00U;
*Sze += (uint32_t)sizeof(USBD_CDCACMFuncDescTypeDef);
/* Union Functional Descriptor*/
pUnionDesc = ((USBD_CDCUnionFuncDescTypeDef *)(pConf + *Sze));
pUnionDesc->bLength = (uint8_t)sizeof(USBD_CDCUnionFuncDescTypeDef);
pUnionDesc->bDescriptorType = 0x24U;
pUnionDesc->bDescriptorSubtype = 0x06U;
pUnionDesc->bMasterInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pUnionDesc->bSlaveInterface = pdev->tclasslist[pdev->classId].Ifs[1];
*Sze += (uint32_t)sizeof(USBD_CDCUnionFuncDescTypeDef);
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[2].add, USBD_EP_TYPE_INTR, \
CDC_RNDIS_CMD_PACKET_SIZE, CDC_RNDIS_HS_BINTERVAL, CDC_RNDIS_FS_BINTERVAL);
/* Data Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0U, 2U, 0x0AU, 0x00U, 0x00U, 0U);
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = CDC_RNDIS_DATA_HS_MAX_PACKET_SIZE;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 2U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_RNDIS == 1 */
#if USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1
/**
* @brief USBD_CMPSIT_CUSTOMHIDDesc
* Configure and Append the MSC Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_CUSTOMHIDDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_DescTypeDef *pDesc;
/* Control Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 2U, 3U, 0U, 0U, 0U);
/* Descriptor of CUSTOM_HID */
pDesc = ((USBD_DescTypeDef *)((uint32_t)pConf + *Sze));
pDesc->bLength = 0x09U;
pDesc->bDescriptorTypeCHID = CUSTOM_HID_DESCRIPTOR_TYPE;
pDesc->bcdCUSTOM_HID = 0x0111U;
pDesc->bCountryCode = 0x00U;
pDesc->bNumDescriptors = 0x01U;
pDesc->bDescriptorType = 0x22U;
pDesc->wItemLength = USBD_CUSTOM_HID_REPORT_DESC_SIZE;
*Sze += (uint32_t)sizeof(USBD_DescTypeDef);
/* Descriptor of Custom HID endpoints */
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[0].add, \
USBD_EP_TYPE_INTR, CUSTOM_HID_EPIN_SIZE, CUSTOM_HID_HS_BINTERVAL, CUSTOM_HID_FS_BINTERVAL);
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[1].add, \
USBD_EP_TYPE_INTR, CUSTOM_HID_EPIN_SIZE, CUSTOM_HID_HS_BINTERVAL, CUSTOM_HID_FS_BINTERVAL);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_CUSTOMHID == 1U */
#if USBD_CMPSIT_ACTIVATE_VIDEO == 1
/**
* @brief USBD_CMPSIT_VIDEODesc
* Configure and Append the VIDEO Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_VIDEODesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
__ALIGN_BEGIN static uint8_t usbd_uvc_guid[16] __ALIGN_END = {DBVAL(UVC_UNCOMPRESSED_GUID), 0x00, 0x00, 0x10,
0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71
};
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
static USBD_IfDescTypeDef *pIfDesc;
static USBD_IadDescTypeDef *pIadDesc;
/* Append AUDIO Interface descriptor to Configuration descriptor */
USBD_specificVCInDescTypeDef *pSVCInDesc;
USBD_InputTerminalDescTypeDef *pInTerDesc;
USBD_OutputTerminalDescTypeDef *pOuTerDesc;
USBD_ClassSpecificVsHeaderDescTypeDef *pSpHeaDesc;
USBD_PayloadFormatDescTypeDef *pPayForDesc;
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
USBD_ColorMatchingDescTypeDef *pColMaDesc;
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
USBD_StandardVCDataEPDescTypeDef *pSVCDEP;
USBD_VIDEO_VSFrameDescTypeDef *pClassSpecVS;
#if USBD_COMPOSITE_USE_IAD == 1
pIadDesc = ((USBD_IadDescTypeDef *)(pConf + *Sze));
pIadDesc->bLength = (uint8_t)sizeof(USBD_IadDescTypeDef);
pIadDesc->bDescriptorType = USB_DESC_TYPE_IAD; /* IAD descriptor */
pIadDesc->bFirstInterface = pdev->tclasslist[pdev->classId].Ifs[0];
pIadDesc->bInterfaceCount = 2U; /* 2 interfaces */
pIadDesc->bFunctionClass = UVC_CC_VIDEO;
pIadDesc->bFunctionSubClass = SC_VIDEO_INTERFACE_COLLECTION;
pIadDesc->bFunctionProtocol = PC_PROTOCOL_UNDEFINED;
pIadDesc->iFunction = 0U; /* String Index */
*Sze += (uint32_t)sizeof(USBD_IadDescTypeDef);
#endif /* USBD_COMPOSITE_USE_IAD == 1 */
/* Append VIDEO Interface descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 0U, UVC_CC_VIDEO, 1U, PC_PROTOCOL_UNDEFINED, 0U);
/* Append Class-specific VC Interface Descriptor to Configuration descriptor*/
pSVCInDesc = ((USBD_specificVCInDescTypeDef *)(pConf + *Sze));
pSVCInDesc->bLength = (uint8_t)sizeof(USBD_specificVCInDescTypeDef);
pSVCInDesc->bDescriptorType = CS_INTERFACE;
pSVCInDesc->bDescriptorSubtype = VC_HEADER;
pSVCInDesc->bcdUVC = UVC_VERSION;
pSVCInDesc->wTotalLength = 0x001EU;
pSVCInDesc->dwClockFrequency = 0x02DC6C00U;
pSVCInDesc->baInterfaceNr = 0x01U;
pSVCInDesc->iTerminal = 0x01U;
*Sze += (uint32_t)sizeof(USBD_specificVCInDescTypeDef);
/*Append Input Terminal Descriptor to Configuration descriptor */
pInTerDesc = ((USBD_InputTerminalDescTypeDef *)(pConf + *Sze));
pInTerDesc->bLength = (uint8_t)sizeof(USBD_InputTerminalDescTypeDef);
pInTerDesc->bDescriptorType = CS_INTERFACE;
pInTerDesc->bDescriptorSubtype = VC_INPUT_TERMINAL;
pInTerDesc->bTerminalID = 0x01U;
pInTerDesc->wTerminalType = ITT_VENDOR_SPECIFIC;
pInTerDesc->bAssocTerminal = 0x00U;
pInTerDesc->iTerminal = 0x00U;
*Sze += (uint32_t)sizeof(USBD_InputTerminalDescTypeDef);
/* Append Output Terminal Descriptor to Configuration descriptor */
pOuTerDesc = ((USBD_OutputTerminalDescTypeDef *)(pConf + *Sze));
pOuTerDesc->bLength = (uint8_t)sizeof(USBD_OutputTerminalDescTypeDef);
pOuTerDesc->bDescriptorType = CS_INTERFACE;
pOuTerDesc->bDescriptorSubtype = VC_OUTPUT_TERMINAL;
pOuTerDesc->bTerminalID = 0x02U;
pOuTerDesc->wTerminalType = TT_STREAMING;
pOuTerDesc->bAssocTerminal = 0x00U;
pOuTerDesc->bSourceID = 0x01U;
pOuTerDesc->iTerminal = 0x00U;
*Sze += (uint32_t)sizeof(USBD_OutputTerminalDescTypeDef);
/* Standard VS (Video Streaming) Interface Descriptor */
/* Interface 1, Alternate Setting 0 = Zero Bandwidth*/
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[1], 0U, 0U, UVC_CC_VIDEO, \
SC_VIDEOSTREAMING, PC_PROTOCOL_UNDEFINED, 0U);
/* Append Class-specific VS Header Descriptor (Input) to Configuration descriptor */
pSpHeaDesc = ((USBD_ClassSpecificVsHeaderDescTypeDef *)(pConf + *Sze));
pSpHeaDesc->bLength = (uint8_t)sizeof(USBD_ClassSpecificVsHeaderDescTypeDef);
pSpHeaDesc->bDescriptorType = CS_INTERFACE;
pSpHeaDesc->bDescriptorSubtype = VS_INPUT_HEADER;
pSpHeaDesc->bNumFormats = 0x4D01U;
pSpHeaDesc->bVideoControlSize = 0x00U;
pSpHeaDesc->bEndPointAddress = UVC_IN_EP;
pSpHeaDesc->bmInfo = 0x00U;
pSpHeaDesc->bTerminalLink = 0x02U;
pSpHeaDesc->bStillCaptureMethod = 0x00U;
pSpHeaDesc->bTriggerSupport = 0x00U;
pSpHeaDesc->bTriggerUsage = 0x00U;
pSpHeaDesc->bControlSize = 0x01U;
pSpHeaDesc->bmaControls = 0x00U;
*Sze += (uint32_t)sizeof(USBD_ClassSpecificVsHeaderDescTypeDef);
/* Append Payload Format Descriptor to Configuration descriptor */
pPayForDesc = ((USBD_PayloadFormatDescTypeDef *)(pConf + *Sze));
pPayForDesc->bLength = (uint8_t)sizeof(USBD_PayloadFormatDescTypeDef);
pPayForDesc->bDescriptorType = CS_INTERFACE;
pPayForDesc->bDescriptorSubType = VS_FORMAT_SUBTYPE;
pPayForDesc->bFormatIndex = 0x01U;
pPayForDesc->bNumFrameDescriptor = 0x01U;
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
(void)USBD_memcpy(pPayForDesc->pGiudFormat, usbd_uvc_guid, 16);
pPayForDesc->bBitsPerPixel = UVC_BITS_PER_PIXEL;
#else
pPayForDesc->bmFlags = 0x01U;
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
pPayForDesc->bDefaultFrameIndex = 0x01U;
pPayForDesc->bAspectRatioX = 0x00U;
pPayForDesc->bAspectRatioY = 0x00U;
pPayForDesc->bInterlaceFlags = 0x00U;
pPayForDesc->bCopyProtect = 0x00U;
*Sze += (uint32_t)sizeof(USBD_PayloadFormatDescTypeDef);
/* Append Class-specific VS (Video Streaming) Frame Descriptor to Configuration descriptor */
pClassSpecVS = ((USBD_VIDEO_VSFrameDescTypeDef *)(pConf + *Sze));
pClassSpecVS->bLength = (uint8_t)sizeof(USBD_VIDEO_VSFrameDescTypeDef);
pClassSpecVS->bDescriptorType = CS_INTERFACE;
pClassSpecVS->bDescriptorSubType = VS_FRAME_SUBTYPE;
pClassSpecVS->bFrameIndex = 0x01U;
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
pClassSpecVS->bmCapabilities = 0x00U;
#else
pClassSpecVS->bmCapabilities = 0x02U;
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
pClassSpecVS->wWidth = UVC_WIDTH;
pClassSpecVS->wHeight = UVC_HEIGHT;
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pClassSpecVS->dwMinBitRate = UVC_MIN_BIT_RATE(UVC_CAM_FPS_HS);
pClassSpecVS->dwMaxBitRate = UVC_MAX_BIT_RATE(UVC_CAM_FPS_HS);
pClassSpecVS->dwDefaultFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_HS);
pClassSpecVS->dwMinFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_HS);
}
else
{
pClassSpecVS->dwMinBitRate = UVC_MIN_BIT_RATE(UVC_CAM_FPS_FS);
pClassSpecVS->dwMaxBitRate = UVC_MAX_BIT_RATE(UVC_CAM_FPS_FS);
pClassSpecVS->dwDefaultFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
pClassSpecVS->dwMinFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
}
pClassSpecVS->dwMaxVideoFrameBufSize = UVC_MAX_FRAME_SIZE;
pClassSpecVS->bFrameIntervalType = 0x01U;
*Sze += (uint32_t)sizeof(USBD_VIDEO_VSFrameDescTypeDef);
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
/* Append Color Matching Descriptor to Configuration descriptor */
pColMaDesc = ((USBD_ColorMatchingDescTypeDef *)(pConf + *Sze));
pColMaDesc->bLength = (uint8_t)sizeof(USBD_ColorMatchingDescTypeDef);
pColMaDesc->bDescriptorType = CS_INTERFACE;
pColMaDesc->bDescriptorSubType = VS_COLORFORMAT;
pColMaDesc->bColorPrimarie = UVC_COLOR_PRIMARIE;
pColMaDesc->bTransferCharacteristics = UVC_TFR_CHARACTERISTICS;
pColMaDesc->bMatrixCoefficients = UVC_MATRIX_COEFFICIENTS;
*Sze += (uint32_t)sizeof(USBD_ColorMatchingDescTypeDef);
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
/* USB Standard VS Interface Descriptor - data transfer mode */
/* Interface 1, Alternate Setting 1*/
__USBD_CMPSIT_SET_IF(1U, 1U, 1U, UVC_CC_VIDEO, SC_VIDEOSTREAMING, PC_PROTOCOL_UNDEFINED, 0U);
/* Standard VS (Video Streaming) data Endpoint */
pSVCDEP = ((USBD_StandardVCDataEPDescTypeDef *)(pConf + *Sze));
pSVCDEP->bLength = (uint8_t)sizeof(USBD_StandardVCDataEPDescTypeDef);
pSVCDEP->bDescriptorType = USB_DESC_TYPE_ENDPOINT;
pSVCDEP->bEndpointAddress = UVC_IN_EP;
pSVCDEP->bmAttributes = 0x05U;
pSVCDEP->bInterval = 0x01U;
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pSVCDEP->wMaxPacketSize = UVC_ISO_HS_MPS;
}
else
{
pSVCDEP->wMaxPacketSize = UVC_ISO_FS_MPS;
}
*Sze += (uint32_t)sizeof(USBD_StandardVCDataEPDescTypeDef);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 2U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_VIDEO == 1 */
#if USBD_CMPSIT_ACTIVATE_PRINTER == 1
/**
* @brief USBD_CMPSIT_PRINTERDesc
* Configure and Append the PRINTER Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_PRNTDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
/* Control Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 0x02, 0x07, 0x01U, USB_PRNT_BIDIRECTIONAL, 0U);
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = PRNT_DATA_HS_MAX_PACKET_SIZE;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_PRINTER == 1 */
#if USBD_CMPSIT_ACTIVATE_CCID == 1
/**
* @brief USBD_CMPSIT_CCIDDesc
* Configure and Append the CCID Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_CCIDDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
static USBD_IfDescTypeDef *pIfDesc;
static USBD_EpDescTypeDef *pEpDesc;
static USBD_CCID_DescTypeDef *pDesc;
/* Control Interface Descriptor */
__USBD_CMPSIT_SET_IF(pdev->tclasslist[pdev->classId].Ifs[0], 0U, 0x03, 0x0BU, 0U, 0U, 0U);
/* Control interface headers */
pDesc = ((USBD_CCID_DescTypeDef *)((uint32_t)pConf + *Sze));
/* Device Descriptor */
pDesc->bLength = 0x36U;
pDesc->bDescriptorType = 0x21U;
pDesc->bcdCCID = 0x0110U;
pDesc->bMaxSlotIndex = 0x00U;
pDesc->bVoltageSupport = CCID_VOLTAGE_SUPP;
pDesc->dwProtocols = USBD_CCID_PROTOCOL;
pDesc->dwDefaultClock = USBD_CCID_DEFAULT_CLOCK_FREQ;
pDesc->dwMaximumClock = USBD_CCID_MAX_CLOCK_FREQ;
pDesc->bNumClockSupported = 0x00U;
pDesc->dwDataRate = USBD_CCID_DEFAULT_DATA_RATE;
pDesc->dwMaxDataRate = USBD_CCID_MAX_DATA_RATE;
pDesc->bNumDataRatesSupported = 0x35U;
pDesc->dwMaxIFSD = USBD_CCID_MAX_INF_FIELD_SIZE;
pDesc->dwSynchProtocols = 0U;
pDesc->dwMechanical = 0U;
pDesc->dwFeatures = 0x000104BAU;
pDesc->dwMaxCCIDMessageLength = CCID_MAX_BLOCK_SIZE_HEADER;
pDesc->bClassGetResponse = 0U;
pDesc->bClassEnvelope = 0U;
pDesc->wLcdLayout = 0U;
pDesc->bPINSupport = 0x03U;
pDesc->bMaxCCIDBusySlots = 0x01U;
*Sze += (uint32_t)sizeof(USBD_CCID_DescTypeDef);
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = CCID_DATA_HS_MAX_PACKET_SIZE;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), \
(USBD_EP_TYPE_BULK), (pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[2].add, \
USBD_EP_TYPE_INTR, CCID_CMD_PACKET_SIZE, CCID_CMD_HS_BINTERVAL, CCID_CMD_FS_BINTERVAL);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_CCID == 1 */
#if USBD_CMPSIT_ACTIVATE_MTP == 1
/**
* @brief USBD_CMPSIT_MTPDesc
* Configure and Append the MTP Descriptor
* @param pdev: device instance
* @param pConf: Configuration descriptor pointer
* @param Sze: pointer to the current configuration descriptor size
* @retval None
*/
static void USBD_CMPSIT_MTPDesc(USBD_HandleTypeDef *pdev, uint32_t pConf, __IO uint32_t *Sze, uint8_t speed)
{
USBD_IfDescTypeDef *pIfDesc;
USBD_EpDescTypeDef *pEpDesc;
/* Append MTP Interface descriptor */
__USBD_CMPSIT_SET_IF((pdev->tclasslist[pdev->classId].Ifs[0]), (0U), \
(uint8_t)(pdev->tclasslist[pdev->classId].NumEps), USB_MTP_INTRERFACE_CLASS, \
USB_MTP_INTRERFACE_SUB_CLASS, USB_MTP_INTRERFACE_PROTOCOL, (0U));
if (speed == (uint8_t)USBD_SPEED_HIGH)
{
pdev->tclasslist[pdev->classId].CurrPcktSze = MTP_DATA_MAX_HS_PACKET_SIZE;
}
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[0].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP((pdev->tclasslist[pdev->classId].Eps[1].add), (USBD_EP_TYPE_BULK), \
(pdev->tclasslist[pdev->classId].CurrPcktSze), (0U), (0U));
/* Append Endpoint descriptor to Configuration descriptor */
__USBD_CMPSIT_SET_EP(pdev->tclasslist[pdev->classId].Eps[2].add, \
USBD_EP_TYPE_INTR, MTP_CMD_PACKET_SIZE, MTP_HS_BINTERVAL, MTP_FS_BINTERVAL);
/* Update Config Descriptor and IAD descriptor */
((USBD_ConfigDescTypeDef *)pConf)->bNumInterfaces += 1U;
((USBD_ConfigDescTypeDef *)pConf)->wTotalLength = (uint16_t)(*Sze);
}
#endif /* USBD_CMPSIT_ACTIVATE_MTP == 1 */
/**
* @brief USBD_CMPSIT_SetClassID
* Find and set the class ID relative to selected class type and instance
* @param pdev: device instance
* @param Class: Class type, can be CLASS_TYPE_NONE if requested to find class from setup request
* @param Instance: Instance number of the class (0 if first/unique instance, >0 otherwise)
* @retval The Class ID, The pdev->classId is set with the value of the selected class ID.
*/
uint32_t USBD_CMPSIT_SetClassID(USBD_HandleTypeDef *pdev, USBD_CompositeClassTypeDef Class, uint32_t Instance)
{
uint32_t idx;
uint32_t inst = 0U;
/* Unroll all already activated classes */
for (idx = 0U; idx < pdev->NumClasses; idx++)
{
/* Check if the class correspond to the requested type and if it is active */
if (((USBD_CompositeClassTypeDef)(pdev->tclasslist[idx].ClassType) == Class) &&
((pdev->tclasslist[idx].Active) == 1U))
{
if (inst == Instance)
{
/* Set the new class ID */
pdev->classId = idx;
/* Return the class ID value */
return (idx);
}
else
{
/* Increment instance index and look for next instance */
inst++;
}
}
}
/* No class found, return 0xFF */
return 0xFFU;
}
/**
* @brief USBD_CMPSIT_GetClassID
* Returns the class ID relative to selected class type and instance
* @param pdev: device instance
* @param Class: Class type, can be CLASS_TYPE_NONE if requested to find class from setup request
* @param Instance: Instance number of the class (0 if first/unique instance, >0 otherwise)
* @retval The Class ID (this function does not set the pdev->classId field.
*/
uint32_t USBD_CMPSIT_GetClassID(USBD_HandleTypeDef *pdev, USBD_CompositeClassTypeDef Class, uint32_t Instance)
{
uint32_t idx;
uint32_t inst = 0U;
/* Unroll all already activated classes */
for (idx = 0U; idx < pdev->NumClasses; idx++)
{
/* Check if the class correspond to the requested type and if it is active */
if (((USBD_CompositeClassTypeDef)(pdev->tclasslist[idx].ClassType) == Class) &&
((pdev->tclasslist[idx].Active) == 1U))
{
if (inst == Instance)
{
/* Return the class ID value */
return (idx);
}
else
{
/* Increment instance index and look for next instance */
inst++;
}
}
}
/* No class found, return 0xFF */
return 0xFFU;
}
/**
* @brief USBD_CMPST_ClearConfDesc
* Reset the configuration descriptor
* @param pdev: device instance (reserved for future use)
* @retval Status.
*/
uint8_t USBD_CMPST_ClearConfDesc(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
/* Reset the configuration descriptor pointer to default value and its size to zero */
pCmpstFSConfDesc = USBD_CMPSIT_FSCfgDesc;
CurrFSConfDescSz = 0U;
#ifdef USE_USB_HS
pCmpstHSConfDesc = USBD_CMPSIT_HSCfgDesc;
CurrHSConfDescSz = 0U;
#endif /* USE_USB_HS */
/* All done, can't fail */
return (uint8_t)USBD_OK;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID\Inc\usbd_customhid.h | /**
******************************************************************************
* @file usbd_customhid.h
* @author MCD Application Team
* @brief header file for the usbd_customhid.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_CUSTOMHID_H
#define __USB_CUSTOMHID_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CUSTOM_HID
* @brief This file is the Header file for USBD_customhid.c
* @{
*/
/** @defgroup USBD_CUSTOM_HID_Exported_Defines
* @{
*/
#ifndef CUSTOM_HID_EPIN_ADDR
#define CUSTOM_HID_EPIN_ADDR 0x81U
#endif /* CUSTOM_HID_EPIN_ADDR */
#ifndef CUSTOM_HID_EPIN_SIZE
#define CUSTOM_HID_EPIN_SIZE 0x02U
#endif /* CUSTOM_HID_EPIN_SIZE */
#ifndef CUSTOM_HID_EPOUT_ADDR
#define CUSTOM_HID_EPOUT_ADDR 0x01U
#endif /* CUSTOM_HID_EPOUT_ADDR */
#ifndef CUSTOM_HID_EPOUT_SIZE
#define CUSTOM_HID_EPOUT_SIZE 0x02U
#endif /* CUSTOM_HID_EPOUT_SIZE*/
#define USB_CUSTOM_HID_CONFIG_DESC_SIZ 41U
#define USB_CUSTOM_HID_DESC_SIZ 9U
#ifndef CUSTOM_HID_HS_BINTERVAL
#define CUSTOM_HID_HS_BINTERVAL 0x05U
#endif /* CUSTOM_HID_HS_BINTERVAL */
#ifndef CUSTOM_HID_FS_BINTERVAL
#define CUSTOM_HID_FS_BINTERVAL 0x05U
#endif /* CUSTOM_HID_FS_BINTERVAL */
#ifndef USBD_CUSTOMHID_OUTREPORT_BUF_SIZE
#define USBD_CUSTOMHID_OUTREPORT_BUF_SIZE 0x02U
#endif /* USBD_CUSTOMHID_OUTREPORT_BUF_SIZE */
#ifndef USBD_CUSTOM_HID_REPORT_DESC_SIZE
#define USBD_CUSTOM_HID_REPORT_DESC_SIZE 163U
#endif /* USBD_CUSTOM_HID_REPORT_DESC_SIZE */
#define CUSTOM_HID_DESCRIPTOR_TYPE 0x21U
#define CUSTOM_HID_REPORT_DESC 0x22U
#define CUSTOM_HID_REQ_SET_PROTOCOL 0x0BU
#define CUSTOM_HID_REQ_GET_PROTOCOL 0x03U
#define CUSTOM_HID_REQ_SET_IDLE 0x0AU
#define CUSTOM_HID_REQ_GET_IDLE 0x02U
#define CUSTOM_HID_REQ_SET_REPORT 0x09U
#define CUSTOM_HID_REQ_GET_REPORT 0x01U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef enum
{
CUSTOM_HID_IDLE = 0U,
CUSTOM_HID_BUSY,
} CUSTOM_HID_StateTypeDef;
typedef struct _USBD_CUSTOM_HID_Itf
{
uint8_t *pReport;
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* OutEvent)(uint8_t event_idx, uint8_t state);
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
int8_t (* CtrlReqComplete)(uint8_t request, uint16_t wLength);
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
uint8_t *(* GetReport)(uint16_t *ReportLength);
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
} USBD_CUSTOM_HID_ItfTypeDef;
typedef struct
{
uint8_t Report_buf[USBD_CUSTOMHID_OUTREPORT_BUF_SIZE];
uint32_t Protocol;
uint32_t IdleState;
uint32_t AltSetting;
uint32_t IsReportAvailable;
CUSTOM_HID_StateTypeDef state;
} USBD_CUSTOM_HID_HandleTypeDef;
/*
* HID Class specification version 1.1
* 6.2.1 HID Descriptor
*/
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorTypeCHID;
uint16_t bcdCUSTOM_HID;
uint8_t bCountryCode;
uint8_t bNumDescriptors;
uint8_t bDescriptorType;
uint16_t wItemLength;
} __PACKED USBD_DescTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_CUSTOM_HID;
#define USBD_CUSTOM_HID_CLASS &USBD_CUSTOM_HID
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CUSTOM_HID_SendReport(USBD_HandleTypeDef *pdev,
uint8_t *report, uint16_t len, uint8_t ClassId);
#else
uint8_t USBD_CUSTOM_HID_SendReport(USBD_HandleTypeDef *pdev,
uint8_t *report, uint16_t len);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CUSTOM_HID_ReceivePacket(USBD_HandleTypeDef *pdev);
uint8_t USBD_CUSTOM_HID_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CUSTOM_HID_ItfTypeDef *fops);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_CUSTOMHID_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID\Inc\usbd_customhid_if_template.h | /**
******************************************************************************
* @file usbd_customhid_if_template.h
* @author MCD Application Team
* @brief Header for usbd_customhid_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_CUSTOMHID_IF_TEMPLATE_H
#define __USBD_CUSTOMHID_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_customhid.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
extern USBD_CUSTOM_HID_ItfTypeDef USBD_CustomHID_template_fops;
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CUSTOMHID_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID\Src\usbd_customhid.c | /**
******************************************************************************
* @file usbd_customhid.c
* @author MCD Application Team
* @brief This file provides the CUSTOM_HID core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* CUSTOM_HID Class Description
* ===================================================================
* This module manages the CUSTOM_HID class V1.11 following the "Device Class Definition
* for Human Interface Devices (CUSTOM_HID) Version 1.11 Jun 27, 2001".
* This driver implements the following aspects of the specification:
* - The Boot Interface Subclass
* - Usage Page : Generic Desktop
* - Usage : Vendor
* - Collection : Application
*
* @note In HS mode and when the DMA is used, all variables and data structures
* dealing with the DMA during the transaction process should be 32-bit aligned.
*
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_customhid.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CUSTOM_HID
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CUSTOM_HID_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CUSTOM_HID_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CUSTOM_HID_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CUSTOM_HID_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_CUSTOM_HID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CUSTOM_HID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_CUSTOM_HID_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_CUSTOM_HID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CUSTOM_HID_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_CUSTOM_HID_EP0_RxReady(USBD_HandleTypeDef *pdev);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_CUSTOM_HID_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_CUSTOM_HID_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_CUSTOM_HID_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_CUSTOM_HID_GetDeviceQualifierDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_CUSTOM_HID_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_CUSTOM_HID =
{
USBD_CUSTOM_HID_Init,
USBD_CUSTOM_HID_DeInit,
USBD_CUSTOM_HID_Setup,
NULL, /*EP0_TxSent*/
USBD_CUSTOM_HID_EP0_RxReady, /*EP0_RxReady*/ /* STATUS STAGE IN */
USBD_CUSTOM_HID_DataIn, /*DataIn*/
USBD_CUSTOM_HID_DataOut,
NULL, /*SOF */
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_CUSTOM_HID_GetHSCfgDesc,
USBD_CUSTOM_HID_GetFSCfgDesc,
USBD_CUSTOM_HID_GetOtherSpeedCfgDesc,
USBD_CUSTOM_HID_GetDeviceQualifierDesc,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB CUSTOM_HID device FS Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_CfgDesc[USB_CUSTOM_HID_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
LOBYTE(USB_CUSTOM_HID_CONFIG_DESC_SIZ), /* wTotalLength: Bytes returned */
HIBYTE(USB_CUSTOM_HID_CONFIG_DESC_SIZ),
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/************** Descriptor of CUSTOM HID interface ****************/
/* 09 */
0x09, /* bLength: Interface Descriptor size*/
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints*/
0x03, /* bInterfaceClass: CUSTOM_HID */
0x00, /* bInterfaceSubClass : 1=BOOT, 0=no boot */
0x00, /* nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse */
0x00, /* iInterface: Index of string descriptor */
/******************** Descriptor of CUSTOM_HID *************************/
/* 18 */
0x09, /* bLength: CUSTOM_HID Descriptor size */
CUSTOM_HID_DESCRIPTOR_TYPE, /* bDescriptorType: CUSTOM_HID */
0x11, /* bCUSTOM_HIDUSTOM_HID: CUSTOM_HID Class Spec release number */
0x01,
0x00, /* bCountryCode: Hardware target country */
0x01, /* bNumDescriptors: Number of CUSTOM_HID class descriptors
to follow */
0x22, /* bDescriptorType */
LOBYTE(USBD_CUSTOM_HID_REPORT_DESC_SIZE), /* wItemLength: Total length of Report descriptor */
HIBYTE(USBD_CUSTOM_HID_REPORT_DESC_SIZE),
/******************** Descriptor of Custom HID endpoints ********************/
/* 27 */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: */
CUSTOM_HID_EPIN_ADDR, /* bEndpointAddress: Endpoint Address (IN) */
0x03, /* bmAttributes: Interrupt endpoint */
LOBYTE(CUSTOM_HID_EPIN_SIZE), /* wMaxPacketSize: 2 Bytes max */
HIBYTE(CUSTOM_HID_EPIN_SIZE),
CUSTOM_HID_FS_BINTERVAL, /* bInterval: Polling Interval */
/* 34 */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: */
CUSTOM_HID_EPOUT_ADDR, /* bEndpointAddress: Endpoint Address (OUT) */
0x03, /* bmAttributes: Interrupt endpoint */
LOBYTE(CUSTOM_HID_EPOUT_SIZE), /* wMaxPacketSize: 2 Bytes max */
HIBYTE(CUSTOM_HID_EPOUT_SIZE),
CUSTOM_HID_FS_BINTERVAL, /* bInterval: Polling Interval */
/* 41 */
};
#endif /* USE_USBD_COMPOSITE */
/* USB CUSTOM_HID device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_Desc[USB_CUSTOM_HID_DESC_SIZ] __ALIGN_END =
{
/* 18 */
0x09, /* bLength: CUSTOM_HID Descriptor size */
CUSTOM_HID_DESCRIPTOR_TYPE, /* bDescriptorType: CUSTOM_HID */
0x11, /* bCUSTOM_HIDUSTOM_HID: CUSTOM_HID Class Spec release number */
0x01,
0x00, /* bCountryCode: Hardware target country */
0x01, /* bNumDescriptors: Number of CUSTOM_HID class descriptors
to follow */
0x22, /* bDescriptorType */
LOBYTE(USBD_CUSTOM_HID_REPORT_DESC_SIZE), /* wItemLength: Total length of Report descriptor */
HIBYTE(USBD_CUSTOM_HID_REPORT_DESC_SIZE),
};
#ifndef USE_USBD_COMPOSITE
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t CUSTOMHIDInEpAdd = CUSTOM_HID_EPIN_ADDR;
static uint8_t CUSTOMHIDOutEpAdd = CUSTOM_HID_EPOUT_ADDR;
/**
* @}
*/
/** @defgroup USBD_CUSTOM_HID_Private_Functions
* @{
*/
/**
* @brief USBD_CUSTOM_HID_Init
* Initialize the CUSTOM_HID interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_CUSTOM_HID_HandleTypeDef *hhid;
hhid = (USBD_CUSTOM_HID_HandleTypeDef *)USBD_malloc(sizeof(USBD_CUSTOM_HID_HandleTypeDef));
if (hhid == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)hhid;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CUSTOMHIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
CUSTOMHIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pdev->ep_in[CUSTOMHIDInEpAdd & 0xFU].bInterval = CUSTOM_HID_HS_BINTERVAL;
pdev->ep_out[CUSTOMHIDOutEpAdd & 0xFU].bInterval = CUSTOM_HID_HS_BINTERVAL;
}
else /* LOW and FULL-speed endpoints */
{
pdev->ep_in[CUSTOMHIDInEpAdd & 0xFU].bInterval = CUSTOM_HID_FS_BINTERVAL;
pdev->ep_out[CUSTOMHIDOutEpAdd & 0xFU].bInterval = CUSTOM_HID_FS_BINTERVAL;
}
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, CUSTOMHIDInEpAdd, USBD_EP_TYPE_INTR,
CUSTOM_HID_EPIN_SIZE);
pdev->ep_in[CUSTOMHIDInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, CUSTOMHIDOutEpAdd, USBD_EP_TYPE_INTR,
CUSTOM_HID_EPOUT_SIZE);
pdev->ep_out[CUSTOMHIDOutEpAdd & 0xFU].is_used = 1U;
hhid->state = CUSTOM_HID_IDLE;
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
#ifndef USBD_CUSTOMHID_OUT_PREPARE_RECEIVE_DISABLED
/* Prepare Out endpoint to receive 1st packet */
(void)USBD_LL_PrepareReceive(pdev, CUSTOMHIDOutEpAdd, hhid->Report_buf,
USBD_CUSTOMHID_OUTREPORT_BUF_SIZE);
#endif /* USBD_CUSTOMHID_OUT_PREPARE_RECEIVE_DISABLED */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CUSTOM_HID_Init
* DeInitialize the CUSTOM_HID layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
CUSTOMHIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
CUSTOMHIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close CUSTOM_HID EP IN */
(void)USBD_LL_CloseEP(pdev, CUSTOMHIDInEpAdd);
pdev->ep_in[CUSTOMHIDInEpAdd & 0xFU].is_used = 0U;
pdev->ep_in[CUSTOMHIDInEpAdd & 0xFU].bInterval = 0U;
/* Close CUSTOM_HID EP OUT */
(void)USBD_LL_CloseEP(pdev, CUSTOMHIDOutEpAdd);
pdev->ep_out[CUSTOMHIDOutEpAdd & 0xFU].is_used = 0U;
pdev->ep_out[CUSTOMHIDOutEpAdd & 0xFU].bInterval = 0U;
/* Free allocated memory */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CUSTOM_HID_Setup
* Handle the CUSTOM_HID specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len = 0U;
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
uint16_t ReportLength = 0U;
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
uint8_t *pbuf = NULL;
uint16_t status_info = 0U;
USBD_StatusTypeDef ret = USBD_OK;
if (hhid == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
switch (req->bRequest)
{
case CUSTOM_HID_REQ_SET_PROTOCOL:
hhid->Protocol = (uint8_t)(req->wValue);
break;
case CUSTOM_HID_REQ_GET_PROTOCOL:
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->Protocol, 1U);
break;
case CUSTOM_HID_REQ_SET_IDLE:
hhid->IdleState = (uint8_t)(req->wValue >> 8);
break;
case CUSTOM_HID_REQ_GET_IDLE:
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->IdleState, 1U);
break;
case CUSTOM_HID_REQ_SET_REPORT:
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
if (((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->CtrlReqComplete != NULL)
{
/* Let the application decide when to enable EP0 to receive the next report */
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->CtrlReqComplete(req->bRequest,
req->wLength);
}
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
#ifndef USBD_CUSTOMHID_EP0_OUT_PREPARE_RECEIVE_DISABLED
hhid->IsReportAvailable = 1U;
(void)USBD_CtlPrepareRx(pdev, hhid->Report_buf,
MIN(req->wLength, USBD_CUSTOMHID_OUTREPORT_BUF_SIZE));
#endif /* USBD_CUSTOMHID_EP0_OUT_PREPARE_RECEIVE_DISABLED */
break;
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
case CUSTOM_HID_REQ_GET_REPORT:
if (((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->GetReport != NULL)
{
ReportLength = req->wLength;
/* Get report data buffer */
pbuf = ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->GetReport(&ReportLength);
}
if ((pbuf != NULL) && (ReportLength != 0U))
{
len = MIN(ReportLength, req->wLength);
/* Send the report data over EP0 */
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
if (((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->CtrlReqComplete != NULL)
{
/* Let the application decide what to do, keep EP0 data phase in NAK state and
use USBD_CtlSendData() when data become available or stall the EP0 data phase */
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->CtrlReqComplete(req->bRequest,
req->wLength);
}
else
{
/* Stall EP0 if no data available */
USBD_CtlError(pdev, req);
}
#else
/* Stall EP0 if no data available */
USBD_CtlError(pdev, req);
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
}
break;
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_DESCRIPTOR:
if ((req->wValue >> 8) == CUSTOM_HID_REPORT_DESC)
{
len = MIN(USBD_CUSTOM_HID_REPORT_DESC_SIZE, req->wLength);
pbuf = ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->pReport;
}
else
{
if ((req->wValue >> 8) == CUSTOM_HID_DESCRIPTOR_TYPE)
{
pbuf = USBD_CUSTOM_HID_Desc;
len = MIN(USB_CUSTOM_HID_DESC_SIZ, req->wLength);
}
}
(void)USBD_CtlSendData(pdev, pbuf, len);
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->AltSetting, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
hhid->AltSetting = (uint8_t)(req->wValue);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_CUSTOM_HID_SendReport
* Send CUSTOM_HID Report
* @param pdev: device instance
* @param buff: pointer to report
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_CUSTOM_HID_SendReport(USBD_HandleTypeDef *pdev,
uint8_t *report, uint16_t len, uint8_t ClassId)
{
USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_CUSTOM_HID_SendReport(USBD_HandleTypeDef *pdev,
uint8_t *report, uint16_t len)
{
USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
if (hhid == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get Endpoint IN address allocated for this class instance */
CUSTOMHIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, ClassId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (hhid->state == CUSTOM_HID_IDLE)
{
hhid->state = CUSTOM_HID_BUSY;
(void)USBD_LL_Transmit(pdev, CUSTOMHIDInEpAdd, report, len);
}
else
{
return (uint8_t)USBD_BUSY;
}
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_CUSTOM_HID_GetFSCfgDesc
* return FS configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CUSTOM_HID_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CUSTOM_HID_EPIN_SIZE;
pEpInDesc->bInterval = CUSTOM_HID_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CUSTOM_HID_EPOUT_SIZE;
pEpOutDesc->bInterval = CUSTOM_HID_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CUSTOM_HID_CfgDesc);
return USBD_CUSTOM_HID_CfgDesc;
}
/**
* @brief USBD_CUSTOM_HID_GetHSCfgDesc
* return HS configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CUSTOM_HID_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CUSTOM_HID_EPIN_SIZE;
pEpInDesc->bInterval = CUSTOM_HID_HS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CUSTOM_HID_EPOUT_SIZE;
pEpOutDesc->bInterval = CUSTOM_HID_HS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CUSTOM_HID_CfgDesc);
return USBD_CUSTOM_HID_CfgDesc;
}
/**
* @brief USBD_CUSTOM_HID_GetOtherSpeedCfgDesc
* return other speed configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CUSTOM_HID_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_CUSTOM_HID_CfgDesc, CUSTOM_HID_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = CUSTOM_HID_EPIN_SIZE;
pEpInDesc->bInterval = CUSTOM_HID_FS_BINTERVAL;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = CUSTOM_HID_EPOUT_SIZE;
pEpOutDesc->bInterval = CUSTOM_HID_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_CUSTOM_HID_CfgDesc);
return USBD_CUSTOM_HID_CfgDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CUSTOM_HID_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
/* Ensure that the FIFO is empty before a new transfer, this condition could
be caused by a new transfer before the end of the previous transfer */
((USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId])->state = CUSTOM_HID_IDLE;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CUSTOM_HID_DataOut
* handle data OUT Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
USBD_CUSTOM_HID_HandleTypeDef *hhid;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application processing */
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->OutEvent(hhid->Report_buf[0],
hhid->Report_buf[1]);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CUSTOM_HID_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_CUSTOM_HID_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_CUSTOM_HID_HandleTypeDef *hhid;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get OUT Endpoint address allocated for this class instance */
CUSTOMHIDOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* Resume USB Out process */
(void)USBD_LL_PrepareReceive(pdev, CUSTOMHIDOutEpAdd, hhid->Report_buf,
USBD_CUSTOMHID_OUTREPORT_BUF_SIZE);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_CUSTOM_HID_EP0_RxReady
* Handles control request data.
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_CUSTOM_HID_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hhid == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (hhid->IsReportAvailable == 1U)
{
((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData[pdev->classId])->OutEvent(hhid->Report_buf[0],
hhid->Report_buf[1]);
hhid->IsReportAvailable = 0U;
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_CUSTOM_HID_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_CUSTOM_HID_DeviceQualifierDesc);
return USBD_CUSTOM_HID_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_CUSTOM_HID_RegisterInterface
* @param pdev: device instance
* @param fops: CUSTOMHID Interface callback
* @retval status
*/
uint8_t USBD_CUSTOM_HID_RegisterInterface(USBD_HandleTypeDef *pdev,
USBD_CUSTOM_HID_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID | D://workCode//uploadProject\stm32_mw_usb_device\Class\CustomHID\Src\usbd_customhid_if_template.c | /**
******************************************************************************
* @file usbd_customhid_if_template.c
* @author MCD Application Team
* @brief USB Device Custom HID interface file.
* This template should be copied to the user folder, renamed and customized
* following user needs.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_customhid_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static int8_t TEMPLATE_CUSTOM_HID_Init(void);
static int8_t TEMPLATE_CUSTOM_HID_DeInit(void);
static int8_t TEMPLATE_CUSTOM_HID_OutEvent(uint8_t event_idx, uint8_t state);
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
static int8_t TEMPLATE_CUSTOM_HID_CtrlReqComplete(uint8_t request, uint16_t wLength);
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
static uint8_t *TEMPLATE_CUSTOM_HID_GetReport(uint16_t *ReportLength);
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
/* Private variables ---------------------------------------------------------*/
extern USBD_HandleTypeDef USBD_Device;
__ALIGN_BEGIN static uint8_t TEMPLATE_CUSTOM_HID_ReportDesc[USBD_CUSTOM_HID_REPORT_DESC_SIZE] __ALIGN_END = {0};
USBD_CUSTOM_HID_ItfTypeDef USBD_CustomHID_template_fops =
{
TEMPLATE_CUSTOM_HID_ReportDesc,
TEMPLATE_CUSTOM_HID_Init,
TEMPLATE_CUSTOM_HID_DeInit,
TEMPLATE_CUSTOM_HID_OutEvent,
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
TEMPLATE_CUSTOM_HID_CtrlReqComplete,
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
TEMPLATE_CUSTOM_HID_GetReport,
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief TEMPLATE_CUSTOM_HID_Init
* Initializes the CUSTOM HID media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_Init(void)
{
return (0);
}
/**
* @brief TEMPLATE_CUSTOM_HID_DeInit
* DeInitializes the CUSTOM HID media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_DeInit(void)
{
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_CUSTOM_HID_Control
* Manage the CUSTOM HID class events
* @param event_idx: event index
* @param state: event state
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_OutEvent(uint8_t event_idx, uint8_t state)
{
UNUSED(event_idx);
UNUSED(state);
/* Start next USB packet transfer once data processing is completed */
if (USBD_CUSTOM_HID_ReceivePacket(&USBD_Device) != (uint8_t)USBD_OK)
{
return -1;
}
return (0);
}
#ifdef USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED
/**
* @brief TEMPLATE_CUSTOM_HID_CtrlReqComplete
* Manage the CUSTOM HID control request complete
* @param request: control request
* @param wLength: request wLength
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_CtrlReqComplete(uint8_t request, uint16_t wLength)
{
UNUSED(wLength);
switch (request)
{
case CUSTOM_HID_REQ_SET_REPORT:
break;
case CUSTOM_HID_REQ_GET_REPORT:
break;
default:
break;
}
return (0);
}
#endif /* USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
#ifdef USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED
/**
* @brief TEMPLATE_CUSTOM_HID_GetReport
* Manage the CUSTOM HID control Get Report request
* @param event_idx: event index
* @param state: event state
* @retval return pointer to HID report
*/
static uint8_t *TEMPLATE_CUSTOM_HID_GetReport(uint16_t *ReportLength)
{
UNUSED(ReportLength);
uint8_t *pbuff;
return (pbuff);
}
#endif /* USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU | D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU\Inc\usbd_dfu.h | /**
******************************************************************************
* @file usbd_dfu.h
* @author MCD Application Team
* @brief Header file for the usbd_dfu.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_DFU_H
#define __USB_DFU_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_DFU
* @brief This file is the Header file for usbd_dfu.c
* @{
*/
/** @defgroup USBD_DFU_Exported_Defines
* @{
*/
#ifndef USBD_DFU_MAX_ITF_NUM
#define USBD_DFU_MAX_ITF_NUM 1U
#endif /* USBD_DFU_MAX_ITF_NUM */
#ifndef USBD_DFU_XFER_SIZE
#define USBD_DFU_XFER_SIZE 1024U
#endif /* USBD_DFU_XFER_SIZE */
#ifndef USBD_DFU_APP_DEFAULT_ADD
#define USBD_DFU_APP_DEFAULT_ADD 0x08008000U /* The first sector (32 KB) is reserved for DFU code */
#endif /* USBD_DFU_APP_DEFAULT_ADD */
#ifndef USBD_DFU_BM_ATTRIBUTES
#define USBD_DFU_BM_ATTRIBUTES 0x0BU
#endif /* USBD_DFU_BM_ATTRIBUTES */
#ifndef USBD_DFU_DETACH_TIMEOUT
#define USBD_DFU_DETACH_TIMEOUT 0xFFU
#endif /* USBD_DFU_DETACH_TIMEOUT */
#define USB_DFU_CONFIG_DESC_SIZ (18U + (9U * USBD_DFU_MAX_ITF_NUM))
#define USB_DFU_DESC_SIZ 9U
#define DFU_DESCRIPTOR_TYPE 0x21U
#define DFU_VENDOR_CMD_MAX 32U
/**************************************************/
/* DFU Requests DFU states */
/**************************************************/
#define APP_STATE_IDLE 0U
#define APP_STATE_DETACH 1U
#define DFU_STATE_IDLE 2U
#define DFU_STATE_DNLOAD_SYNC 3U
#define DFU_STATE_DNLOAD_BUSY 4U
#define DFU_STATE_DNLOAD_IDLE 5U
#define DFU_STATE_MANIFEST_SYNC 6U
#define DFU_STATE_MANIFEST 7U
#define DFU_STATE_MANIFEST_WAIT_RESET 8U
#define DFU_STATE_UPLOAD_IDLE 9U
#define DFU_STATE_ERROR 10U
/**************************************************/
/* DFU errors */
/**************************************************/
#define DFU_ERROR_NONE 0x00U
#define DFU_ERROR_TARGET 0x01U
#define DFU_ERROR_FILE 0x02U
#define DFU_ERROR_WRITE 0x03U
#define DFU_ERROR_ERASE 0x04U
#define DFU_ERROR_CHECK_ERASED 0x05U
#define DFU_ERROR_PROG 0x06U
#define DFU_ERROR_VERIFY 0x07U
#define DFU_ERROR_ADDRESS 0x08U
#define DFU_ERROR_NOTDONE 0x09U
#define DFU_ERROR_FIRMWARE 0x0AU
#define DFU_ERROR_VENDOR 0x0BU
#define DFU_ERROR_USB 0x0CU
#define DFU_ERROR_POR 0x0DU
#define DFU_ERROR_UNKNOWN 0x0EU
#define DFU_ERROR_STALLEDPKT 0x0FU
/**************************************************/
/* DFU Manifestation State */
/**************************************************/
#define DFU_MANIFEST_COMPLETE 0x00U
#define DFU_MANIFEST_IN_PROGRESS 0x01U
/**************************************************/
/* Special Commands with Download Request */
/**************************************************/
#define DFU_CMD_GETCOMMANDS 0x00U
#define DFU_CMD_SETADDRESSPOINTER 0x21U
#define DFU_CMD_ERASE 0x41U
#define DFU_MEDIA_ERASE 0x00U
#define DFU_MEDIA_PROGRAM 0x01U
/**************************************************/
/* Other defines */
/**************************************************/
/* Bit Detach capable = bit 3 in bmAttributes field */
#define DFU_DETACH_MASK (1U << 3)
#define DFU_MANIFEST_MASK (1U << 2)
#define DFU_STATUS_DEPTH 6U
#define IS_DFU_DOWNLOAD 0x0DFDFU
#define IS_DFU_UPLOAD 0x1DFDFU
#define IS_DFU_SETADDRESSPOINTER 0x2DFDFU
#define IS_DFU_PHY_ADDRESS 0x3DFDFU
typedef enum
{
DFU_DETACH = 0U,
DFU_DNLOAD,
DFU_UPLOAD,
DFU_GETSTATUS,
DFU_CLRSTATUS,
DFU_GETSTATE,
DFU_ABORT
} DFU_RequestTypeDef;
typedef void (*pFunction)(void);
/********** Descriptor of DFU interface 0 Alternate setting n ****************/
#define USBD_DFU_IF_DESC(n) \
0x09, /* bLength: Interface Descriptor size */ \
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */ \
0x00, /* bInterfaceNumber: Number of Interface */ \
(n), /* bAlternateSetting: Alternate setting */ \
0x00, /* bNumEndpoints*/ \
0xFE, /* bInterfaceClass: Application Specific Class Code */ \
0x01, /* bInterfaceSubClass : Device Firmware Upgrade Code */ \
0x02, /* nInterfaceProtocol: DFU mode protocol */ \
USBD_IDX_INTERFACE_STR + (n) + 1U /* iInterface: Index of string descriptor */
#define TRANSFER_SIZE_BYTES(size) ((uint8_t)(size)), ((uint8_t)((size) >> 8))
#define IS_PROTECTED_AREA(add) (uint8_t)((((add) >= 0x08000000) && ((add) < (APP_DEFAULT_ADD))) ? 1 : 0)
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef struct
{
union
{
uint32_t d32[USBD_DFU_XFER_SIZE / 4U];
uint8_t d8[USBD_DFU_XFER_SIZE];
} buffer;
uint32_t wblock_num;
uint32_t wlength;
uint32_t data_ptr;
uint32_t app_addr_ptr;
uint32_t alt_setting;
uint8_t dev_status[DFU_STATUS_DEPTH];
uint8_t ReservedForAlign[2];
uint8_t dev_state;
uint8_t manif_state;
} USBD_DFU_HandleTypeDef;
typedef struct
{
const uint8_t *pStrDesc;
uint16_t (* Init)(void);
uint16_t (* DeInit)(void);
uint16_t (* Erase)(uint32_t Add);
uint16_t (* Write)(uint8_t *src, uint8_t *dest, uint32_t Len);
uint8_t *(* Read)(uint8_t *src, uint8_t *dest, uint32_t Len);
uint16_t (* GetStatus)(uint32_t Add, uint8_t cmd, uint8_t *buff);
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
uint16_t (* GetVendorCMD)(uint8_t *cmd, uint8_t *cmdlength);
uint16_t (* VendorDownloadCMD)(uint8_t *pbuf, uint32_t BlockNumber, uint32_t wlength, uint32_t *status);
uint16_t (* VendorUploadCMD)(uint32_t Add, uint32_t BlockNumber, uint32_t *status);
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
uint16_t (* VendorCheck)(uint8_t *pbuf, uint32_t ReqType, uint32_t *status);
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
#if (USBD_DFU_VENDOR_EXIT_ENABLED == 1U)
uint16_t (* LeaveDFU)(uint32_t Add);
#endif /* USBD_DFU_VENDOR_EXIT_ENABLED */
} USBD_DFU_MediaTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bmAttributes;
uint16_t wDetachTimeout;
uint16_t wTransferSze;
uint16_t bcdDFUVersion;
} __PACKED USBD_DFUFuncDescTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_DFU;
#define USBD_DFU_CLASS &USBD_DFU
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_DFU_RegisterMedia(USBD_HandleTypeDef *pdev,
USBD_DFU_MediaTypeDef *fops);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_DFU_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU | D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU\Inc\usbd_dfu_media_template.h | /**
******************************************************************************
* @file usbd_dfu_media_template.h
* @author MCD Application Team
* @brief header file for the usbd_dfu_media_template.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_DFU_MEDIA_TEMPLATE_H
#define __USBD_DFU_MEDIA_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_dfu.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_MEDIA
* @brief header file for the usbd_dfu_media_template.c file
* @{
*/
/** @defgroup USBD_MEDIA_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MEDIA_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MEDIA_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MEDIA_Exported_Variables
* @{
*/
extern USBD_DFU_MediaTypeDef USBD_DFU_MEDIA_Template_fops;
/**
* @}
*/
/** @defgroup USBD_MEDIA_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_DFU_MEDIA_TEMPLATE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU | D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU\Src\usbd_dfu.c | /**
******************************************************************************
* @file usbd_dfu.c
* @author MCD Application Team
* @brief This file provides the DFU core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* DFU Class Driver Description
* ===================================================================
* This driver manages the DFU class V1.1 following the "Device Class Specification for
* Device Firmware Upgrade Version 1.1 Aug 5, 2004".
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as DFU device (in DFU mode only)
* - Requests management (supporting ST DFU sub-protocol)
* - Memory operations management (Download/Upload/Erase/Detach/GetState/GetStatus)
* - DFU state machine implementation.
*
* @note
* ST DFU sub-protocol is compliant with DFU protocol and use sub-requests to manage
* memory addressing, commands processing, specific memories operations (ie. Erase) ...
* As required by the DFU specification, only endpoint 0 is used in this application.
* Other endpoints and functions may be added to the application (ie. DFU ...)
*
* These aspects may be enriched or modified for a specific user application.
*
* This driver doesn't implement the following aspects of the specification
* (but it is possible to manage these features with some modifications on this driver):
* - Manifestation Tolerant mode
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_dfu.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_DFU
* @brief usbd core module
* @{
*/
/** @defgroup USBD_DFU_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_DFU_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_DFU_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_DFU_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_DFU_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_DFU_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_DFU_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_DFU_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_DFU_EP0_TxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_DFU_SOF(USBD_HandleTypeDef *pdev);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_DFU_GetCfgDesc(uint16_t *length);
static uint8_t *USBD_DFU_GetDeviceQualifierDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_DFU_GetUsrStringDesc(USBD_HandleTypeDef *pdev,
uint8_t index, uint16_t *length);
#endif /* USBD_SUPPORT_USER_STRING_DESC */
static void DFU_Detach(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void DFU_Download(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void DFU_Upload(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void DFU_GetStatus(USBD_HandleTypeDef *pdev);
static void DFU_ClearStatus(USBD_HandleTypeDef *pdev);
static void DFU_GetState(USBD_HandleTypeDef *pdev);
static void DFU_Abort(USBD_HandleTypeDef *pdev);
static void DFU_Leave(USBD_HandleTypeDef *pdev);
static void *USBD_DFU_GetDfuFuncDesc(uint8_t *pConfDesc);
/**
* @}
*/
/** @defgroup USBD_DFU_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_DFU =
{
USBD_DFU_Init,
USBD_DFU_DeInit,
USBD_DFU_Setup,
USBD_DFU_EP0_TxReady,
USBD_DFU_EP0_RxReady,
NULL,
NULL,
USBD_DFU_SOF,
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_DFU_GetCfgDesc,
USBD_DFU_GetCfgDesc,
USBD_DFU_GetCfgDesc,
USBD_DFU_GetDeviceQualifierDesc,
#endif /* USE_USBD_COMPOSITE */
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
USBD_DFU_GetUsrStringDesc
#endif /* USBD_SUPPORT_USER_STRING_DESC */
};
#ifndef USE_USBD_COMPOSITE
/* USB DFU device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_DFU_CfgDesc[USB_DFU_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_DFU_CONFIG_DESC_SIZ, /* wTotalLength: Bytes returned */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x02, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/* 09 */
/********** Descriptor of DFU interface 0 Alternate setting 0 **************/
USBD_DFU_IF_DESC(0U), /* This interface is mandatory for all devices */
#if (USBD_DFU_MAX_ITF_NUM > 1U)
/********** Descriptor of DFU interface 0 Alternate setting 1 **************/
USBD_DFU_IF_DESC(1),
#endif /* (USBD_DFU_MAX_ITF_NUM > 1) */
#if (USBD_DFU_MAX_ITF_NUM > 2U)
/********** Descriptor of DFU interface 0 Alternate setting 2 **************/
USBD_DFU_IF_DESC(2),
#endif /* (USBD_DFU_MAX_ITF_NUM > 2) */
#if (USBD_DFU_MAX_ITF_NUM > 3U)
/********** Descriptor of DFU interface 0 Alternate setting 3 **************/
USBD_DFU_IF_DESC(3),
#endif /* (USBD_DFU_MAX_ITF_NUM > 3) */
#if (USBD_DFU_MAX_ITF_NUM > 4U)
/********** Descriptor of DFU interface 0 Alternate setting 4 **************/
USBD_DFU_IF_DESC(4),
#endif /* (USBD_DFU_MAX_ITF_NUM > 4) */
#if (USBD_DFU_MAX_ITF_NUM > 5U)
/********** Descriptor of DFU interface 0 Alternate setting 5 **************/
USBD_DFU_IF_DESC(5),
#endif /* (USBD_DFU_MAX_ITF_NUM > 5) */
#if (USBD_DFU_MAX_ITF_NUM > 6U)
#error "ERROR: usbd_dfu_core.c: Modify the file to support more descriptors!"
#endif /* (USBD_DFU_MAX_ITF_NUM > 6) */
/******************** DFU Functional Descriptor********************/
0x09, /* blength = 9 Bytes */
DFU_DESCRIPTOR_TYPE, /* DFU Functional Descriptor */
0x0B, /* bmAttribute:
bitCanDnload = 1 (bit 0)
bitCanUpload = 1 (bit 1)
bitManifestationTolerant = 0 (bit 2)
bitWillDetach = 1 (bit 3)
Reserved (bit4-6)
bitAcceleratedST = 0 (bit 7) */
0xFF, /* DetachTimeOut= 255 ms*/
0x00,
/* WARNING: In DMA mode the multiple MPS packets feature is still not supported
==> In this case, when using DMA USBD_DFU_XFER_SIZE should be set to 64 in usbd_conf.h */
TRANSFER_SIZE_BYTES(USBD_DFU_XFER_SIZE), /* TransferSize = 1024 Byte */
0x1A, /* bcdDFUVersion */
0x01
/***********************************************************/
/* 9*/
};
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_DFU_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_DFU_Private_Functions
* @{
*/
/**
* @brief USBD_DFU_Init
* Initialize the DFU interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_DFU_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_DFU_HandleTypeDef *hdfu;
/* Allocate Audio structure */
hdfu = (USBD_DFU_HandleTypeDef *)USBD_malloc(sizeof(USBD_DFU_HandleTypeDef));
if (hdfu == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)hdfu;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
hdfu->alt_setting = 0U;
hdfu->data_ptr = USBD_DFU_APP_DEFAULT_ADD;
hdfu->wblock_num = 0U;
hdfu->wlength = 0U;
hdfu->manif_state = DFU_MANIFEST_COMPLETE;
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[0] = DFU_ERROR_NONE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = DFU_STATE_IDLE;
hdfu->dev_status[5] = 0U;
/* Initialize Hardware layer */
if (((USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId])->Init() != USBD_OK)
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_DFU_DeInit
* De-Initialize the DFU layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_DFU_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_DFU_HandleTypeDef *hdfu;
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_EMEM;
}
hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hdfu->wblock_num = 0U;
hdfu->wlength = 0U;
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[0] = DFU_ERROR_NONE;
hdfu->dev_status[4] = DFU_STATE_IDLE;
/* DeInit physical Interface components and Hardware Layer */
((USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_DFU_Setup
* Handle the DFU specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_DFU_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint8_t *pbuf;
uint16_t len;
uint16_t status_info = 0U;
if (hdfu == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
switch (req->bRequest)
{
case DFU_DNLOAD:
DFU_Download(pdev, req);
break;
case DFU_UPLOAD:
DFU_Upload(pdev, req);
break;
case DFU_GETSTATUS:
DFU_GetStatus(pdev);
break;
case DFU_CLRSTATUS:
DFU_ClearStatus(pdev);
break;
case DFU_GETSTATE:
DFU_GetState(pdev);
break;
case DFU_ABORT:
DFU_Abort(pdev);
break;
case DFU_DETACH:
DFU_Detach(pdev, req);
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_DESCRIPTOR:
if ((req->wValue >> 8) == DFU_DESCRIPTOR_TYPE)
{
pbuf = (uint8_t *)USBD_DFU_GetDfuFuncDesc(pdev->pConfDesc);
if (pbuf != NULL)
{
len = MIN(USB_DFU_DESC_SIZ, req->wLength);
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&hdfu->alt_setting, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if ((uint8_t)(req->wValue) < USBD_DFU_MAX_ITF_NUM)
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
hdfu->alt_setting = (uint8_t)(req->wValue);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
}
else
{
/* Call the error management function (command will be NAKed */
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_DFU_GetCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_DFU_GetCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_DFU_CfgDesc);
return USBD_DFU_CfgDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_DFU_EP0_RxReady
* handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_DFU_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_DFU_EP0_TxReady
* handle EP0 TRx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_DFU_EP0_TxReady(USBD_HandleTypeDef *pdev)
{
USBD_SetupReqTypedef req;
uint32_t app_addr_ptr;
uint32_t addr;
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
uint32_t VendorStatus = 0U;
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
if (hdfu == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (hdfu->dev_state == DFU_STATE_DNLOAD_BUSY)
{
/* Decode the Special Command */
if (hdfu->wblock_num == 0U)
{
if (hdfu->wlength == 1U)
{
if (hdfu->buffer.d8[0] == DFU_CMD_GETCOMMANDS)
{
/* Nothing to do */
}
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
else
{
/* Vendor specific DFU CMD */
if (DfuInterface->VendorDownloadCMD(hdfu->buffer.d8, hdfu->wblock_num,
hdfu->wlength, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
}
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
}
else if (hdfu->wlength == 5U)
{
if (hdfu->buffer.d8[0] == DFU_CMD_SETADDRESSPOINTER)
{
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
if (DfuInterface->VendorCheck(hdfu->buffer.d8, IS_DFU_SETADDRESSPOINTER, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
hdfu->data_ptr = hdfu->buffer.d8[1];
hdfu->data_ptr += (uint32_t)hdfu->buffer.d8[2] << 8;
hdfu->data_ptr += (uint32_t)hdfu->buffer.d8[3] << 16;
hdfu->data_ptr += (uint32_t)hdfu->buffer.d8[4] << 24;
}
else if (hdfu->buffer.d8[0] == DFU_CMD_ERASE)
{
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
if (DfuInterface->VendorCheck(hdfu->buffer.d8, IS_DFU_DOWNLOAD, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
app_addr_ptr = hdfu->buffer.d8[1];
app_addr_ptr += (uint32_t)hdfu->buffer.d8[2] << 8;
app_addr_ptr += (uint32_t)hdfu->buffer.d8[3] << 16;
app_addr_ptr += (uint32_t)hdfu->buffer.d8[4] << 24;
if (DfuInterface->Erase(app_addr_ptr) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = DFU_ERROR_VENDOR;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
}
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
else
{
/* Vendor specific DFU CMD */
if (DfuInterface->VendorDownloadCMD(hdfu->buffer.d8, hdfu->wblock_num,
hdfu->wlength, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
}
#else
else
{
return (uint8_t)USBD_FAIL;
}
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
}
else
{
/* Reset the global length and block number */
hdfu->wlength = 0U;
hdfu->wblock_num = 0U;
/* Call the error management function (command will be NAKed) */
req.bmRequest = 0U;
req.wLength = 1U;
USBD_CtlError(pdev, &req);
}
}
/* Regular Download Command */
else
{
if (hdfu->wblock_num > 1U)
{
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
if (DfuInterface->VendorCheck(hdfu->buffer.d8, IS_DFU_DOWNLOAD, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
/* Decode the required address */
addr = ((hdfu->wblock_num - 2U) * USBD_DFU_XFER_SIZE) + hdfu->data_ptr;
/* Perform the write operation */
if (DfuInterface->Write(hdfu->buffer.d8, (uint8_t *)addr, hdfu->wlength) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = DFU_ERROR_VENDOR;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return (uint8_t)USBD_FAIL;
}
}
}
/* Reset the global length and block number */
hdfu->wlength = 0U;
hdfu->wblock_num = 0U;
/* Update the state machine */
hdfu->dev_state = DFU_STATE_DNLOAD_SYNC;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
else if (hdfu->dev_state == DFU_STATE_MANIFEST)/* Manifestation in progress */
{
/* Start leaving DFU mode */
DFU_Leave(pdev);
}
else
{
return (uint8_t)USBD_FAIL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_DFU_SOF
* handle SOF event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_DFU_SOF(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_DFU_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_DFU_DeviceQualifierDesc);
return USBD_DFU_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_DFU_GetUsrStringDesc
* Manages the transfer of memory interfaces string descriptors.
* @param pdev: device instance
* @param index: descriptor index
* @param length : pointer data length
* @retval pointer to the descriptor table or NULL if the descriptor is not supported.
*/
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
static uint8_t *USBD_DFU_GetUsrStringDesc(USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length)
{
static uint8_t USBD_StrDesc[255];
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
/* Check if the requested string interface is supported */
if (index <= (USBD_IDX_INTERFACE_STR + USBD_DFU_MAX_ITF_NUM))
{
USBD_GetString((uint8_t *)DfuInterface->pStrDesc, USBD_StrDesc, length);
return USBD_StrDesc;
}
else
{
/* Not supported Interface Descriptor index */
*length = 0U;
return NULL;
}
}
#endif /* USBD_SUPPORT_USER_STRING_DESC */
/**
* @brief USBD_MSC_RegisterStorage
* @param pdev: device instance
* @param fops: storage callback
* @retval status
*/
uint8_t USBD_DFU_RegisterMedia(USBD_HandleTypeDef *pdev,
USBD_DFU_MediaTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/******************************************************************************
DFU Class requests management
******************************************************************************/
/**
* @brief DFU_Detach
* Handles the DFU DETACH request.
* @param pdev: device instance
* @param req: pointer to the request structure.
* @retval None.
*/
static void DFU_Detach(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_DFUFuncDescTypeDef *pDfuFunc = (USBD_DFUFuncDescTypeDef *)USBD_DFU_GetDfuFuncDesc(pdev->pConfDesc);
if ((hdfu == NULL) || (pDfuFunc == NULL))
{
return;
}
if ((hdfu->dev_state == DFU_STATE_IDLE) ||
(hdfu->dev_state == DFU_STATE_DNLOAD_SYNC) ||
(hdfu->dev_state == DFU_STATE_DNLOAD_IDLE) ||
(hdfu->dev_state == DFU_STATE_MANIFEST_SYNC) ||
(hdfu->dev_state == DFU_STATE_UPLOAD_IDLE))
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[0] = DFU_ERROR_NONE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U; /*bwPollTimeout=0ms*/
hdfu->dev_status[4] = hdfu->dev_state;
hdfu->dev_status[5] = 0U; /*iString*/
hdfu->wblock_num = 0U;
hdfu->wlength = 0U;
}
/* Check the detach capability in the DFU functional descriptor */
if ((pDfuFunc->bmAttributes & DFU_DETACH_MASK) != 0U)
{
/* Perform an Attach-Detach operation on USB bus */
(void)USBD_Stop(pdev);
(void)USBD_Start(pdev);
}
else
{
/* Wait for the period of time specified in Detach request */
USBD_Delay((uint32_t)req->wValue);
}
}
/**
* @brief DFU_Download
* Handles the DFU DNLOAD request.
* @param pdev: device instance
* @param req: pointer to the request structure
* @retval None
*/
static void DFU_Download(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
uint32_t VendorStatus = 0U;
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
if (hdfu == NULL)
{
return;
}
/* Data setup request */
if (req->wLength > 0U)
{
if ((hdfu->dev_state == DFU_STATE_IDLE) || (hdfu->dev_state == DFU_STATE_DNLOAD_IDLE))
{
/* Update the global length and block number */
hdfu->wblock_num = req->wValue;
hdfu->wlength = MIN(req->wLength, USBD_DFU_XFER_SIZE);
/* Update the state machine */
hdfu->dev_state = DFU_STATE_DNLOAD_SYNC;
hdfu->dev_status[4] = hdfu->dev_state;
/* Prepare the reception of the buffer over EP0 */
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)hdfu->buffer.d8, hdfu->wlength);
}
/* Unsupported state */
else
{
/* Call the error management function (command will be NAKed */
USBD_CtlError(pdev, req);
}
}
/* 0 Data DNLOAD request */
else
{
/* End of DNLOAD operation */
if ((hdfu->dev_state == DFU_STATE_DNLOAD_IDLE) || (hdfu->dev_state == DFU_STATE_IDLE))
{
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
if (DfuInterface->VendorCheck(hdfu->buffer.d8, IS_DFU_SETADDRESSPOINTER, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
else
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
{
hdfu->manif_state = DFU_MANIFEST_IN_PROGRESS;
hdfu->dev_state = DFU_STATE_MANIFEST_SYNC;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
}
else
{
/* Call the error management function (command will be NAKed */
USBD_CtlError(pdev, req);
}
}
}
/**
* @brief DFU_Upload
* Handles the DFU UPLOAD request.
* @param pdev: instance
* @param req: pointer to the request structure
* @retval status
*/
static void DFU_Upload(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
uint8_t *phaddr;
uint32_t addr;
uint32_t CmdLength;
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
uint32_t VendorStatus = 0U;
uint8_t VendorCmdLength = 0U;
uint8_t VendorCmdBuffer[DFU_VENDOR_CMD_MAX];
uint8_t idx;
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
if (hdfu == NULL)
{
return;
}
/* Data setup request */
if (req->wLength > 0U)
{
if ((hdfu->dev_state == DFU_STATE_IDLE) || (hdfu->dev_state == DFU_STATE_UPLOAD_IDLE))
{
/* Update the global length and block number */
hdfu->wblock_num = req->wValue;
hdfu->wlength = MIN(req->wLength, USBD_DFU_XFER_SIZE);
/* DFU Get Command */
if (hdfu->wblock_num == 0U)
{
/* Update the state machine */
hdfu->dev_state = (hdfu->wlength > 3U) ? DFU_STATE_IDLE : DFU_STATE_UPLOAD_IDLE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
/* Store the values of all supported commands */
hdfu->buffer.d8[0] = DFU_CMD_GETCOMMANDS;
hdfu->buffer.d8[1] = DFU_CMD_SETADDRESSPOINTER;
hdfu->buffer.d8[2] = DFU_CMD_ERASE;
CmdLength = 3U;
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
if (DfuInterface->GetVendorCMD != NULL)
{
(void)DfuInterface->GetVendorCMD(VendorCmdBuffer, (uint8_t *)&VendorCmdLength);
for (idx = 0U; idx < MIN(VendorCmdLength, DFU_VENDOR_CMD_MAX); idx++)
{
hdfu->buffer.d8[idx + 3U] = VendorCmdBuffer[idx];
}
CmdLength += MIN(VendorCmdLength, DFU_VENDOR_CMD_MAX);
}
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
/* Send the status data over EP0 */
(void)USBD_CtlSendData(pdev, (uint8_t *)(&(hdfu->buffer.d8[0])), CmdLength);
}
else if (hdfu->wblock_num > 1U)
{
hdfu->dev_state = DFU_STATE_UPLOAD_IDLE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
/* Vendor specific DFU CMD */
if (DfuInterface->VendorUploadCMD(hdfu->data_ptr, hdfu->wblock_num, &VendorStatus) != USBD_OK)
{
/* Update the state machine */
hdfu->dev_state = DFU_ERROR_STALLEDPKT;
hdfu->dev_status[0] = (uint8_t)VendorStatus;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
/* Call the error management function (command will be NAKed) */
USBD_CtlError(pdev, req);
}
if (VendorStatus == IS_DFU_PHY_ADDRESS)
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
{
addr = ((hdfu->wblock_num - 2U) * USBD_DFU_XFER_SIZE) + hdfu->data_ptr;
/* Return the physical address where data are stored */
phaddr = DfuInterface->Read((uint8_t *)addr, hdfu->buffer.d8, hdfu->wlength);
if (phaddr == NULL)
{
hdfu->dev_state = DFU_ERROR_STALLEDPKT;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
/* Call the error management function (command will be NAKed) */
USBD_CtlError(pdev, req);
}
else
{
/* Send the status data over EP0 */
(void)USBD_CtlSendData(pdev, phaddr, hdfu->wlength);
}
}
}
else /* unsupported hdfu->wblock_num */
{
hdfu->dev_state = DFU_ERROR_STALLEDPKT;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
/* Call the error management function (command will be NAKed) */
USBD_CtlError(pdev, req);
}
}
/* Unsupported state */
else
{
hdfu->wlength = 0U;
hdfu->wblock_num = 0U;
/* Call the error management function (command will be NAKed) */
USBD_CtlError(pdev, req);
}
}
/* No Data setup request */
else
{
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
}
/**
* @brief DFU_GetStatus
* Handles the DFU GETSTATUS request.
* @param pdev: instance
* @retval status
*/
static void DFU_GetStatus(USBD_HandleTypeDef *pdev)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
USBD_DFUFuncDescTypeDef *pDfuFunc = (USBD_DFUFuncDescTypeDef *)USBD_DFU_GetDfuFuncDesc(pdev->pConfDesc);
if ((hdfu == NULL) || (DfuInterface == NULL) || (pDfuFunc == NULL))
{
return;
}
switch (hdfu->dev_state)
{
case DFU_STATE_DNLOAD_SYNC:
if (hdfu->wlength != 0U)
{
hdfu->dev_state = DFU_STATE_DNLOAD_BUSY;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
if ((hdfu->wblock_num == 0U) && (hdfu->buffer.d8[0] == DFU_CMD_ERASE))
{
DfuInterface->GetStatus(hdfu->data_ptr, DFU_MEDIA_ERASE, hdfu->dev_status);
}
else
{
DfuInterface->GetStatus(hdfu->data_ptr, DFU_MEDIA_PROGRAM, hdfu->dev_status);
}
}
else /* (hdfu->wlength == 0U) */
{
hdfu->dev_state = DFU_STATE_DNLOAD_IDLE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
break;
case DFU_STATE_MANIFEST_SYNC:
if (hdfu->manif_state == DFU_MANIFEST_IN_PROGRESS)
{
hdfu->dev_state = DFU_STATE_MANIFEST;
hdfu->dev_status[1] = 1U; /* bwPollTimeout = 1ms */
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
else
{
if ((hdfu->manif_state == DFU_MANIFEST_COMPLETE) &&
((pDfuFunc->bmAttributes & DFU_MANIFEST_MASK) != 0U))
{
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
}
}
break;
default:
break;
}
/* Send the status data over EP0 */
(void)USBD_CtlSendData(pdev, (uint8_t *)(&(hdfu->dev_status[0])), 6U);
}
/**
* @brief DFU_ClearStatus
* Handles the DFU CLRSTATUS request.
* @param pdev: device instance
* @retval status
*/
static void DFU_ClearStatus(USBD_HandleTypeDef *pdev)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hdfu == NULL)
{
return;
}
if (hdfu->dev_state == DFU_STATE_ERROR)
{
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[0] = DFU_ERROR_NONE; /* bStatus */
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U; /* bwPollTimeout=0ms */
hdfu->dev_status[4] = hdfu->dev_state; /* bState */
hdfu->dev_status[5] = 0U; /* iString */
}
else
{
/* State Error */
hdfu->dev_state = DFU_STATE_ERROR;
hdfu->dev_status[0] = DFU_ERROR_UNKNOWN; /* bStatus */
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U; /* bwPollTimeout=0ms */
hdfu->dev_status[4] = hdfu->dev_state; /* bState */
hdfu->dev_status[5] = 0U; /* iString */
}
}
/**
* @brief DFU_GetState
* Handles the DFU GETSTATE request.
* @param pdev: device instance
* @retval None
*/
static void DFU_GetState(USBD_HandleTypeDef *pdev)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hdfu == NULL)
{
return;
}
/* Return the current state of the DFU interface */
(void)USBD_CtlSendData(pdev, &hdfu->dev_state, 1U);
}
/**
* @brief DFU_Abort
* Handles the DFU ABORT request.
* @param pdev: device instance
* @retval None
*/
static void DFU_Abort(USBD_HandleTypeDef *pdev)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hdfu == NULL)
{
return;
}
if ((hdfu->dev_state == DFU_STATE_IDLE) ||
(hdfu->dev_state == DFU_STATE_DNLOAD_SYNC) ||
(hdfu->dev_state == DFU_STATE_DNLOAD_IDLE) ||
(hdfu->dev_state == DFU_STATE_MANIFEST_SYNC) ||
(hdfu->dev_state == DFU_STATE_UPLOAD_IDLE))
{
hdfu->dev_state = DFU_STATE_IDLE;
hdfu->dev_status[0] = DFU_ERROR_NONE;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U; /* bwPollTimeout=0ms */
hdfu->dev_status[4] = hdfu->dev_state;
hdfu->dev_status[5] = 0U; /* iString */
hdfu->wblock_num = 0U;
hdfu->wlength = 0U;
}
}
/**
* @brief DFU_Leave
* Handles the sub-protocol DFU leave DFU mode request (leaves DFU mode
* and resets device to jump to user loaded code).
* @param pdev: device instance
* @retval None
*/
static void DFU_Leave(USBD_HandleTypeDef *pdev)
{
USBD_DFU_HandleTypeDef *hdfu = (USBD_DFU_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_DFU_MediaTypeDef *DfuInterface = (USBD_DFU_MediaTypeDef *)pdev->pUserData[pdev->classId];
USBD_DFUFuncDescTypeDef *pDfuFunc = (USBD_DFUFuncDescTypeDef *)USBD_DFU_GetDfuFuncDesc(pdev->pConfDesc);
if ((hdfu == NULL) || (DfuInterface == NULL) || (pDfuFunc == NULL))
{
return;
}
hdfu->manif_state = DFU_MANIFEST_COMPLETE;
if ((pDfuFunc->bmAttributes & DFU_MANIFEST_MASK) != 0U)
{
hdfu->dev_state = DFU_STATE_MANIFEST_SYNC;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
return;
}
else
{
hdfu->dev_state = DFU_STATE_MANIFEST_WAIT_RESET;
hdfu->dev_status[1] = 0U;
hdfu->dev_status[2] = 0U;
hdfu->dev_status[3] = 0U;
hdfu->dev_status[4] = hdfu->dev_state;
/* Disconnect the USB device */
(void)USBD_Stop(pdev);
#if (USBD_DFU_VENDOR_EXIT_ENABLED == 1U)
/* Jump should be ensured by user application */
DfuInterface->LeaveDFU(hdfu->data_ptr);
#else
/* Generate system reset to allow jumping to the user code */
NVIC_SystemReset();
#endif /* USBD_DFU_VENDOR_EXIT_ENABLED */
/* The next instructions will not be reached (system reset) */
}
}
/**
* @brief USBD_DFU_GetDfuFuncDesc
* This function return the DFU descriptor
* @param pdev: device instance
* @param pConfDesc: pointer to Bos descriptor
* @retval pointer to the DFU descriptor
*/
static void *USBD_DFU_GetDfuFuncDesc(uint8_t *pConfDesc)
{
USBD_ConfigDescTypeDef *desc = (USBD_ConfigDescTypeDef *)(void *)pConfDesc;
USBD_DescHeaderTypeDef *pdesc = (USBD_DescHeaderTypeDef *)(void *)pConfDesc;
uint8_t *pDfuDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_GetNextDesc((uint8_t *)pdesc, &ptr);
if (pdesc->bDescriptorType == DFU_DESCRIPTOR_TYPE)
{
pDfuDesc = (uint8_t *)pdesc;
break;
}
}
}
return pDfuDesc;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU | D://workCode//uploadProject\stm32_mw_usb_device\Class\DFU\Src\usbd_dfu_media_template.c | /**
******************************************************************************
* @file usbd_dfu_media_template.c
* @author MCD Application Team
* @brief Memory management layer
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_dfu_media_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Extern function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
uint16_t MEM_If_Init(void);
uint16_t MEM_If_Erase(uint32_t Add);
uint16_t MEM_If_Write(uint8_t *src, uint8_t *dest, uint32_t Len);
uint8_t *MEM_If_Read(uint8_t *src, uint8_t *dest, uint32_t Len);
uint16_t MEM_If_DeInit(void);
uint16_t MEM_If_GetStatus(uint32_t Add, uint8_t Cmd, uint8_t *buffer);
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
uint16_t MEM_If_GetVendorCMD(uint8_t *cmd, uint8_t *cmdlength);
uint16_t MEM_If_VendorDownloadCMD(uint8_t *pbuf, uint32_t BlockNumber, uint32_t wlength, uint32_t *status);
uint16_t MEM_If_VendorUploadCMD(uint32_t Add, uint32_t BlockNumber, uint32_t *status);
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
uint16_t MEM_If_VendorCheck(uint8_t *pbuf, uint32_t ReqType, uint32_t *status);
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
#if (USBD_DFU_VENDOR_EXIT_ENABLED == 1U)
uint16_t MEM_If_LeaveDFU(uint32_t Add);
#endif /* USBD_DFU_VENDOR_EXIT_ENABLED */
USBD_DFU_MediaTypeDef USBD_DFU_MEDIA_Template_fops =
{
(uint8_t *)"DFU MEDIA",
MEM_If_Init,
MEM_If_DeInit,
MEM_If_Erase,
MEM_If_Write,
MEM_If_Read,
MEM_If_GetStatus,
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
MEM_If_GetVendorCMD,
MEM_If_VendorDownloadCMD,
MEM_If_VendorUploadCMD,
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
MEM_If_VendorCheck,
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
#if (USBD_DFU_VENDOR_EXIT_ENABLED == 1U)
MEM_If_LeaveDFU
#endif /* USBD_DFU_VENDOR_EXIT_ENABLED */
};
/**
* @brief MEM_If_Init
* Memory initialization routine.
* @param None
* @retval 0 if operation is successful, MAL_FAIL else.
*/
uint16_t MEM_If_Init(void)
{
return 0;
}
/**
* @brief MEM_If_DeInit
* Memory deinitialization routine.
* @param None
* @retval 0 if operation is successful, MAL_FAIL else.
*/
uint16_t MEM_If_DeInit(void)
{
return 0;
}
/**
* @brief MEM_If_Erase
* Erase sector.
* @param Add: Address of sector to be erased.
* @retval 0 if operation is successful, MAL_FAIL else.
*/
uint16_t MEM_If_Erase(uint32_t Add)
{
UNUSED(Add);
return 0;
}
/**
* @brief MEM_If_Write
* Memory write routine.
* @param Add: Address to be written to.
* @param Len: Number of data to be written (in bytes).
* @retval 0 if operation is successful, MAL_FAIL else.
*/
uint16_t MEM_If_Write(uint8_t *src, uint8_t *dest, uint32_t Len)
{
UNUSED(src);
UNUSED(dest);
UNUSED(Len);
return 0;
}
/**
* @brief MEM_If_Read
* Memory read routine.
* @param Add: Address to be read from.
* @param Len: Number of data to be read (in bytes).
* @retval Pointer to the physical address where data should be read.
*/
uint8_t *MEM_If_Read(uint8_t *src, uint8_t *dest, uint32_t Len)
{
UNUSED(src);
UNUSED(dest);
UNUSED(Len);
/* Return a valid address to avoid HardFault */
return NULL;
}
/**
* @brief Flash_If_GetStatus
* Memory read routine.
* @param Add: Address to be read from.
* @param cmd: Number of data to be read (in bytes).
* @retval Pointer to the physical address where data should be read.
*/
uint16_t MEM_If_GetStatus(uint32_t Add, uint8_t Cmd, uint8_t *buffer)
{
UNUSED(Add);
UNUSED(buffer);
switch (Cmd)
{
case DFU_MEDIA_PROGRAM:
break;
case DFU_MEDIA_ERASE:
default:
break;
}
return (0);
}
#if (USBD_DFU_VENDOR_CMD_ENABLED == 1U)
/**
* @brief Get supported vendor specific commands
* @param pointer to supported vendor commands
* @param pointer to length of supported vendor commands
* @retval 0 if operation is successful
*/
uint16_t MEM_If_GetVendorCMD(uint8_t *cmd, uint8_t *cmdlength)
{
UNUSED(cmd);
UNUSED(cmdlength);
return 0U;
}
/**
* @brief Vendor specific download commands
* @param pbuf DFU data buffer
* @param BlockNumber DFU memory block number
* @param wLength DFU request length
* @param pointer to DFU status
* @retval 0 if operation is successful
*/
uint16_t MEM_If_VendorDownloadCMD(uint8_t *pbuf, uint32_t BlockNumber, uint32_t wlength, uint32_t *status)
{
UNUSED(pbuf);
UNUSED(BlockNumber);
UNUSED(wlength);
UNUSED(status);
return 0U;
}
/**
* @brief Vendor specific upload commands
* @param Add memory Address
* @param BlockNumber DFU memory block number
* @param pointer to DFU status
* @retval 0 if operation is successful
*/
uint16_t MEM_If_VendorUploadCMD(uint32_t Add, uint32_t BlockNumber, uint32_t *status)
{
UNUSED(Add);
UNUSED(BlockNumber);
UNUSED(status);
return 0U;
}
#endif /* USBD_DFU_VENDOR_CMD_ENABLED */
#if (USBD_DFU_VENDOR_CHECK_ENABLED == 1U)
/**
* @brief Vendor memory check
* @param pbuf DFU data buffer
* @param ReqType IS_DFU_SETADDRESSPOINTER/DOWNLOAD/UPLOAD
* @param pointer to DFU status
* @retval 0 if operation is successful
*/
uint16_t MEM_If_VendorCheck(uint8_t *pbuf, uint32_t ReqType, uint32_t *status)
{
UNUSED(pbuf);
UNUSED(ReqType);
UNUSED(status);
return 0U;
}
#endif /* USBD_DFU_VENDOR_CHECK_ENABLED */
#if (USBD_DFU_VENDOR_EXIT_ENABLED == 1U)
/**
* @brief Vendor Leave DFU
* @param Application address
* @retval 0 if operation is successful
*/
uint16_t MEM_If_LeaveDFU(uint32_t Add)
{
UNUSED(Add);
return 0U;
}
#endif /* USBD_DFU_VENDOR_EXIT_ENABLED */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\HID | D://workCode//uploadProject\stm32_mw_usb_device\Class\HID\Inc\usbd_hid.h | /**
******************************************************************************
* @file usbd_hid.h
* @author MCD Application Team
* @brief Header file for the usbd_hid_core.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_HID_H
#define __USB_HID_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_HID
* @brief This file is the Header file for usbd_hid.c
* @{
*/
/** @defgroup USBD_HID_Exported_Defines
* @{
*/
#ifndef HID_EPIN_ADDR
#define HID_EPIN_ADDR 0x81U
#endif /* HID_EPIN_ADDR */
#define HID_EPIN_SIZE 0x04U
#define USB_HID_CONFIG_DESC_SIZ 34U
#define USB_HID_DESC_SIZ 9U
#define HID_MOUSE_REPORT_DESC_SIZE 74U
#define HID_DESCRIPTOR_TYPE 0x21U
#define HID_REPORT_DESC 0x22U
#ifndef HID_HS_BINTERVAL
#define HID_HS_BINTERVAL 0x07U
#endif /* HID_HS_BINTERVAL */
#ifndef HID_FS_BINTERVAL
#define HID_FS_BINTERVAL 0x0AU
#endif /* HID_FS_BINTERVAL */
#define USBD_HID_REQ_SET_PROTOCOL 0x0BU
#define USBD_HID_REQ_GET_PROTOCOL 0x03U
#define USBD_HID_REQ_SET_IDLE 0x0AU
#define USBD_HID_REQ_GET_IDLE 0x02U
#define USBD_HID_REQ_SET_REPORT 0x09U
#define USBD_HID_REQ_GET_REPORT 0x01U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef enum
{
USBD_HID_IDLE = 0,
USBD_HID_BUSY,
} USBD_HID_StateTypeDef;
typedef struct
{
uint32_t Protocol;
uint32_t IdleState;
uint32_t AltSetting;
USBD_HID_StateTypeDef state;
} USBD_HID_HandleTypeDef;
/*
* HID Class specification version 1.1
* 6.2.1 HID Descriptor
*/
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdHID;
uint8_t bCountryCode;
uint8_t bNumDescriptors;
uint8_t bHIDDescriptorType;
uint16_t wItemLength;
} __PACKED USBD_HIDDescTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_HID;
#define USBD_HID_CLASS &USBD_HID
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_HID_SendReport(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len, uint8_t ClassId);
#else
uint8_t USBD_HID_SendReport(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len);
#endif /* USE_USBD_COMPOSITE */
uint32_t USBD_HID_GetPollingInterval(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_HID_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\HID | D://workCode//uploadProject\stm32_mw_usb_device\Class\HID\Src\usbd_hid.c | /**
******************************************************************************
* @file usbd_hid.c
* @author MCD Application Team
* @brief This file provides the HID core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* HID Class Description
* ===================================================================
* This module manages the HID class V1.11 following the "Device Class Definition
* for Human Interface Devices (HID) Version 1.11 Jun 27, 2001".
* This driver implements the following aspects of the specification:
* - The Boot Interface Subclass
* - The Mouse protocol
* - Usage Page : Generic Desktop
* - Usage : Joystick
* - Collection : Application
*
* @note In HS mode and when the DMA is used, all variables and data structures
* dealing with the DMA during the transaction process should be 32-bit aligned.
*
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_hid.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_HID
* @brief usbd core module
* @{
*/
/** @defgroup USBD_HID_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_HID_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_HID_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_HID_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_HID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_HID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_HID_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_HID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_HID_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_HID_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_HID_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_HID_GetDeviceQualifierDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_HID_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_HID =
{
USBD_HID_Init,
USBD_HID_DeInit,
USBD_HID_Setup,
NULL, /* EP0_TxSent */
NULL, /* EP0_RxReady */
USBD_HID_DataIn, /* DataIn */
NULL, /* DataOut */
NULL, /* SOF */
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_HID_GetHSCfgDesc,
USBD_HID_GetFSCfgDesc,
USBD_HID_GetOtherSpeedCfgDesc,
USBD_HID_GetDeviceQualifierDesc,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB HID device FS Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_HID_CfgDesc[USB_HID_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_HID_CONFIG_DESC_SIZ, /* wTotalLength: Bytes returned */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xE0, /* bmAttributes: Bus Powered according to user configuration */
#else
0xA0, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/************** Descriptor of Joystick Mouse interface ****************/
/* 09 */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints */
0x03, /* bInterfaceClass: HID */
0x01, /* bInterfaceSubClass : 1=BOOT, 0=no boot */
0x02, /* nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse */
0, /* iInterface: Index of string descriptor */
/******************** Descriptor of Joystick Mouse HID ********************/
/* 18 */
0x09, /* bLength: HID Descriptor size */
HID_DESCRIPTOR_TYPE, /* bDescriptorType: HID */
0x11, /* bcdHID: HID Class Spec release number */
0x01,
0x00, /* bCountryCode: Hardware target country */
0x01, /* bNumDescriptors: Number of HID class descriptors to follow */
0x22, /* bDescriptorType */
HID_MOUSE_REPORT_DESC_SIZE, /* wItemLength: Total length of Report descriptor */
0x00,
/******************** Descriptor of Mouse endpoint ********************/
/* 27 */
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType:*/
HID_EPIN_ADDR, /* bEndpointAddress: Endpoint Address (IN) */
0x03, /* bmAttributes: Interrupt endpoint */
HID_EPIN_SIZE, /* wMaxPacketSize: 4 Bytes max */
0x00,
HID_FS_BINTERVAL, /* bInterval: Polling Interval */
/* 34 */
};
#endif /* USE_USBD_COMPOSITE */
/* USB HID device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_HID_Desc[USB_HID_DESC_SIZ] __ALIGN_END =
{
/* 18 */
0x09, /* bLength: HID Descriptor size */
HID_DESCRIPTOR_TYPE, /* bDescriptorType: HID */
0x11, /* bcdHID: HID Class Spec release number */
0x01,
0x00, /* bCountryCode: Hardware target country */
0x01, /* bNumDescriptors: Number of HID class descriptors to follow */
0x22, /* bDescriptorType */
HID_MOUSE_REPORT_DESC_SIZE, /* wItemLength: Total length of Report descriptor */
0x00,
};
#ifndef USE_USBD_COMPOSITE
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_HID_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
__ALIGN_BEGIN static uint8_t HID_MOUSE_ReportDesc[HID_MOUSE_REPORT_DESC_SIZE] __ALIGN_END =
{
0x05, 0x01, /* Usage Page (Generic Desktop Ctrls) */
0x09, 0x02, /* Usage (Mouse) */
0xA1, 0x01, /* Collection (Application) */
0x09, 0x01, /* Usage (Pointer) */
0xA1, 0x00, /* Collection (Physical) */
0x05, 0x09, /* Usage Page (Button) */
0x19, 0x01, /* Usage Minimum (0x01) */
0x29, 0x03, /* Usage Maximum (0x03) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x95, 0x03, /* Report Count (3) */
0x75, 0x01, /* Report Size (1) */
0x81, 0x02, /* Input (Data,Var,Abs) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x05, /* Report Size (5) */
0x81, 0x01, /* Input (Const,Array,Abs) */
0x05, 0x01, /* Usage Page (Generic Desktop Ctrls) */
0x09, 0x30, /* Usage (X) */
0x09, 0x31, /* Usage (Y) */
0x09, 0x38, /* Usage (Wheel) */
0x15, 0x81, /* Logical Minimum (-127) */
0x25, 0x7F, /* Logical Maximum (127) */
0x75, 0x08, /* Report Size (8) */
0x95, 0x03, /* Report Count (3) */
0x81, 0x06, /* Input (Data,Var,Rel) */
0xC0, /* End Collection */
0x09, 0x3C, /* Usage (Motion Wakeup) */
0x05, 0xFF, /* Usage Page (Reserved 0xFF) */
0x09, 0x01, /* Usage (0x01) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x95, 0x02, /* Report Count (2) */
0xB1, 0x22, /* Feature (Data,Var,Abs,NoWrp) */
0x75, 0x06, /* Report Size (6) */
0x95, 0x01, /* Report Count (1) */
0xB1, 0x01, /* Feature (Const,Array,Abs,NoWrp) */
0xC0 /* End Collection */
};
static uint8_t HIDInEpAdd = HID_EPIN_ADDR;
/**
* @}
*/
/** @defgroup USBD_HID_Private_Functions
* @{
*/
/**
* @brief USBD_HID_Init
* Initialize the HID interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_HID_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_HID_HandleTypeDef *hhid;
hhid = (USBD_HID_HandleTypeDef *)USBD_malloc(sizeof(USBD_HID_HandleTypeDef));
if (hhid == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)hhid;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
HIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
pdev->ep_in[HIDInEpAdd & 0xFU].bInterval = HID_HS_BINTERVAL;
}
else /* LOW and FULL-speed endpoints */
{
pdev->ep_in[HIDInEpAdd & 0xFU].bInterval = HID_FS_BINTERVAL;
}
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, HIDInEpAdd, USBD_EP_TYPE_INTR, HID_EPIN_SIZE);
pdev->ep_in[HIDInEpAdd & 0xFU].is_used = 1U;
hhid->state = USBD_HID_IDLE;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_HID_DeInit
* DeInitialize the HID layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_HID_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
HIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close HID EPs */
(void)USBD_LL_CloseEP(pdev, HIDInEpAdd);
pdev->ep_in[HIDInEpAdd & 0xFU].is_used = 0U;
pdev->ep_in[HIDInEpAdd & 0xFU].bInterval = 0U;
/* Free allocated memory */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_HID_Setup
* Handle the HID specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_HID_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_HID_HandleTypeDef *hhid = (USBD_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint16_t len;
uint8_t *pbuf;
uint16_t status_info = 0U;
if (hhid == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS :
switch (req->bRequest)
{
case USBD_HID_REQ_SET_PROTOCOL:
hhid->Protocol = (uint8_t)(req->wValue);
break;
case USBD_HID_REQ_GET_PROTOCOL:
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->Protocol, 1U);
break;
case USBD_HID_REQ_SET_IDLE:
hhid->IdleState = (uint8_t)(req->wValue >> 8);
break;
case USBD_HID_REQ_GET_IDLE:
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->IdleState, 1U);
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_DESCRIPTOR:
if ((req->wValue >> 8) == HID_REPORT_DESC)
{
len = MIN(HID_MOUSE_REPORT_DESC_SIZE, req->wLength);
pbuf = HID_MOUSE_ReportDesc;
}
else if ((req->wValue >> 8) == HID_DESCRIPTOR_TYPE)
{
pbuf = USBD_HID_Desc;
len = MIN(USB_HID_DESC_SIZ, req->wLength);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
(void)USBD_CtlSendData(pdev, pbuf, len);
break;
case USB_REQ_GET_INTERFACE :
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&hhid->AltSetting, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
hhid->AltSetting = (uint8_t)(req->wValue);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_HID_SendReport
* Send HID Report
* @param pdev: device instance
* @param buff: pointer to report
* @param ClassId: The Class ID
* @retval status
*/
#ifdef USE_USBD_COMPOSITE
uint8_t USBD_HID_SendReport(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len, uint8_t ClassId)
{
USBD_HID_HandleTypeDef *hhid = (USBD_HID_HandleTypeDef *)pdev->pClassDataCmsit[ClassId];
#else
uint8_t USBD_HID_SendReport(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len)
{
USBD_HID_HandleTypeDef *hhid = (USBD_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#endif /* USE_USBD_COMPOSITE */
if (hhid == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
HIDInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, ClassId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (hhid->state == USBD_HID_IDLE)
{
hhid->state = USBD_HID_BUSY;
(void)USBD_LL_Transmit(pdev, HIDInEpAdd, report, len);
}
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_HID_GetPollingInterval
* return polling interval from endpoint descriptor
* @param pdev: device instance
* @retval polling interval
*/
uint32_t USBD_HID_GetPollingInterval(USBD_HandleTypeDef *pdev)
{
uint32_t polling_interval;
/* HIGH-speed endpoints */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Sets the data transfer polling interval for high speed transfers.
Values between 1..16 are allowed. Values correspond to interval
of 2 ^ (bInterval-1). This option (8 ms, corresponds to HID_HS_BINTERVAL */
polling_interval = (((1U << (HID_HS_BINTERVAL - 1U))) / 8U);
}
else /* LOW and FULL-speed endpoints */
{
/* Sets the data transfer polling interval for low and full
speed transfers */
polling_interval = HID_FS_BINTERVAL;
}
return ((uint32_t)(polling_interval));
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_HID_GetCfgFSDesc
* return FS configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_HID_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_HID_CfgDesc, HID_EPIN_ADDR);
if (pEpDesc != NULL)
{
pEpDesc->bInterval = HID_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_HID_CfgDesc);
return USBD_HID_CfgDesc;
}
/**
* @brief USBD_HID_GetCfgHSDesc
* return HS configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_HID_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_HID_CfgDesc, HID_EPIN_ADDR);
if (pEpDesc != NULL)
{
pEpDesc->bInterval = HID_HS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_HID_CfgDesc);
return USBD_HID_CfgDesc;
}
/**
* @brief USBD_HID_GetOtherSpeedCfgDesc
* return other speed configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_HID_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_HID_CfgDesc, HID_EPIN_ADDR);
if (pEpDesc != NULL)
{
pEpDesc->bInterval = HID_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_HID_CfgDesc);
return USBD_HID_CfgDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_HID_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_HID_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
/* Ensure that the FIFO is empty before a new transfer, this condition could
be caused by a new transfer before the end of the previous transfer */
((USBD_HID_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId])->state = USBD_HID_IDLE;
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_HID_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_HID_DeviceQualifierDesc);
return USBD_HID_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Inc\usbd_msc.h | /**
******************************************************************************
* @file usbd_msc.h
* @author MCD Application Team
* @brief Header for the usbd_msc.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_MSC_H
#define __USBD_MSC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc_bot.h"
#include "usbd_msc_scsi.h"
#include "usbd_ioreq.h"
/** @addtogroup USBD_MSC_BOT
* @{
*/
/** @defgroup USBD_MSC
* @brief This file is the Header file for usbd_msc.c
* @{
*/
/** @defgroup USBD_BOT_Exported_Defines
* @{
*/
/* MSC Class Config */
#ifndef MSC_MEDIA_PACKET
#define MSC_MEDIA_PACKET 512U
#endif /* MSC_MEDIA_PACKET */
#define MSC_MAX_FS_PACKET 0x40U
#define MSC_MAX_HS_PACKET 0x200U
#define BOT_GET_MAX_LUN 0xFE
#define BOT_RESET 0xFF
#define USB_MSC_CONFIG_DESC_SIZ 32
#ifndef MSC_EPIN_ADDR
#define MSC_EPIN_ADDR 0x81U
#endif /* MSC_EPIN_ADDR */
#ifndef MSC_EPOUT_ADDR
#define MSC_EPOUT_ADDR 0x01U
#endif /* MSC_EPOUT_ADDR */
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Types
* @{
*/
typedef struct _USBD_STORAGE
{
int8_t (* Init)(uint8_t lun);
int8_t (* GetCapacity)(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
int8_t (* IsReady)(uint8_t lun);
int8_t (* IsWriteProtected)(uint8_t lun);
int8_t (* Read)(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t (* Write)(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t (* GetMaxLun)(void);
int8_t *pInquiry;
} USBD_StorageTypeDef;
typedef struct
{
uint32_t max_lun;
uint32_t interface;
uint8_t bot_state;
uint8_t bot_status;
uint32_t bot_data_length;
uint8_t bot_data[MSC_MEDIA_PACKET];
USBD_MSC_BOT_CBWTypeDef cbw;
USBD_MSC_BOT_CSWTypeDef csw;
USBD_SCSI_SenseTypeDef scsi_sense [SENSE_LIST_DEEPTH];
uint8_t scsi_sense_head;
uint8_t scsi_sense_tail;
uint8_t scsi_medium_state;
uint16_t scsi_blk_size;
uint32_t scsi_blk_nbr;
uint32_t scsi_blk_addr;
uint32_t scsi_blk_len;
} USBD_MSC_BOT_HandleTypeDef;
/* Structure for MSC process */
extern USBD_ClassTypeDef USBD_MSC;
#define USBD_MSC_CLASS &USBD_MSC
uint8_t USBD_MSC_RegisterStorage(USBD_HandleTypeDef *pdev,
USBD_StorageTypeDef *fops);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MSC_H */
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Inc\usbd_msc_bot.h | /**
******************************************************************************
* @file usbd_msc_bot.h
* @author MCD Application Team
* @brief Header for the usbd_msc_bot.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_MSC_BOT_H
#define __USBD_MSC_BOT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_core.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup MSC_BOT
* @brief This file is the Header file for usbd_msc_bot.c
* @{
*/
/** @defgroup USBD_CORE_Exported_Defines
* @{
*/
#define USBD_BOT_IDLE 0U /* Idle state */
#define USBD_BOT_DATA_OUT 1U /* Data Out state */
#define USBD_BOT_DATA_IN 2U /* Data In state */
#define USBD_BOT_LAST_DATA_IN 3U /* Last Data In Last */
#define USBD_BOT_SEND_DATA 4U /* Send Immediate data */
#define USBD_BOT_NO_DATA 5U /* No data Stage */
#define USBD_BOT_CBW_SIGNATURE 0x43425355U
#define USBD_BOT_CSW_SIGNATURE 0x53425355U
#define USBD_BOT_CBW_LENGTH 31U
#define USBD_BOT_CSW_LENGTH 13U
#define USBD_BOT_MAX_DATA 256U
/* CSW Status Definitions */
#define USBD_CSW_CMD_PASSED 0x00U
#define USBD_CSW_CMD_FAILED 0x01U
#define USBD_CSW_PHASE_ERROR 0x02U
/* BOT Status */
#define USBD_BOT_STATUS_NORMAL 0U
#define USBD_BOT_STATUS_RECOVERY 1U
#define USBD_BOT_STATUS_ERROR 2U
#define USBD_DIR_IN 0U
#define USBD_DIR_OUT 1U
#define USBD_BOTH_DIR 2U
/**
* @}
*/
/** @defgroup MSC_CORE_Private_TypesDefinitions
* @{
*/
typedef struct
{
uint32_t dSignature;
uint32_t dTag;
uint32_t dDataLength;
uint8_t bmFlags;
uint8_t bLUN;
uint8_t bCBLength;
uint8_t CB[16];
uint8_t ReservedForAlign;
} USBD_MSC_BOT_CBWTypeDef;
typedef struct
{
uint32_t dSignature;
uint32_t dTag;
uint32_t dDataResidue;
uint8_t bStatus;
uint8_t ReservedForAlign[3];
} USBD_MSC_BOT_CSWTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_FunctionsPrototypes
* @{
*/
void MSC_BOT_Init(USBD_HandleTypeDef *pdev);
void MSC_BOT_Reset(USBD_HandleTypeDef *pdev);
void MSC_BOT_DeInit(USBD_HandleTypeDef *pdev);
void MSC_BOT_DataIn(USBD_HandleTypeDef *pdev,
uint8_t epnum);
void MSC_BOT_DataOut(USBD_HandleTypeDef *pdev,
uint8_t epnum);
void MSC_BOT_SendCSW(USBD_HandleTypeDef *pdev,
uint8_t CSW_Status);
void MSC_BOT_CplClrFeature(USBD_HandleTypeDef *pdev,
uint8_t epnum);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MSC_BOT_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Inc\usbd_msc_data.h | /**
******************************************************************************
* @file usbd_msc_data.h
* @author MCD Application Team
* @brief Header for the usbd_msc_data.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_MSC_DATA_H
#define __USBD_MSC_DATA_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_conf.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USB_INFO
* @brief general defines for the usb device library file
* @{
*/
/** @defgroup USB_INFO_Exported_Defines
* @{
*/
#define MODE_SENSE6_LEN 0x04U
#define MODE_SENSE10_LEN 0x08U
#define LENGTH_INQUIRY_PAGE00 0x06U
#define LENGTH_INQUIRY_PAGE80 0x08U
#define LENGTH_FORMAT_CAPACITIES 0x14U
/**
* @}
*/
/** @defgroup USBD_INFO_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_INFO_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_INFO_Exported_Variables
* @{
*/
extern uint8_t MSC_Page00_Inquiry_Data[LENGTH_INQUIRY_PAGE00];
extern uint8_t MSC_Page80_Inquiry_Data[LENGTH_INQUIRY_PAGE80];
extern uint8_t MSC_Mode_Sense6_data[MODE_SENSE6_LEN];
extern uint8_t MSC_Mode_Sense10_data[MODE_SENSE10_LEN];
/**
* @}
*/
/** @defgroup USBD_INFO_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MSC_DATA_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Inc\usbd_msc_scsi.h | /**
******************************************************************************
* @file usbd_msc_scsi.h
* @author MCD Application Team
* @brief Header for the usbd_msc_scsi.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_MSC_SCSI_H
#define __USBD_MSC_SCSI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_SCSI
* @brief header file for the storage disk file
* @{
*/
/** @defgroup USBD_SCSI_Exported_Defines
* @{
*/
#define SENSE_LIST_DEEPTH 4U
/* SCSI Commands */
#define SCSI_FORMAT_UNIT 0x04U
#define SCSI_INQUIRY 0x12U
#define SCSI_MODE_SELECT6 0x15U
#define SCSI_MODE_SELECT10 0x55U
#define SCSI_MODE_SENSE6 0x1AU
#define SCSI_MODE_SENSE10 0x5AU
#define SCSI_ALLOW_MEDIUM_REMOVAL 0x1EU
#define SCSI_READ6 0x08U
#define SCSI_READ10 0x28U
#define SCSI_READ12 0xA8U
#define SCSI_READ16 0x88U
#define SCSI_READ_CAPACITY10 0x25U
#define SCSI_READ_CAPACITY16 0x9EU
#define SCSI_REQUEST_SENSE 0x03U
#define SCSI_START_STOP_UNIT 0x1BU
#define SCSI_TEST_UNIT_READY 0x00U
#define SCSI_WRITE6 0x0AU
#define SCSI_WRITE10 0x2AU
#define SCSI_WRITE12 0xAAU
#define SCSI_WRITE16 0x8AU
#define SCSI_VERIFY10 0x2FU
#define SCSI_VERIFY12 0xAFU
#define SCSI_VERIFY16 0x8FU
#define SCSI_SEND_DIAGNOSTIC 0x1DU
#define SCSI_READ_FORMAT_CAPACITIES 0x23U
#define NO_SENSE 0U
#define RECOVERED_ERROR 1U
#define NOT_READY 2U
#define MEDIUM_ERROR 3U
#define HARDWARE_ERROR 4U
#define ILLEGAL_REQUEST 5U
#define UNIT_ATTENTION 6U
#define DATA_PROTECT 7U
#define BLANK_CHECK 8U
#define MSC_VENDOR_SPECIFIC 9U
#define COPY_ABORTED 10U
#define ABORTED_COMMAND 11U
#define VOLUME_OVERFLOW 13U
#define MISCOMPARE 14U
#define INVALID_CDB 0x20U
#define INVALID_FIELED_IN_COMMAND 0x24U
#define PARAMETER_LIST_LENGTH_ERROR 0x1AU
#define INVALID_FIELD_IN_PARAMETER_LIST 0x26U
#define ADDRESS_OUT_OF_RANGE 0x21U
#define MEDIUM_NOT_PRESENT 0x3AU
#define MEDIUM_HAVE_CHANGED 0x28U
#define WRITE_PROTECTED 0x27U
#define UNRECOVERED_READ_ERROR 0x11U
#define WRITE_FAULT 0x03U
#define READ_FORMAT_CAPACITY_DATA_LEN 0x0CU
#define READ_CAPACITY10_DATA_LEN 0x08U
#define REQUEST_SENSE_DATA_LEN 0x12U
#define STANDARD_INQUIRY_DATA_LEN 0x24U
#define BLKVFY 0x04U
#define SCSI_MEDIUM_UNLOCKED 0x00U
#define SCSI_MEDIUM_LOCKED 0x01U
#define SCSI_MEDIUM_EJECTED 0x02U
/**
* @}
*/
/** @defgroup USBD_SCSI_Exported_TypesDefinitions
* @{
*/
typedef struct _SENSE_ITEM
{
uint8_t Skey;
union
{
struct _ASCs
{
uint8_t ASC;
uint8_t ASCQ;
} b;
uint8_t ASC;
uint8_t *pData;
} w;
} USBD_SCSI_SenseTypeDef;
/**
* @}
*/
/** @defgroup USBD_SCSI_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_SCSI_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_SCSI_Exported_FunctionsPrototype
* @{
*/
int8_t SCSI_ProcessCmd(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *cmd);
void SCSI_SenseCode(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t sKey,
uint8_t ASC);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MSC_SCSI_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Inc\usbd_msc_storage_template.h | /**
******************************************************************************
* @file usbd_msc_storage.h
* @author MCD Application Team
* @brief Header file for the usbd_msc_storage.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_MSC_STORAGE_H
#define __USBD_MSC_STORAGE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_STORAGE
* @brief header file for the usbd_msc_storage.c file
* @{
*/
/** @defgroup USBD_STORAGE_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_STORAGE_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_STORAGE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_STORAGE_Exported_Variables
* @{
*/
extern USBD_StorageTypeDef USBD_MSC_Template_fops;
/**
* @}
*/
/** @defgroup USBD_STORAGE_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MSC_STORAGE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Src\usbd_msc.c | /**
******************************************************************************
* @file usbd_msc.c
* @author MCD Application Team
* @brief This file provides all the MSC core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* MSC Class Description
* ===================================================================
* This module manages the MSC class V1.0 following the "Universal
* Serial Bus Mass Storage Class (MSC) Bulk-Only Transport (BOT) Version 1.0
* Sep. 31, 1999".
* This driver implements the following aspects of the specification:
* - Bulk-Only Transport protocol
* - Subclass : SCSI transparent command set (ref. SCSI Primary Commands - 3 (SPC-3))
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_sd.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup MSC_CORE
* @brief Mass storage core module
* @{
*/
/** @defgroup MSC_CORE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup MSC_CORE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup MSC_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup MSC_CORE_Private_FunctionPrototypes
* @{
*/
uint8_t USBD_MSC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
uint8_t USBD_MSC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
uint8_t USBD_MSC_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
uint8_t USBD_MSC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t USBD_MSC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
#ifndef USE_USBD_COMPOSITE
uint8_t *USBD_MSC_GetHSCfgDesc(uint16_t *length);
uint8_t *USBD_MSC_GetFSCfgDesc(uint16_t *length);
uint8_t *USBD_MSC_GetOtherSpeedCfgDesc(uint16_t *length);
uint8_t *USBD_MSC_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup MSC_CORE_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_MSC =
{
USBD_MSC_Init,
USBD_MSC_DeInit,
USBD_MSC_Setup,
NULL, /*EP0_TxSent*/
NULL, /*EP0_RxReady*/
USBD_MSC_DataIn,
USBD_MSC_DataOut,
NULL, /*SOF */
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_MSC_GetHSCfgDesc,
USBD_MSC_GetFSCfgDesc,
USBD_MSC_GetOtherSpeedCfgDesc,
USBD_MSC_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
};
/* USB Mass storage device Configuration Descriptor */
#ifndef USE_USBD_COMPOSITE
/* USB Mass storage device Configuration Descriptor */
/* All Descriptors (Configuration, Interface, Endpoint, Class, Vendor */
__ALIGN_BEGIN static uint8_t USBD_MSC_CfgDesc[USB_MSC_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_MSC_CONFIG_DESC_SIZ,
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue */
0x04, /* iConfiguration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/******************** Mass Storage interface ********************/
0x09, /* bLength: Interface Descriptor size */
0x04, /* bDescriptorType: */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints */
0x08, /* bInterfaceClass: MSC Class */
0x06, /* bInterfaceSubClass : SCSI transparent*/
0x50, /* nInterfaceProtocol */
0x05, /* iInterface: */
/******************** Mass Storage Endpoints ********************/
0x07, /* Endpoint descriptor length = 7 */
0x05, /* Endpoint descriptor type */
MSC_EPIN_ADDR, /* Endpoint address (IN, address 1) */
0x02, /* Bulk endpoint type */
LOBYTE(MSC_MAX_FS_PACKET),
HIBYTE(MSC_MAX_FS_PACKET),
0x00, /* Polling interval in milliseconds */
0x07, /* Endpoint descriptor length = 7 */
0x05, /* Endpoint descriptor type */
MSC_EPOUT_ADDR, /* Endpoint address (OUT, address 1) */
0x02, /* Bulk endpoint type */
LOBYTE(MSC_MAX_FS_PACKET),
HIBYTE(MSC_MAX_FS_PACKET),
0x00 /* Polling interval in milliseconds */
};
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_MSC_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
MSC_MAX_FS_PACKET,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
uint8_t MSCInEpAdd = MSC_EPIN_ADDR;
uint8_t MSCOutEpAdd = MSC_EPOUT_ADDR;
/**
* @}
*/
/** @defgroup MSC_CORE_Private_Functions
* @{
*/
/**
* @brief USBD_MSC_Init
* Initialize the mass storage configuration
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status
*/
uint8_t USBD_MSC_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_MSC_BOT_HandleTypeDef *hmsc;
hmsc = (USBD_MSC_BOT_HandleTypeDef *)USBD_malloc(sizeof(USBD_MSC_BOT_HandleTypeDef));
if (hmsc == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
pdev->pClassDataCmsit[pdev->classId] = (void *)hmsc;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, MSCOutEpAdd, USBD_EP_TYPE_BULK, MSC_MAX_HS_PACKET);
pdev->ep_out[MSCOutEpAdd & 0xFU].is_used = 1U;
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, MSCInEpAdd, USBD_EP_TYPE_BULK, MSC_MAX_HS_PACKET);
pdev->ep_in[MSCInEpAdd & 0xFU].is_used = 1U;
}
else
{
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, MSCOutEpAdd, USBD_EP_TYPE_BULK, MSC_MAX_FS_PACKET);
pdev->ep_out[MSCOutEpAdd & 0xFU].is_used = 1U;
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, MSCInEpAdd, USBD_EP_TYPE_BULK, MSC_MAX_FS_PACKET);
pdev->ep_in[MSCInEpAdd & 0xFU].is_used = 1U;
}
/* Init the BOT layer */
MSC_BOT_Init(pdev);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MSC_DeInit
* DeInitialize the mass storage configuration
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status
*/
uint8_t USBD_MSC_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close MSC EPs */
(void)USBD_LL_CloseEP(pdev, MSCOutEpAdd);
pdev->ep_out[MSCOutEpAdd & 0xFU].is_used = 0U;
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, MSCInEpAdd);
pdev->ep_in[MSCInEpAdd & 0xFU].is_used = 0U;
/* Free MSC Class Resources */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
/* De-Init the BOT layer */
MSC_BOT_DeInit(pdev);
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MSC_Setup
* Handle the MSC specific requests
* @param pdev: device instance
* @param req: USB request
* @retval status
*/
uint8_t USBD_MSC_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint16_t status_info = 0U;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
/* Class request */
case USB_REQ_TYPE_CLASS:
switch (req->bRequest)
{
case BOT_GET_MAX_LUN:
if ((req->wValue == 0U) && (req->wLength == 1U) &&
((req->bmRequest & 0x80U) == 0x80U))
{
hmsc->max_lun = (uint32_t)((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->GetMaxLun();
(void)USBD_CtlSendData(pdev, (uint8_t *)&hmsc->max_lun, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case BOT_RESET :
if ((req->wValue == 0U) && (req->wLength == 0U) &&
((req->bmRequest & 0x80U) != 0x80U))
{
MSC_BOT_Reset(pdev);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
/* Interface & Endpoint request */
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&hmsc->interface, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
hmsc->interface = (uint8_t)(req->wValue);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (req->wValue == USB_FEATURE_EP_HALT)
{
/* Flush the FIFO */
(void)USBD_LL_FlushEP(pdev, (uint8_t)req->wIndex);
/* Handle BOT error */
MSC_BOT_CplClrFeature(pdev, (uint8_t)req->wIndex);
}
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_MSC_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
uint8_t USBD_MSC_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
MSC_BOT_DataIn(pdev, epnum);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MSC_DataOut
* handle data OUT Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
uint8_t USBD_MSC_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
MSC_BOT_DataOut(pdev, epnum);
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_MSC_GetHSCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_MSC_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MSC_MAX_HS_PACKET;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MSC_MAX_HS_PACKET;
}
*length = (uint16_t)sizeof(USBD_MSC_CfgDesc);
return USBD_MSC_CfgDesc;
}
/**
* @brief USBD_MSC_GetFSCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_MSC_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MSC_MAX_FS_PACKET;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MSC_MAX_FS_PACKET;
}
*length = (uint16_t)sizeof(USBD_MSC_CfgDesc);
return USBD_MSC_CfgDesc;
}
/**
* @brief USBD_MSC_GetOtherSpeedCfgDesc
* return other speed configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_MSC_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPIN_ADDR);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MSC_CfgDesc, MSC_EPOUT_ADDR);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MSC_MAX_FS_PACKET;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MSC_MAX_FS_PACKET;
}
*length = (uint16_t)sizeof(USBD_MSC_CfgDesc);
return USBD_MSC_CfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_MSC_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_MSC_DeviceQualifierDesc);
return USBD_MSC_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_MSC_RegisterStorage
* @param fops: storage callback
* @retval status
*/
uint8_t USBD_MSC_RegisterStorage(USBD_HandleTypeDef *pdev, USBD_StorageTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Src\usbd_msc_bot.c | /**
******************************************************************************
* @file usbd_msc_bot.c
* @author MCD Application Team
* @brief This file provides all the BOT protocol core functions.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_sd.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc_bot.h"
#include "usbd_msc.h"
#include "usbd_msc_scsi.h"
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup MSC_BOT
* @brief BOT protocol module
* @{
*/
/** @defgroup MSC_BOT_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup MSC_BOT_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup MSC_BOT_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup MSC_BOT_Private_Variables
* @{
*/
extern uint8_t MSCInEpAdd;
extern uint8_t MSCOutEpAdd;
/**
* @}
*/
/** @defgroup MSC_BOT_Private_FunctionPrototypes
* @{
*/
static void MSC_BOT_SendData(USBD_HandleTypeDef *pdev, uint8_t *pbuf, uint32_t len);
static void MSC_BOT_CBW_Decode(USBD_HandleTypeDef *pdev);
static void MSC_BOT_Abort(USBD_HandleTypeDef *pdev);
/**
* @}
*/
/** @defgroup MSC_BOT_Private_Functions
* @{
*/
/**
* @brief MSC_BOT_Init
* Initialize the BOT Process
* @param pdev: device instance
* @retval None
*/
void MSC_BOT_Init(USBD_HandleTypeDef *pdev)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
hmsc->bot_state = USBD_BOT_IDLE;
hmsc->bot_status = USBD_BOT_STATUS_NORMAL;
hmsc->scsi_sense_tail = 0U;
hmsc->scsi_sense_head = 0U;
hmsc->scsi_medium_state = SCSI_MEDIUM_UNLOCKED;
((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->Init(0U);
(void)USBD_LL_FlushEP(pdev, MSCOutEpAdd);
(void)USBD_LL_FlushEP(pdev, MSCInEpAdd);
/* Prepare EP to Receive First BOT Cmd */
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, (uint8_t *)&hmsc->cbw,
USBD_BOT_CBW_LENGTH);
}
/**
* @brief MSC_BOT_Reset
* Reset the BOT Machine
* @param pdev: device instance
* @retval None
*/
void MSC_BOT_Reset(USBD_HandleTypeDef *pdev)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
hmsc->bot_state = USBD_BOT_IDLE;
hmsc->bot_status = USBD_BOT_STATUS_RECOVERY;
(void)USBD_LL_ClearStallEP(pdev, MSCInEpAdd);
(void)USBD_LL_ClearStallEP(pdev, MSCOutEpAdd);
/* Prepare EP to Receive First BOT Cmd */
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, (uint8_t *)&hmsc->cbw,
USBD_BOT_CBW_LENGTH);
}
/**
* @brief MSC_BOT_DeInit
* DeInitialize the BOT Machine
* @param pdev: device instance
* @retval None
*/
void MSC_BOT_DeInit(USBD_HandleTypeDef *pdev)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc != NULL)
{
hmsc->bot_state = USBD_BOT_IDLE;
}
}
/**
* @brief MSC_BOT_DataIn
* Handle BOT IN data stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval None
*/
void MSC_BOT_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return;
}
switch (hmsc->bot_state)
{
case USBD_BOT_DATA_IN:
if (SCSI_ProcessCmd(pdev, hmsc->cbw.bLUN, &hmsc->cbw.CB[0]) < 0)
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_FAILED);
}
break;
case USBD_BOT_SEND_DATA:
case USBD_BOT_LAST_DATA_IN:
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_PASSED);
break;
default:
break;
}
}
/**
* @brief MSC_BOT_DataOut
* Process MSC OUT data
* @param pdev: device instance
* @param epnum: endpoint index
* @retval None
*/
void MSC_BOT_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return;
}
switch (hmsc->bot_state)
{
case USBD_BOT_IDLE:
MSC_BOT_CBW_Decode(pdev);
break;
case USBD_BOT_DATA_OUT:
if (SCSI_ProcessCmd(pdev, hmsc->cbw.bLUN, &hmsc->cbw.CB[0]) < 0)
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_FAILED);
}
break;
default:
break;
}
}
/**
* @brief MSC_BOT_CBW_Decode
* Decode the CBW command and set the BOT state machine accordingly
* @param pdev: device instance
* @retval None
*/
static void MSC_BOT_CBW_Decode(USBD_HandleTypeDef *pdev)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
hmsc->csw.dTag = hmsc->cbw.dTag;
hmsc->csw.dDataResidue = hmsc->cbw.dDataLength;
if ((USBD_LL_GetRxDataSize(pdev, MSCOutEpAdd) != USBD_BOT_CBW_LENGTH) ||
(hmsc->cbw.dSignature != USBD_BOT_CBW_SIGNATURE) ||
(hmsc->cbw.bLUN > 1U) || (hmsc->cbw.bCBLength < 1U) ||
(hmsc->cbw.bCBLength > 16U))
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
hmsc->bot_status = USBD_BOT_STATUS_ERROR;
MSC_BOT_Abort(pdev);
}
else
{
if (SCSI_ProcessCmd(pdev, hmsc->cbw.bLUN, &hmsc->cbw.CB[0]) < 0)
{
if (hmsc->bot_state == USBD_BOT_NO_DATA)
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_FAILED);
}
else
{
MSC_BOT_Abort(pdev);
}
}
/* Burst xfer handled internally */
else if ((hmsc->bot_state != USBD_BOT_DATA_IN) &&
(hmsc->bot_state != USBD_BOT_DATA_OUT) &&
(hmsc->bot_state != USBD_BOT_LAST_DATA_IN))
{
if (hmsc->bot_data_length > 0U)
{
MSC_BOT_SendData(pdev, hmsc->bot_data, hmsc->bot_data_length);
}
else if (hmsc->bot_data_length == 0U)
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_PASSED);
}
else
{
MSC_BOT_Abort(pdev);
}
}
else
{
return;
}
}
}
/**
* @brief MSC_BOT_SendData
* Send the requested data
* @param pdev: device instance
* @param buf: pointer to data buffer
* @param len: Data Length
* @retval None
*/
static void MSC_BOT_SendData(USBD_HandleTypeDef *pdev, uint8_t *pbuf, uint32_t len)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t length;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
length = MIN(hmsc->cbw.dDataLength, len);
hmsc->csw.dDataResidue -= len;
hmsc->csw.bStatus = USBD_CSW_CMD_PASSED;
hmsc->bot_state = USBD_BOT_SEND_DATA;
(void)USBD_LL_Transmit(pdev, MSCInEpAdd, pbuf, length);
}
/**
* @brief MSC_BOT_SendCSW
* Send the Command Status Wrapper
* @param pdev: device instance
* @param status : CSW status
* @retval None
*/
void MSC_BOT_SendCSW(USBD_HandleTypeDef *pdev, uint8_t CSW_Status)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
hmsc->csw.dSignature = USBD_BOT_CSW_SIGNATURE;
hmsc->csw.bStatus = CSW_Status;
hmsc->bot_state = USBD_BOT_IDLE;
(void)USBD_LL_Transmit(pdev, MSCInEpAdd, (uint8_t *)&hmsc->csw,
USBD_BOT_CSW_LENGTH);
/* Prepare EP to Receive next Cmd */
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, (uint8_t *)&hmsc->cbw,
USBD_BOT_CBW_LENGTH);
}
/**
* @brief MSC_BOT_Abort
* Abort the current transfer
* @param pdev: device instance
* @retval status
*/
static void MSC_BOT_Abort(USBD_HandleTypeDef *pdev)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
if ((hmsc->cbw.bmFlags == 0U) &&
(hmsc->cbw.dDataLength != 0U) &&
(hmsc->bot_status == USBD_BOT_STATUS_NORMAL))
{
(void)USBD_LL_StallEP(pdev, MSCOutEpAdd);
}
(void)USBD_LL_StallEP(pdev, MSCInEpAdd);
if (hmsc->bot_status == USBD_BOT_STATUS_ERROR)
{
(void)USBD_LL_StallEP(pdev, MSCInEpAdd);
(void)USBD_LL_StallEP(pdev, MSCOutEpAdd);
}
}
/**
* @brief MSC_BOT_CplClrFeature
* Complete the clear feature request
* @param pdev: device instance
* @param epnum: endpoint index
* @retval None
*/
void MSC_BOT_CplClrFeature(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc == NULL)
{
return;
}
if (hmsc->bot_status == USBD_BOT_STATUS_ERROR) /* Bad CBW Signature */
{
(void)USBD_LL_StallEP(pdev, MSCInEpAdd);
(void)USBD_LL_StallEP(pdev, MSCOutEpAdd);
}
else if (((epnum & 0x80U) == 0x80U) && (hmsc->bot_status != USBD_BOT_STATUS_RECOVERY))
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_FAILED);
}
else
{
return;
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Src\usbd_msc_data.c | /**
******************************************************************************
* @file usbd_msc_data.c
* @author MCD Application Team
* @brief This file provides all the vital inquiry pages and sense data.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_sd.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc_data.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup MSC_DATA
* @brief Mass storage info/data module
* @{
*/
/** @defgroup MSC_DATA_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup MSC_DATA_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup MSC_DATA_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup MSC_DATA_Private_Variables
* @{
*/
/* USB Mass storage Page 0 Inquiry Data */
uint8_t MSC_Page00_Inquiry_Data[LENGTH_INQUIRY_PAGE00] =
{
0x00,
0x00,
0x00,
(LENGTH_INQUIRY_PAGE00 - 4U),
0x00,
0x80
};
/* USB Mass storage VPD Page 0x80 Inquiry Data for Unit Serial Number */
uint8_t MSC_Page80_Inquiry_Data[LENGTH_INQUIRY_PAGE80] =
{
0x00,
0x80,
0x00,
LENGTH_INQUIRY_PAGE80,
0x20, /* Put Product Serial number */
0x20,
0x20,
0x20
};
/* USB Mass storage sense 6 Data */
uint8_t MSC_Mode_Sense6_data[MODE_SENSE6_LEN] =
{
0x03, /* MODE DATA LENGTH. The number of bytes that follow. */
0x00, /* MEDIUM TYPE. 00h for SBC devices. */
0x00, /* DEVICE-SPECIFIC PARAMETER. For SBC devices:
* bit 7: WP. Set to 1 if the media is write-protected.
* bits 6..5: reserved
* bit 4: DPOFUA. Set to 1 if the device supports the DPO and FUA bits
* bits 3..0: reserved */
0x00 /* BLOCK DESCRIPTOR LENGTH */
};
/* USB Mass storage sense 10 Data */
uint8_t MSC_Mode_Sense10_data[MODE_SENSE10_LEN] =
{
0x00, /* MODE DATA LENGTH MSB. */
0x06, /* MODE DATA LENGTH LSB. The number of bytes that follow. */
0x00, /* MEDIUM TYPE. 00h for SBC devices. */
0x00, /* DEVICE-SPECIFIC PARAMETER. For SBC devices:
* bit 7: WP. Set to 1 if the media is write-protected.
* bits 6..5: reserved
* bit 4: DPOFUA. Set to 1 if the device supports the DPO and FUA bits
* bits 3..0: reserved */
0x00, /* LONGLBA Set to zero */
0x00, /* Reserved */
0x00, /* BLOCK DESCRIPTOR LENGTH MSB. */
0x00 /* BLOCK DESCRIPTOR LENGTH LSB. */
};
/**
* @}
*/
/** @defgroup MSC_DATA_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup MSC_DATA_Private_Functions
* @{
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Src\usbd_msc_scsi.c | /**
******************************************************************************
* @file usbd_msc_scsi.c
* @author MCD Application Team
* @brief This file provides all the USBD SCSI layer functions.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_sd.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc_bot.h"
#include "usbd_msc_scsi.h"
#include "usbd_msc.h"
#include "usbd_msc_data.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup MSC_SCSI
* @brief Mass storage SCSI layer module
* @{
*/
/** @defgroup MSC_SCSI_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup MSC_SCSI_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup MSC_SCSI_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup MSC_SCSI_Private_Variables
* @{
*/
extern uint8_t MSCInEpAdd;
extern uint8_t MSCOutEpAdd;
/**
* @}
*/
/** @defgroup MSC_SCSI_Private_FunctionPrototypes
* @{
*/
static int8_t SCSI_TestUnitReady(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Inquiry(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_ReadFormatCapacity(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_ReadCapacity10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_ReadCapacity16(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_RequestSense(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_StartStopUnit(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_AllowPreventRemovable(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_ModeSense6(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_ModeSense10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Write10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Write12(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Read10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Read12(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_Verify10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params);
static int8_t SCSI_CheckAddressRange(USBD_HandleTypeDef *pdev, uint8_t lun,
uint32_t blk_offset, uint32_t blk_nbr);
static int8_t SCSI_ProcessRead(USBD_HandleTypeDef *pdev, uint8_t lun);
static int8_t SCSI_ProcessWrite(USBD_HandleTypeDef *pdev, uint8_t lun);
static int8_t SCSI_UpdateBotData(USBD_MSC_BOT_HandleTypeDef *hmsc,
uint8_t *pBuff, uint16_t length);
/**
* @}
*/
/** @defgroup MSC_SCSI_Private_Functions
* @{
*/
/**
* @brief SCSI_ProcessCmd
* Process SCSI commands
* @param pdev: device instance
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
int8_t SCSI_ProcessCmd(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *cmd)
{
int8_t ret;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
switch (cmd[0])
{
case SCSI_TEST_UNIT_READY:
ret = SCSI_TestUnitReady(pdev, lun, cmd);
break;
case SCSI_REQUEST_SENSE:
ret = SCSI_RequestSense(pdev, lun, cmd);
break;
case SCSI_INQUIRY:
ret = SCSI_Inquiry(pdev, lun, cmd);
break;
case SCSI_START_STOP_UNIT:
ret = SCSI_StartStopUnit(pdev, lun, cmd);
break;
case SCSI_ALLOW_MEDIUM_REMOVAL:
ret = SCSI_AllowPreventRemovable(pdev, lun, cmd);
break;
case SCSI_MODE_SENSE6:
ret = SCSI_ModeSense6(pdev, lun, cmd);
break;
case SCSI_MODE_SENSE10:
ret = SCSI_ModeSense10(pdev, lun, cmd);
break;
case SCSI_READ_FORMAT_CAPACITIES:
ret = SCSI_ReadFormatCapacity(pdev, lun, cmd);
break;
case SCSI_READ_CAPACITY10:
ret = SCSI_ReadCapacity10(pdev, lun, cmd);
break;
case SCSI_READ_CAPACITY16:
ret = SCSI_ReadCapacity16(pdev, lun, cmd);
break;
case SCSI_READ10:
ret = SCSI_Read10(pdev, lun, cmd);
break;
case SCSI_READ12:
ret = SCSI_Read12(pdev, lun, cmd);
break;
case SCSI_WRITE10:
ret = SCSI_Write10(pdev, lun, cmd);
break;
case SCSI_WRITE12:
ret = SCSI_Write12(pdev, lun, cmd);
break;
case SCSI_VERIFY10:
ret = SCSI_Verify10(pdev, lun, cmd);
break;
default:
SCSI_SenseCode(pdev, lun, ILLEGAL_REQUEST, INVALID_CDB);
hmsc->bot_status = USBD_BOT_STATUS_ERROR;
ret = -1;
break;
}
return ret;
}
/**
* @brief SCSI_TestUnitReady
* Process SCSI Test Unit Ready Command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_TestUnitReady(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(params);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
/* case 9 : Hi > D0 */
if (hmsc->cbw.dDataLength != 0U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
if (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
hmsc->bot_state = USBD_BOT_NO_DATA;
return -1;
}
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsReady(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
hmsc->bot_state = USBD_BOT_NO_DATA;
return -1;
}
hmsc->bot_data_length = 0U;
return 0;
}
/**
* @brief SCSI_Inquiry
* Process Inquiry command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Inquiry(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
uint8_t *pPage;
uint16_t len;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if (hmsc->cbw.dDataLength == 0U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
if ((params[1] & 0x01U) != 0U) /* Evpd is set */
{
if (params[2] == 0U) /* Request for Supported Vital Product Data Pages*/
{
(void)SCSI_UpdateBotData(hmsc, MSC_Page00_Inquiry_Data, LENGTH_INQUIRY_PAGE00);
}
else if (params[2] == 0x80U) /* Request for VPD page 0x80 Unit Serial Number */
{
(void)SCSI_UpdateBotData(hmsc, MSC_Page80_Inquiry_Data, LENGTH_INQUIRY_PAGE80);
}
else /* Request Not supported */
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST,
INVALID_FIELED_IN_COMMAND);
return -1;
}
}
else
{
pPage = (uint8_t *) & ((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId]) \
->pInquiry[lun * STANDARD_INQUIRY_DATA_LEN];
len = (uint16_t)pPage[4] + 5U;
if (params[4] <= len)
{
len = params[4];
}
(void)SCSI_UpdateBotData(hmsc, pPage, len);
}
return 0;
}
/**
* @brief SCSI_ReadCapacity10
* Process Read Capacity 10 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_ReadCapacity10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(params);
int8_t ret;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
ret = ((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->GetCapacity(lun, &hmsc->scsi_blk_nbr,
&hmsc->scsi_blk_size);
if ((ret != 0) || (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED))
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
hmsc->bot_data[0] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 24);
hmsc->bot_data[1] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 16);
hmsc->bot_data[2] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 8);
hmsc->bot_data[3] = (uint8_t)(hmsc->scsi_blk_nbr - 1U);
hmsc->bot_data[4] = (uint8_t)(hmsc->scsi_blk_size >> 24);
hmsc->bot_data[5] = (uint8_t)(hmsc->scsi_blk_size >> 16);
hmsc->bot_data[6] = (uint8_t)(hmsc->scsi_blk_size >> 8);
hmsc->bot_data[7] = (uint8_t)(hmsc->scsi_blk_size);
hmsc->bot_data_length = 8U;
return 0;
}
/**
* @brief SCSI_ReadCapacity16
* Process Read Capacity 16 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_ReadCapacity16(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(params);
uint32_t idx;
int8_t ret;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
ret = ((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->GetCapacity(lun, &hmsc->scsi_blk_nbr,
&hmsc->scsi_blk_size);
if ((ret != 0) || (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED))
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
hmsc->bot_data_length = ((uint32_t)params[10] << 24) |
((uint32_t)params[11] << 16) |
((uint32_t)params[12] << 8) |
(uint32_t)params[13];
for (idx = 0U; idx < hmsc->bot_data_length; idx++)
{
hmsc->bot_data[idx] = 0U;
}
hmsc->bot_data[4] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 24);
hmsc->bot_data[5] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 16);
hmsc->bot_data[6] = (uint8_t)((hmsc->scsi_blk_nbr - 1U) >> 8);
hmsc->bot_data[7] = (uint8_t)(hmsc->scsi_blk_nbr - 1U);
hmsc->bot_data[8] = (uint8_t)(hmsc->scsi_blk_size >> 24);
hmsc->bot_data[9] = (uint8_t)(hmsc->scsi_blk_size >> 16);
hmsc->bot_data[10] = (uint8_t)(hmsc->scsi_blk_size >> 8);
hmsc->bot_data[11] = (uint8_t)(hmsc->scsi_blk_size);
hmsc->bot_data_length = ((uint32_t)params[10] << 24) |
((uint32_t)params[11] << 16) |
((uint32_t)params[12] << 8) |
(uint32_t)params[13];
return 0;
}
/**
* @brief SCSI_ReadFormatCapacity
* Process Read Format Capacity command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_ReadFormatCapacity(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(params);
uint16_t blk_size;
uint32_t blk_nbr;
uint16_t i;
int8_t ret;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
ret = ((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->GetCapacity(lun, &blk_nbr, &blk_size);
if ((ret != 0) || (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED))
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
for (i = 0U; i < 12U ; i++)
{
hmsc->bot_data[i] = 0U;
}
hmsc->bot_data[3] = 0x08U;
hmsc->bot_data[4] = (uint8_t)((blk_nbr - 1U) >> 24);
hmsc->bot_data[5] = (uint8_t)((blk_nbr - 1U) >> 16);
hmsc->bot_data[6] = (uint8_t)((blk_nbr - 1U) >> 8);
hmsc->bot_data[7] = (uint8_t)(blk_nbr - 1U);
hmsc->bot_data[8] = 0x02U;
hmsc->bot_data[9] = (uint8_t)(blk_size >> 16);
hmsc->bot_data[10] = (uint8_t)(blk_size >> 8);
hmsc->bot_data[11] = (uint8_t)(blk_size);
hmsc->bot_data_length = 12U;
return 0;
}
/**
* @brief SCSI_ModeSense6
* Process Mode Sense6 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_ModeSense6(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(lun);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len = MODE_SENSE6_LEN;
if (hmsc == NULL)
{
return -1;
}
/* Check If media is write-protected */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsWriteProtected(lun) != 0)
{
MSC_Mode_Sense6_data[2] |= 0x80U;
}
if (params[4] <= len)
{
len = params[4];
}
(void)SCSI_UpdateBotData(hmsc, MSC_Mode_Sense6_data, len);
return 0;
}
/**
* @brief SCSI_ModeSense10
* Process Mode Sense10 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_ModeSense10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(lun);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len = MODE_SENSE10_LEN;
if (hmsc == NULL)
{
return -1;
}
/* Check If media is write-protected */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsWriteProtected(lun) != 0)
{
MSC_Mode_Sense10_data[3] |= 0x80U;
}
if (params[8] <= len)
{
len = params[8];
}
(void)SCSI_UpdateBotData(hmsc, MSC_Mode_Sense10_data, len);
return 0;
}
/**
* @brief SCSI_RequestSense
* Process Request Sense command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_RequestSense(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(lun);
uint8_t i;
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if (hmsc->cbw.dDataLength == 0U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
for (i = 0U; i < REQUEST_SENSE_DATA_LEN; i++)
{
hmsc->bot_data[i] = 0U;
}
hmsc->bot_data[0] = 0x70U;
hmsc->bot_data[7] = REQUEST_SENSE_DATA_LEN - 6U;
if ((hmsc->scsi_sense_head != hmsc->scsi_sense_tail))
{
hmsc->bot_data[2] = (uint8_t)hmsc->scsi_sense[hmsc->scsi_sense_head].Skey;
hmsc->bot_data[12] = (uint8_t)hmsc->scsi_sense[hmsc->scsi_sense_head].w.b.ASC;
hmsc->bot_data[13] = (uint8_t)hmsc->scsi_sense[hmsc->scsi_sense_head].w.b.ASCQ;
hmsc->scsi_sense_head++;
if (hmsc->scsi_sense_head == SENSE_LIST_DEEPTH)
{
hmsc->scsi_sense_head = 0U;
}
}
hmsc->bot_data_length = REQUEST_SENSE_DATA_LEN;
if (params[4] <= REQUEST_SENSE_DATA_LEN)
{
hmsc->bot_data_length = params[4];
}
return 0;
}
/**
* @brief SCSI_SenseCode
* Load the last error code in the error list
* @param lun: Logical unit number
* @param sKey: Sense Key
* @param ASC: Additional Sense Code
* @retval none
*/
void SCSI_SenseCode(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t sKey, uint8_t ASC)
{
UNUSED(lun);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return;
}
hmsc->scsi_sense[hmsc->scsi_sense_tail].Skey = sKey;
hmsc->scsi_sense[hmsc->scsi_sense_tail].w.b.ASC = ASC;
hmsc->scsi_sense[hmsc->scsi_sense_tail].w.b.ASCQ = 0U;
hmsc->scsi_sense_tail++;
if (hmsc->scsi_sense_tail == SENSE_LIST_DEEPTH)
{
hmsc->scsi_sense_tail = 0U;
}
}
/**
* @brief SCSI_StartStopUnit
* Process Start Stop Unit command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_StartStopUnit(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(lun);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if ((hmsc->scsi_medium_state == SCSI_MEDIUM_LOCKED) && ((params[4] & 0x3U) == 2U))
{
SCSI_SenseCode(pdev, lun, ILLEGAL_REQUEST, INVALID_FIELED_IN_COMMAND);
return -1;
}
if ((params[4] & 0x3U) == 0x1U) /* START=1 */
{
hmsc->scsi_medium_state = SCSI_MEDIUM_UNLOCKED;
}
else if ((params[4] & 0x3U) == 0x2U) /* START=0 and LOEJ Load Eject=1 */
{
hmsc->scsi_medium_state = SCSI_MEDIUM_EJECTED;
}
else if ((params[4] & 0x3U) == 0x3U) /* START=1 and LOEJ Load Eject=1 */
{
hmsc->scsi_medium_state = SCSI_MEDIUM_UNLOCKED;
}
else
{
/* .. */
}
hmsc->bot_data_length = 0U;
return 0;
}
/**
* @brief SCSI_AllowPreventRemovable
* Process Allow Prevent Removable medium command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_AllowPreventRemovable(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
UNUSED(lun);
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if (params[4] == 0U)
{
hmsc->scsi_medium_state = SCSI_MEDIUM_UNLOCKED;
}
else
{
hmsc->scsi_medium_state = SCSI_MEDIUM_LOCKED;
}
hmsc->bot_data_length = 0U;
return 0;
}
/**
* @brief SCSI_Read10
* Process Read10 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Read10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if (hmsc->bot_state == USBD_BOT_IDLE) /* Idle */
{
/* case 10 : Ho <> Di */
if ((hmsc->cbw.bmFlags & 0x80U) != 0x80U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
if (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsReady(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
hmsc->scsi_blk_addr = ((uint32_t)params[2] << 24) |
((uint32_t)params[3] << 16) |
((uint32_t)params[4] << 8) |
(uint32_t)params[5];
hmsc->scsi_blk_len = ((uint32_t)params[7] << 8) | (uint32_t)params[8];
if (SCSI_CheckAddressRange(pdev, lun, hmsc->scsi_blk_addr,
hmsc->scsi_blk_len) < 0)
{
return -1; /* error */
}
/* cases 4,5 : Hi <> Dn */
if (hmsc->cbw.dDataLength != (hmsc->scsi_blk_len * hmsc->scsi_blk_size))
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
hmsc->bot_state = USBD_BOT_DATA_IN;
}
hmsc->bot_data_length = MSC_MEDIA_PACKET;
return SCSI_ProcessRead(pdev, lun);
}
/**
* @brief SCSI_Read12
* Process Read12 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Read12(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if (hmsc->bot_state == USBD_BOT_IDLE) /* Idle */
{
/* case 10 : Ho <> Di */
if ((hmsc->cbw.bmFlags & 0x80U) != 0x80U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
if (hmsc->scsi_medium_state == SCSI_MEDIUM_EJECTED)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsReady(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
hmsc->scsi_blk_addr = ((uint32_t)params[2] << 24) |
((uint32_t)params[3] << 16) |
((uint32_t)params[4] << 8) |
(uint32_t)params[5];
hmsc->scsi_blk_len = ((uint32_t)params[6] << 24) |
((uint32_t)params[7] << 16) |
((uint32_t)params[8] << 8) |
(uint32_t)params[9];
if (SCSI_CheckAddressRange(pdev, lun, hmsc->scsi_blk_addr,
hmsc->scsi_blk_len) < 0)
{
return -1; /* error */
}
/* cases 4,5 : Hi <> Dn */
if (hmsc->cbw.dDataLength != (hmsc->scsi_blk_len * hmsc->scsi_blk_size))
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
hmsc->bot_state = USBD_BOT_DATA_IN;
}
hmsc->bot_data_length = MSC_MEDIA_PACKET;
return SCSI_ProcessRead(pdev, lun);
}
/**
* @brief SCSI_Write10
* Process Write10 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Write10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t len;
if (hmsc == NULL)
{
return -1;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc->bot_state == USBD_BOT_IDLE) /* Idle */
{
if (hmsc->cbw.dDataLength == 0U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
/* case 8 : Hi <> Do */
if ((hmsc->cbw.bmFlags & 0x80U) == 0x80U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
/* Check whether Media is ready */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsReady(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
return -1;
}
/* Check If media is write-protected */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsWriteProtected(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, WRITE_PROTECTED);
return -1;
}
hmsc->scsi_blk_addr = ((uint32_t)params[2] << 24) |
((uint32_t)params[3] << 16) |
((uint32_t)params[4] << 8) |
(uint32_t)params[5];
hmsc->scsi_blk_len = ((uint32_t)params[7] << 8) |
(uint32_t)params[8];
/* check if LBA address is in the right range */
if (SCSI_CheckAddressRange(pdev, lun, hmsc->scsi_blk_addr,
hmsc->scsi_blk_len) < 0)
{
return -1; /* error */
}
len = hmsc->scsi_blk_len * hmsc->scsi_blk_size;
/* cases 3,11,13 : Hn,Ho <> D0 */
if (hmsc->cbw.dDataLength != len)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
len = MIN(len, MSC_MEDIA_PACKET);
/* Prepare EP to receive first data packet */
hmsc->bot_state = USBD_BOT_DATA_OUT;
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, hmsc->bot_data, len);
}
else /* Write Process ongoing */
{
return SCSI_ProcessWrite(pdev, lun);
}
return 0;
}
/**
* @brief SCSI_Write12
* Process Write12 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Write12(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t len;
if (hmsc == NULL)
{
return -1;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmsc->bot_state == USBD_BOT_IDLE) /* Idle */
{
if (hmsc->cbw.dDataLength == 0U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
/* case 8 : Hi <> Do */
if ((hmsc->cbw.bmFlags & 0x80U) == 0x80U)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
/* Check whether Media is ready */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsReady(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, MEDIUM_NOT_PRESENT);
hmsc->bot_state = USBD_BOT_NO_DATA;
return -1;
}
/* Check If media is write-protected */
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->IsWriteProtected(lun) != 0)
{
SCSI_SenseCode(pdev, lun, NOT_READY, WRITE_PROTECTED);
hmsc->bot_state = USBD_BOT_NO_DATA;
return -1;
}
hmsc->scsi_blk_addr = ((uint32_t)params[2] << 24) |
((uint32_t)params[3] << 16) |
((uint32_t)params[4] << 8) |
(uint32_t)params[5];
hmsc->scsi_blk_len = ((uint32_t)params[6] << 24) |
((uint32_t)params[7] << 16) |
((uint32_t)params[8] << 8) |
(uint32_t)params[9];
/* check if LBA address is in the right range */
if (SCSI_CheckAddressRange(pdev, lun, hmsc->scsi_blk_addr,
hmsc->scsi_blk_len) < 0)
{
return -1; /* error */
}
len = hmsc->scsi_blk_len * hmsc->scsi_blk_size;
/* cases 3,11,13 : Hn,Ho <> D0 */
if (hmsc->cbw.dDataLength != len)
{
SCSI_SenseCode(pdev, hmsc->cbw.bLUN, ILLEGAL_REQUEST, INVALID_CDB);
return -1;
}
len = MIN(len, MSC_MEDIA_PACKET);
/* Prepare EP to receive first data packet */
hmsc->bot_state = USBD_BOT_DATA_OUT;
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, hmsc->bot_data, len);
}
else /* Write Process ongoing */
{
return SCSI_ProcessWrite(pdev, lun);
}
return 0;
}
/**
* @brief SCSI_Verify10
* Process Verify10 command
* @param lun: Logical unit number
* @param params: Command parameters
* @retval status
*/
static int8_t SCSI_Verify10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if ((params[1] & 0x02U) == 0x02U)
{
SCSI_SenseCode(pdev, lun, ILLEGAL_REQUEST, INVALID_FIELED_IN_COMMAND);
return -1; /* Error, Verify Mode Not supported*/
}
if (SCSI_CheckAddressRange(pdev, lun, hmsc->scsi_blk_addr, hmsc->scsi_blk_len) < 0)
{
return -1; /* error */
}
hmsc->bot_data_length = 0U;
return 0;
}
/**
* @brief SCSI_CheckAddressRange
* Check address range
* @param lun: Logical unit number
* @param blk_offset: first block address
* @param blk_nbr: number of block to be processed
* @retval status
*/
static int8_t SCSI_CheckAddressRange(USBD_HandleTypeDef *pdev, uint8_t lun,
uint32_t blk_offset, uint32_t blk_nbr)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmsc == NULL)
{
return -1;
}
if ((blk_offset + blk_nbr) > hmsc->scsi_blk_nbr)
{
SCSI_SenseCode(pdev, lun, ILLEGAL_REQUEST, ADDRESS_OUT_OF_RANGE);
return -1;
}
return 0;
}
/**
* @brief SCSI_ProcessRead
* Handle Read Process
* @param lun: Logical unit number
* @retval status
*/
static int8_t SCSI_ProcessRead(USBD_HandleTypeDef *pdev, uint8_t lun)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t len;
if (hmsc == NULL)
{
return -1;
}
len = hmsc->scsi_blk_len * hmsc->scsi_blk_size;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
len = MIN(len, MSC_MEDIA_PACKET);
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->Read(lun, hmsc->bot_data,
hmsc->scsi_blk_addr,
(len / hmsc->scsi_blk_size)) < 0)
{
SCSI_SenseCode(pdev, lun, HARDWARE_ERROR, UNRECOVERED_READ_ERROR);
return -1;
}
(void)USBD_LL_Transmit(pdev, MSCInEpAdd, hmsc->bot_data, len);
hmsc->scsi_blk_addr += (len / hmsc->scsi_blk_size);
hmsc->scsi_blk_len -= (len / hmsc->scsi_blk_size);
/* case 6 : Hi = Di */
hmsc->csw.dDataResidue -= len;
if (hmsc->scsi_blk_len == 0U)
{
hmsc->bot_state = USBD_BOT_LAST_DATA_IN;
}
return 0;
}
/**
* @brief SCSI_ProcessWrite
* Handle Write Process
* @param lun: Logical unit number
* @retval status
*/
static int8_t SCSI_ProcessWrite(USBD_HandleTypeDef *pdev, uint8_t lun)
{
USBD_MSC_BOT_HandleTypeDef *hmsc = (USBD_MSC_BOT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t len;
if (hmsc == NULL)
{
return -1;
}
len = hmsc->scsi_blk_len * hmsc->scsi_blk_size;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MSCOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
len = MIN(len, MSC_MEDIA_PACKET);
if (((USBD_StorageTypeDef *)pdev->pUserData[pdev->classId])->Write(lun, hmsc->bot_data,
hmsc->scsi_blk_addr,
(len / hmsc->scsi_blk_size)) < 0)
{
SCSI_SenseCode(pdev, lun, HARDWARE_ERROR, WRITE_FAULT);
return -1;
}
hmsc->scsi_blk_addr += (len / hmsc->scsi_blk_size);
hmsc->scsi_blk_len -= (len / hmsc->scsi_blk_size);
/* case 12 : Ho = Do */
hmsc->csw.dDataResidue -= len;
if (hmsc->scsi_blk_len == 0U)
{
MSC_BOT_SendCSW(pdev, USBD_CSW_CMD_PASSED);
}
else
{
len = MIN((hmsc->scsi_blk_len * hmsc->scsi_blk_size), MSC_MEDIA_PACKET);
/* Prepare EP to Receive next packet */
(void)USBD_LL_PrepareReceive(pdev, MSCOutEpAdd, hmsc->bot_data, len);
}
return 0;
}
/**
* @brief SCSI_UpdateBotData
* fill the requested Data to transmit buffer
* @param hmsc handler
* @param pBuff: Data buffer
* @param length: Data length
* @retval status
*/
static int8_t SCSI_UpdateBotData(USBD_MSC_BOT_HandleTypeDef *hmsc,
uint8_t *pBuff, uint16_t length)
{
uint16_t len = length;
if (hmsc == NULL)
{
return -1;
}
hmsc->bot_data_length = len;
while (len != 0U)
{
len--;
hmsc->bot_data[len] = pBuff[len];
}
return 0;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC | D://workCode//uploadProject\stm32_mw_usb_device\Class\MSC\Src\usbd_msc_storage_template.c | /**
******************************************************************************
* @file usbd_msc_storage_template.c
* @author MCD Application Team
* @brief Memory management layer
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_sd.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_msc_storage_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Extern function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
#define STORAGE_LUN_NBR 1U
#define STORAGE_BLK_NBR 0x10000U
#define STORAGE_BLK_SIZ 0x200U
int8_t STORAGE_Init(uint8_t lun);
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num,
uint16_t *block_size);
int8_t STORAGE_IsReady(uint8_t lun);
int8_t STORAGE_IsWriteProtected(uint8_t lun);
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr,
uint16_t blk_len);
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr,
uint16_t blk_len);
int8_t STORAGE_GetMaxLun(void);
/* USB Mass storage Standard Inquiry Data */
int8_t STORAGE_Inquirydata[] = /* 36 */
{
/* LUN 0 */
0x00,
0x80,
0x02,
0x02,
(STANDARD_INQUIRY_DATA_LEN - 5),
0x00,
0x00,
0x00,
'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer : 8 bytes */
'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product : 16 Bytes */
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
'0', '.', '0', '1', /* Version : 4 Bytes */
};
USBD_StorageTypeDef USBD_MSC_Template_fops =
{
STORAGE_Init,
STORAGE_GetCapacity,
STORAGE_IsReady,
STORAGE_IsWriteProtected,
STORAGE_Read,
STORAGE_Write,
STORAGE_GetMaxLun,
STORAGE_Inquirydata,
};
/**
* @brief Initializes the storage unit (medium)
* @param lun: Logical unit number
* @retval Status (0 : OK / -1 : Error)
*/
int8_t STORAGE_Init(uint8_t lun)
{
UNUSED(lun);
return (0);
}
/**
* @brief Returns the medium capacity.
* @param lun: Logical unit number
* @param block_num: Number of total block number
* @param block_size: Block size
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size)
{
UNUSED(lun);
*block_num = STORAGE_BLK_NBR;
*block_size = STORAGE_BLK_SIZ;
return (0);
}
/**
* @brief Checks whether the medium is ready.
* @param lun: Logical unit number
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_IsReady(uint8_t lun)
{
UNUSED(lun);
return (0);
}
/**
* @brief Checks whether the medium is write protected.
* @param lun: Logical unit number
* @retval Status (0: write enabled / -1: otherwise)
*/
int8_t STORAGE_IsWriteProtected(uint8_t lun)
{
UNUSED(lun);
return 0;
}
/**
* @brief Reads data from the medium.
* @param lun: Logical unit number
* @param buf: data buffer
* @param blk_addr: Logical block address
* @param blk_len: Blocks number
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf,
uint32_t blk_addr, uint16_t blk_len)
{
UNUSED(lun);
UNUSED(buf);
UNUSED(blk_addr);
UNUSED(blk_len);
return 0;
}
/**
* @brief Writes data into the medium.
* @param lun: Logical unit number
* @param buf: data buffer
* @param blk_addr: Logical block address
* @param blk_len: Blocks number
* @retval Status (0 : OK / -1 : Error)
*/
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf,
uint32_t blk_addr, uint16_t blk_len)
{
UNUSED(lun);
UNUSED(buf);
UNUSED(blk_addr);
UNUSED(blk_len);
return (0);
}
/**
* @brief Returns the Max Supported LUNs.
* @param None
* @retval Lun(s) number
*/
int8_t STORAGE_GetMaxLun(void)
{
return (STORAGE_LUN_NBR - 1);
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Inc\usbd_mtp.h | /**
******************************************************************************
* @file usbd_mtp.h
* @author MCD Application Team
* @brief header file for the usbd_mtp.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_MTP_H
#define __USB_MTP_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_MTP
* @brief This file is the header file for usbd_mtp.c
* @{
*/
/** @defgroup USBD_MTP_Exported_Defines
* @{
*/
#ifndef MTP_IN_EP
#define MTP_IN_EP 0x81U /* EP1 for data IN */
#endif /* MTP_IN_EP */
#ifndef MTP_OUT_EP
#define MTP_OUT_EP 0x01U /* EP1 for data OUT */
#endif /* MTP_OUT_EP */
#ifndef MTP_CMD_EP
#define MTP_CMD_EP 0x82U /* EP2 for MTP commands */
#endif /* MTP_CMD_EP */
#ifndef MTP_CMD_ITF_NBR
#define MTP_CMD_ITF_NBR 0x00U /* Command Interface Number 0 */
#endif /* MTP_CMD_ITF_NBR */
#ifndef MTP_COM_ITF_NBR
#define MTP_COM_ITF_NBR 0x01U /* Communication Interface Number 0 */
#endif /* MTP_CMD_ITF_NBR */
#ifndef MTP_HS_BINTERVAL
#define MTP_HS_BINTERVAL 0x10U
#endif /* MTP_HS_BINTERVAL */
#ifndef MTP_FS_BINTERVAL
#define MTP_FS_BINTERVAL 0x10U
#endif /* MTP_FS_BINTERVAL */
#define MTP_DATA_MAX_HS_PACKET_SIZE 512U
#define MTP_DATA_MAX_FS_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#define MTP_CMD_PACKET_SIZE 8U /* Control Endpoint Packet size */
#define MTP_MEDIA_PACKET 512U
#define MTP_CONT_HEADER_SIZE 12U
#define MTP_CONFIG_DESC_SIZ 39U
#define MTP_INTERFACE_DESC_SIZE 0x09U
#define USB_MTP_INTRERFACE_CLASS 0x06U
#define USB_MTP_INTRERFACE_SUB_CLASS 0x01U
#define USB_MTP_INTRERFACE_PROTOCOL 0x01U
#define MTP_ENDPOINT_DESC_SIZE 0x07U
/*---------------------------------------------------------------------*/
/* MTP definitions */
/*---------------------------------------------------------------------*/
/* MTP class requests */
#define MTP_REQ_CANCEL 0x64U
#define MTP_REQ_GET_EXT_EVENT_DATA 0x65U
#define MTP_REQ_RESET 0x66U
#define MTP_REQ_GET_DEVICE_STATUS 0x67U
/* Max info items size */
#define MTP_SUPPORTED_OPERATIONS_NBR 100U
#define MTP_SUPPORTED_EVENTS_NBR 100U
#define MTP_SUPPORTED_PROPRIETIES_NBR 100U
#define MTP_CAPTURE_FORMATS_NBR 100U
#define MTP_IMAGE_FORMATS_NBR 100U
#define MTP_MAX_STR_SIZE 255U
/* MTP response code */
#define MTP_RESPONSE_OK 0x2001U
#define MTP_RESPONSE_GENERAL_ERROR 0x2002U
#define MTP_RESPONSE_PARAMETER_NOT_SUPPORTED 0x2006U
#define MTP_RESPONSE_INCOMPLETE_TRANSFER 0x2007U
#define MTP_RESPONSE_INVALID_STORAGE_ID 0x2008U
#define MTP_RESPONSE_INVALID_OBJECT_HANDLE 0x2009U
#define MTP_RESPONSE_DEVICEPROP_NOT_SUPPORTED 0x200AU
#define MTP_RESPONSE_STORE_FULL 0x200CU
#define MTP_RESPONSE_ACCESS_DENIED 0x200FU
#define MTP_RESPONSE_STORE_NOT_AVAILABLE 0x2013U
#define MTP_RESPONSE_SPECIFICATION_BY_FORMAT_NOT_SUPPORTED 0x2014U
#define MTP_RESPONSE_NO_VALID_OBJECT_INFO 0x2015U
#define MTP_RESPONSE_DEVICE_BUSY 0x2019U
#define MTP_RESPONSE_INVALID_PARENT_OBJECT 0x201AU
#define MTP_RESPONSE_INVALID_PARAMETER 0x201DU
#define MTP_RESPONSE_SESSION_ALREADY_OPEN 0x201EU
#define MTP_RESPONSE_TRANSACTION_CANCELLED 0x201FU
#define MTP_RESPONSE_INVALID_OBJECT_PROP_CODE 0xA801U
#define MTP_RESPONSE_SPECIFICATION_BY_GROUP_UNSUPPORTED 0xA807U
#define MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED 0xA80AU
/*
* MTP Class specification Revision 1.1
* Appendix A. Object Formats
*/
/* MTP Object format codes */
#define MTP_OBJ_FORMAT_UNDEFINED 0x3000U
#define MTP_OBJ_FORMAT_ASSOCIATION 0x3001U
#define MTP_OBJ_FORMAT_SCRIPT 0x3002U
#define MTP_OBJ_FORMAT_EXECUTABLE 0x3003U
#define MTP_OBJ_FORMAT_TEXT 0x3004U
#define MTP_OBJ_FORMAT_HTML 0x3005U
#define MTP_OBJ_FORMAT_DPOF 0x3006U
#define MTP_OBJ_FORMAT_AIFF 0x3007U
#define MTP_OBJ_FORMAT_WAV 0x3008U
#define MTP_OBJ_FORMAT_MP3 0x3009U
#define MTP_OBJ_FORMAT_AVI 0x300AU
#define MTP_OBJ_FORMAT_MPEG 0x300BU
#define MTP_OBJ_FORMAT_ASF 0x300CU
#define MTP_OBJ_FORMAT_DEFINED 0x3800U
#define MTP_OBJ_FORMAT_EXIF_JPEG 0x3801U
#define MTP_OBJ_FORMAT_TIFF_EP 0x3802U
#define MTP_OBJ_FORMAT_FLASHPIX 0x3803U
#define MTP_OBJ_FORMAT_BMP 0x3804U
#define MTP_OBJ_FORMAT_CIFF 0x3805U
#define MTP_OBJ_FORMAT_UNDEFINED_RESERVED0 0x3806U
#define MTP_OBJ_FORMAT_GIF 0x3807U
#define MTP_OBJ_FORMAT_JFIF 0x3808U
#define MTP_OBJ_FORMAT_CD 0x3809U
#define MTP_OBJ_FORMAT_PICT 0x380AU
#define MTP_OBJ_FORMAT_PNG 0x380BU
#define MTP_OBJ_FORMAT_UNDEFINED_RESERVED1 0x380CU
#define MTP_OBJ_FORMAT_TIFF 0x380DU
#define MTP_OBJ_FORMAT_TIFF_IT 0x380EU
#define MTP_OBJ_FORMAT_JP2 0x380FU
#define MTP_OBJ_FORMAT_JPX 0x3810U
#define MTP_OBJ_FORMAT_UNDEFINED_FIRMWARE 0xB802U
#define MTP_OBJ_FORMAT_WINDOWS_IMAGE_FORMAT 0xB881U
#define MTP_OBJ_FORMAT_UNDEFINED_AUDIO 0xB900U
#define MTP_OBJ_FORMAT_WMA 0xB901U
#define MTP_OBJ_FORMAT_OGG 0xB902U
#define MTP_OBJ_FORMAT_AAC 0xB903U
#define MTP_OBJ_FORMAT_AUDIBLE 0xB904U
#define MTP_OBJ_FORMAT_FLAC 0xB906U
#define MTP_OBJ_FORMAT_UNDEFINED_VIDEO 0xB980U
#define MTP_OBJ_FORMAT_WMV 0xB981U
#define MTP_OBJ_FORMAT_MP4_CONTAINER 0xB982U
#define MTP_OBJ_FORMAT_MP2 0xB983U
#define MTP_OBJ_FORMAT_3GP_CONTAINER 0xB984U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
/* MTP Session state */
typedef enum
{
MTP_SESSION_NOT_OPENED = 0x00,
MTP_SESSION_OPENED = 0x01,
} MTP_SessionStateTypeDef;
/* MTP response phases */
typedef enum
{
MTP_PHASE_IDLE = 0x00,
MTP_RESPONSE_PHASE = 0x01,
MTP_READ_DATA = 0x02,
MTP_RECEIVE_DATA = 0x03,
} MTP_ResponsePhaseTypeDef;
typedef struct
{
uint32_t temp_length;
uint32_t prv_len;
uint32_t totallen;
uint32_t rx_length;
uint32_t readbytes; /* File write/read counts */
} MTP_DataLengthTypeDef;
typedef enum
{
RECEIVE_IDLE_STATE = 0x00U,
RECEIVE_COMMAND_DATA = 0x01U,
RECEIVE_FIRST_DATA = 0x02U,
RECEIVE_REST_OF_DATA = 0x03U,
SEND_RESPONSE = 0x04U,
} MTP_RECEIVE_DATA_STATUS;
typedef struct
{
uint32_t length;
uint16_t type;
uint16_t code;
uint32_t trans_id;
uint32_t Param1;
uint32_t Param2;
uint32_t Param3;
uint32_t Param4;
uint32_t Param5;
} MTP_OperationsTypeDef;
typedef struct
{
uint32_t length;
uint16_t type;
uint16_t code;
uint32_t trans_id;
uint8_t data[MTP_MEDIA_PACKET];
} MTP_GenericContainerTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint32_t Storage_id;
uint16_t ObjectFormat;
uint16_t ProtectionStatus;
uint32_t ObjectCompressedSize;
uint16_t ThumbFormat;
uint32_t ThumbCompressedSize;
uint32_t ThumbPixWidth;
uint32_t ThumbPixHeight;
uint32_t ImagePixWidth;
uint32_t ImagePixHeight;
uint32_t ImageBitDepth;
uint32_t ParentObject;
uint16_t AssociationType;
uint32_t AssociationDesc;
uint32_t SequenceNumber;
uint8_t Filename_len;
uint16_t Filename[255];
uint32_t CaptureDate;
uint32_t ModificationDate;
uint8_t Keywords;
} MTP_ObjectInfoTypeDef;
typedef struct
{
uint32_t alt_setting;
uint32_t dev_status;
uint32_t ResponseLength;
uint32_t ResponseCode;
__IO uint16_t MaxPcktLen;
uint32_t rx_buff[MTP_MEDIA_PACKET / 4U]; /* Force 32-bit alignment */
MTP_ResponsePhaseTypeDef MTP_ResponsePhase;
MTP_SessionStateTypeDef MTP_SessionState;
MTP_RECEIVE_DATA_STATUS RECEIVE_DATA_STATUS;
MTP_OperationsTypeDef OperationsContainer;
MTP_GenericContainerTypeDef GenericContainer;
} USBD_MTP_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_MTP;
#define USBD_MTP_CLASS &USBD_MTP
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
typedef struct _USBD_MTP_ItfTypeDef
{
uint8_t (*Init)(void);
uint8_t (*DeInit)(void);
uint32_t (*ReadData)(uint32_t Param1, uint8_t *buff, MTP_DataLengthTypeDef *data_length);
uint16_t (*Create_NewObject)(MTP_ObjectInfoTypeDef ObjectInfo, uint32_t objhandle);
uint32_t (*GetIdx)(uint32_t Param3, uint32_t *obj_handle);
uint32_t (*GetParentObject)(uint32_t Param);
uint16_t (*GetObjectFormat)(uint32_t Param);
uint8_t (*GetObjectName_len)(uint32_t Param);
void (*GetObjectName)(uint32_t Param, uint8_t obj_len, uint16_t *buf);
uint32_t (*GetObjectSize)(uint32_t Param);
uint64_t (*GetMaxCapability)(void);
uint64_t (*GetFreeSpaceInBytes)(void);
uint32_t (*GetNewIndex)(uint16_t objformat);
void (*WriteData)(uint16_t len, uint8_t buff[]);
uint32_t (*GetContainerLength)(uint32_t Param1);
uint16_t (*DeleteObject)(uint32_t Param1);
void (*Cancel)(uint32_t Phase);
uint32_t *ScratchBuff;
uint32_t ScratchBuffSze;
} USBD_MTP_ItfTypeDef;
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_MTP_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_MTP_ItfTypeDef *fops);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_MTP_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Inc\usbd_mtp_if_template.h | /**
******************************************************************************
* @file usbd_mtp_if_template.h
* @author MCD Application Team
* @brief Header file for the usbd_mtp_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_MTP_IF_TEMPLATE_H
#define __USBD_MTP_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_mtp.h"
/* Exported Define -----------------------------------------------------------*/
#define USBD_MTP_DEVICE_PROP_SUPPORTED 1U
#define USBD_MTP_CAPTURE_FORMAT_SUPPORTED 1U
#define USBD_MTP_VEND_EXT_DESC_SUPPORTED 1U
#define USBD_MTP_EVENTS_SUPPORTED 1U
#if USBD_MTP_EVENTS_SUPPORTED == 1
#define SUPP_EVENTS_LEN (uint8_t)((uint8_t)sizeof(SuppEvents) / 2U)
#else
#define SUPP_EVENTS_LEN 0U
#endif /* USBD_MTP_EVENTS_SUPPORTED */
#if USBD_MTP_VEND_EXT_DESC_SUPPORTED == 1
#define VEND_EXT_DESC_LEN (sizeof(VendExtDesc) / 2U)
#else
#define VEND_EXT_DESC_LEN 0U
#endif /* USBD_MTP_VEND_EXT_DESC_SUPPORTED */
#if USBD_MTP_CAPTURE_FORMAT_SUPPORTED == 1
#define SUPP_CAPT_FORMAT_LEN (uint8_t)((uint8_t)sizeof(SuppCaptFormat) / 2U)
#else
#define SUPP_CAPT_FORMAT_LEN 0U
#endif /* USBD_MTP_CAPTURE_FORMAT_SUPPORTED */
#if USBD_MTP_DEVICE_PROP_SUPPORTED == 1
#define SUPP_DEVICE_PROP_LEN (uint8_t)((uint8_t)sizeof(DevicePropSupp) / 2U)
#else
#define SUPP_DEVICE_PROP_LEN 0U
#endif /* USBD_MTP_DEVICE_PROP_SUPPORTED */
#define MTP_IF_SCRATCH_BUFF_SZE 1024U
/* Exported types ------------------------------------------------------------*/
extern USBD_MTP_ItfTypeDef USBD_MTP_fops;
/* Exported macros -----------------------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
static const uint16_t Manuf[] = {'S', 'T', 'M', 0}; /* last 2 bytes must be 0*/
static const uint16_t Model[] = {'S', 'T', 'M', '3', '2', 0}; /* last 2 bytes must be 0*/
static const uint16_t VendExtDesc[] = {'m', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't', '.',
'c', 'o', 'm', ':', ' ', '1', '.', '0', ';', ' ', 0
}; /* last 2 bytes must be 0*/
/*SerialNbr shall be 32 character hexadecimal string for legacy compatibility reasons */
static const uint16_t SerialNbr[] = {'0', '0', '0', '0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '0',
'1', '0', '0', '0', '0', '1', '0', '0', '0', '0', '1', '0', '0', '0',
'0', '1', '0', '0', 0
}; /* last 2 bytes must be 0*/
static const uint16_t DeviceVers[] = {'V', '1', '.', '0', '0', 0}; /* last 2 bytes must be 0*/
static const uint16_t DefaultFileName[] = {'N', 'e', 'w', ' ', 'F', 'o', 'l', 'd', 'e', 'r', 0};
static const uint16_t DevicePropDefVal[] = {'S', 'T', 'M', '3', '2', 0}; /* last 2 bytes must be 0*/
static const uint16_t DevicePropCurDefVal[] = {'S', 'T', 'M', '3', '2', ' ', 'V', '1', '.', '0', 0};
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MTP_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Inc\usbd_mtp_opt.h | /**
******************************************************************************
* @file usbd_mtp_opt.h
* @author MCD Application Team
* @brief header file for the usbd_mtp_opt.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_MTP_OPT_H__
#define __USBD_MTP_OPT_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#ifndef __USBD_MTP_IF_H
#include "usbd_mtp_if_template.h"
#endif /* __USBD_MTP_IF_H */
#include "usbd_mtp.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_MTP_OPT
* @brief This file is the header file for usbd_mtp_opt.c
* @{
*/
/** @defgroup USBD_MTP_OPT_Exported_Defines
* @{
*/
/*
* MTP Class specification Revision 1.1
* Appendix B. Object Properties
*/
/* MTP OBJECT PROPERTIES supported*/
#define MTP_OB_PROP_STORAGE_ID 0xDC01U
#define MTP_OB_PROP_OBJECT_FORMAT 0xDC02U
#define MTP_OB_PROP_PROTECTION_STATUS 0xDC03U
#define MTP_OB_PROP_OBJECT_SIZE 0xDC04U
#define MTP_OB_PROP_ASSOC_TYPE 0xDC05U
#define MTP_OB_PROP_ASSOC_DESC 0xDC06U
#define MTP_OB_PROP_OBJ_FILE_NAME 0xDC07U
#define MTP_OB_PROP_DATE_CREATED 0xDC08U
#define MTP_OB_PROP_DATE_MODIFIED 0xDC09U
#define MTP_OB_PROP_KEYWORDS 0xDC0AU
#define MTP_OB_PROP_PARENT_OBJECT 0xDC0BU
#define MTP_OB_PROP_ALLOWED_FOLD_CONTENTS 0xDC0CU
#define MTP_OB_PROP_HIDDEN 0xDC0DU
#define MTP_OB_PROP_SYSTEM_OBJECT 0xDC0EU
#define MTP_OB_PROP_PERS_UNIQ_OBJ_IDEN 0xDC41U
#define MTP_OB_PROP_SYNCID 0xDC42U
#define MTP_OB_PROP_PROPERTY_BAG 0xDC43U
#define MTP_OB_PROP_NAME 0xDC44U
#define MTP_OB_PROP_CREATED_BY 0xDC45U
#define MTP_OB_PROP_ARTIST 0xDC46U
#define MTP_OB_PROP_DATE_AUTHORED 0xDC47U
#define MTP_OB_PROP_DESCRIPTION 0xDC48U
#define MTP_OB_PROP_URL_REFERENCE 0xDC49U
#define MTP_OB_PROP_LANGUAGELOCALE 0xDC4AU
#define MTP_OB_PROP_COPYRIGHT_INFORMATION 0xDC4BU
#define MTP_OB_PROP_SOURCE 0xDC4CU
#define MTP_OB_PROP_ORIGIN_LOCATION 0xDC4DU
#define MTP_OB_PROP_DATE_ADDED 0xDC4EU
#define MTP_OB_PROP_NON_CONSUMABLE 0xDC4FU
#define MTP_OB_PROP_CORRUPTUNPLAYABLE 0xDC50U
#define MTP_OB_PROP_PRODUCERSERIALNUMBER 0xDC51U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_FORMAT 0xDC81U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_SIZE 0xDC82U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_HEIGHT 0xDC83U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_WIDTH 0xDC84U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_DURATION 0xDC85U
#define MTP_OB_PROP_REPRESENTATIVE_SAMPLE_DATA 0xDC86U
#define MTP_OB_PROP_WIDTH 0xDC87U
#define MTP_OB_PROP_HEIGHT 0xDC88U
#define MTP_OB_PROP_DURATION 0xDC89U
#define MTP_OB_PROP_RATING 0xDC8AU
#define MTP_OB_PROP_TRACK 0xDC8BU
#define MTP_OB_PROP_GENRE 0xDC8CU
#define MTP_OB_PROP_CREDITS 0xDC8DU
#define MTP_OB_PROP_LYRICS 0xDC8EU
#define MTP_OB_PROP_SUBSCRIPTION_CONTENT_ID 0xDC8FU
#define MTP_OB_PROP_PRODUCED_BY 0xDC90U
#define MTP_OB_PROP_USE_COUNT 0xDC91U
#define MTP_OB_PROP_SKIP_COUNT 0xDC92U
#define MTP_OB_PROP_LAST_ACCESSED 0xDC93U
#define MTP_OB_PROP_PARENTAL_RATING 0xDC94U
#define MTP_OB_PROP_META_GENRE 0xDC95U
#define MTP_OB_PROP_COMPOSER 0xDC96U
#define MTP_OB_PROP_EFFECTIVE_RATING 0xDC97U
#define MTP_OB_PROP_SUBTITLE 0xDC98U
#define MTP_OB_PROP_ORIGINAL_RELEASE_DATE 0xDC99U
#define MTP_OB_PROP_ALBUM_NAME 0xDC9AU
#define MTP_OB_PROP_ALBUM_ARTIST 0xDC9BU
#define MTP_OB_PROP_MOOD 0xDC9CU
#define MTP_OB_PROP_DRM_STATUS 0xDC9DU
#define MTP_OB_PROP_SUB_DESCRIPTION 0xDC9EU
#define MTP_OB_PROP_IS_CROPPED 0xDCD1U
#define MTP_OB_PROP_IS_COLOUR_CORRECTED 0xDCD2U
#define MTP_OB_PROP_IMAGE_BIT_DEPTH 0xDCD3U
#define MTP_OB_PROP_FNUMBER 0xDCD4U
#define MTP_OB_PROP_EXPOSURE_TIME 0xDCD5U
#define MTP_OB_PROP_EXPOSURE_INDEX 0xDCD6U
#define MTP_OB_PROP_TOTAL_BITRATE 0xDE91U
#define MTP_OB_PROP_BITRATE_TYPE 0xDE92U
#define MTP_OB_PROP_SAMPLE_RATE 0xDE93U
#define MTP_OB_PROP_NUMBER_OF_CHANNELS 0xDE94U
#define MTP_OB_PROP_AUDIO_BITDEPTH 0xDE95U
#define MTP_OB_PROP_SCAN_TYPE 0xDE97U
#define MTP_OB_PROP_AUDIO_WAVE_CODEC 0xDE99U
#define MTP_OB_PROP_AUDIO_BITRATE 0xDE9AU
#define MTP_OB_PROP_VIDEO_FOURCC_CODEC 0xDE9BU
#define MTP_OB_PROP_VIDEO_BITRATE 0xDE9CU
#define MTP_OB_PROP_FRAMES_PER_THOUSAND_SECONDS 0xDE9DU
#define MTP_OB_PROP_KEYFRAME_DISTANCE 0xDE9EU
#define MTP_OB_PROP_BUFFER_SIZE 0xDE9FU
#define MTP_OB_PROP_ENCODING_QUALITY 0xDEA0U
#define MTP_OB_PROP_ENCODING_PROFILE 0xDEA1U
#define MTP_OB_PROP_DISPLAY_NAME 0xDCE0U
#define MTP_OB_PROP_BODY_TEXT 0xDCE1U
#define MTP_OB_PROP_SUBJECT 0xDCE2U
#define MTP_OB_PROP_PRIORITY 0xDCE3U
#define MTP_OB_PROP_GIVEN_NAME 0xDD00U
#define MTP_OB_PROP_MIDDLE_NAMES 0xDD01U
#define MTP_OB_PROP_FAMILY_NAME 0xDD02U
#define MTP_OB_PROP_PREFIX 0xDD03U
#define MTP_OB_PROP_SUFFIX 0xDD04U
#define MTP_OB_PROP_PHONETIC_GIVEN_NAME 0xDD05U
#define MTP_OB_PROP_PHONETIC_FAMILY_NAME 0xDD06U
#define MTP_OB_PROP_EMAIL_PRIMARY 0xDD07U
#define MTP_OB_PROP_EMAIL_PERSONAL_1 0xDD08U
#define MTP_OB_PROP_EMAIL_PERSONAL_2 0xDD09U
#define MTP_OB_PROP_EMAIL_BUSINESS_1 0xDD0AU
#define MTP_OB_PROP_EMAIL_BUSINESS_2 0xDD0BU
#define MTP_OB_PROP_EMAIL_OTHERS 0xDD0CU
#define MTP_OB_PROP_PHONE_NUMBER_PRIMARY 0xDD0DU
#define MTP_OB_PROP_PHONE_NUMBER_PERSONAL 0xDD0EU
#define MTP_OB_PROP_PHONE_NUMBER_PERSONAL_2 0xDD0FU
#define MTP_OB_PROP_PHONE_NUMBER_BUSINESS 0xDD10U
#define MTP_OB_PROP_PHONE_NUMBER_BUSINESS_2 0xDD11U
#define MTP_OB_PROP_PHONE_NUMBER_MOBILE 0xDD12U
#define MTP_OB_PROP_PHONE_NUMBER_MOBILE_2 0xDD13U
#define MTP_OB_PROP_FAX_NUMBER_PRIMARY 0xDD14U
#define MTP_OB_PROP_FAX_NUMBER_PERSONAL 0xDD15U
#define MTP_OB_PROP_FAX_NUMBER_BUSINESS 0xDD16U
#define MTP_OB_PROP_PAGER_NUMBER 0xDD17U
#define MTP_OB_PROP_PHONE_NUMBER_OTHERS 0xDD18U
#define MTP_OB_PROP_PRIMARY_WEB_ADDRESS 0xDD19U
#define MTP_OB_PROP_PERSONAL_WEB_ADDRESS 0xDD1AU
#define MTP_OB_PROP_BUSINESS_WEB_ADDRESS 0xDD1BU
#define MTP_OB_PROP_INSTANT_MESSENGER_ADDRESS 0xDD1CU
#define MTP_OB_PROP_INSTANT_MESSENGER_ADDRESS_2 0xDD1DU
#define MTP_OB_PROP_INSTANT_MESSENGER_ADDRESS_3 0xDD1EU
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_FULL 0xDD1FU
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_LINE_1 0xDD20U
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_LINE_2 0xDD21U
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_CITY 0xDD22U
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_REGION 0xDD23U
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_POSTAL_CODE 0xDD24U
#define MTP_OB_PROP_POSTAL_ADDRESS_PERSONAL_COUNTRY 0xDD25U
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_FULL 0xDD26U
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_LINE_1 0xDD27U
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_LINE_2 0xDD28U
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_CITY 0xDD29U
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_REGION 0xDD2AU
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_POSTAL_CODE 0xDD2BU
#define MTP_OB_PROP_POSTAL_ADDRESS_BUSINESS_COUNTRY 0xDD2CU
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_FULL 0xDD2DU
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_LINE_1 0xDD2EU
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_LINE_2 0xDD2FU
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_CITY 0xDD30U
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_REGION 0xDD31U
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_POSTAL_CODE 0xDD32U
#define MTP_OB_PROP_POSTAL_ADDRESS_OTHER_COUNTRY 0xDD33U
#define MTP_OB_PROP_ORGANIZATION_NAME 0xDD34U
#define MTP_OB_PROP_PHONETIC_ORGANIZATION_NAME 0xDD35U
#define MTP_OB_PROP_ROLE 0xDD36U
#define MTP_OB_PROP_BIRTHDATE 0xDD37U
#define MTP_OB_PROP_MESSAGE_TO 0xDD40U
#define MTP_OB_PROP_MESSAGE_CC 0xDD41U
#define MTP_OB_PROP_MESSAGE_BCC 0xDD42U
#define MTP_OB_PROP_MESSAGE_READ 0xDD43U
#define MTP_OB_PROP_MESSAGE_RECEIVED_TIME 0xDD44U
#define MTP_OB_PROP_MESSAGE_SENDER 0xDD45U
#define MTP_OB_PROP_ACT_BEGIN_TIME 0xDD50U
#define MTP_OB_PROP_ACT_END_TIME 0xDD51U
#define MTP_OB_PROP_ACT_LOCATION 0xDD52U
#define MTP_OB_PROP_ACT_REQUIRED_ATTENDEES 0xDD54U
#define MTP_OB_PROP_ACT_OPTIONAL_ATTENDEES 0xDD55U
#define MTP_OB_PROP_ACT_RESOURCES 0xDD56U
#define MTP_OB_PROP_ACT_ACCEPTED 0xDD57U
#define MTP_OB_PROP_OWNER 0xDD5DU
#define MTP_OB_PROP_EDITOR 0xDD5EU
#define MTP_OB_PROP_WEBMASTER 0xDD5FU
#define MTP_OB_PROP_URL_SOURCE 0xDD60U
#define MTP_OB_PROP_URL_DESTINATION 0xDD61U
#define MTP_OB_PROP_TIME_BOOKMARK 0xDD62U
#define MTP_OB_PROP_OBJECT_BOOKMARK 0xDD63U
#define MTP_OB_PROP_BYTE_BOOKMARK 0xDD64U
#define MTP_OB_PROP_LAST_BUILD_DATE 0xDD70U
#define MTP_OB_PROP_TIME_TO_LIVE 0xDD71U
#define MTP_OB_PROP_MEDIA_GUID 0xDD72U
/* MTP event codes*/
#define MTP_EVENT_UNDEFINED 0x4000U
#define MTP_EVENT_CANCELTRANSACTION 0x4001U
#define MTP_EVENT_OBJECTADDED 0x4002U
#define MTP_EVENT_OBJECTREMOVED 0x4003U
#define MTP_EVENT_STOREADDED 0x4004U
#define MTP_EVENT_STOREREMOVED 0x4005U
#define MTP_EVENT_DEVICEPROPCHANGED 0x4006U
#define MTP_EVENT_OBJECTINFOCHANGED 0x4007U
#define MTP_EVENT_DEVICEINFOCHANGED 0x4008U
#define MTP_EVENT_REQUESTOBJECTTRANSFER 0x4009U
#define MTP_EVENT_STOREFULL 0x400AU
#define MTP_EVENT_DEVICERESET 0x400BU
#define MTP_EVENT_STORAGEINFOCHANGED 0x400CU
#define MTP_EVENT_CAPTURECOMPLETE 0x400DU
#define MTP_EVENT_UNREPORTEDSTATUS 0x400EU
#define MTP_EVENT_OBJECTPROPCHANGED 0xC801U
#define MTP_EVENT_OBJECTPROPDESCCHANGED 0xC802U
#define MTP_EVENT_OBJECTREFERENCESCHANGED 0xC803U
/*
* MTP Class specification Revision 1.1
* Appendix D. Operations
*/
/* Operations code */
#define MTP_OP_GET_DEVICE_INFO 0x1001U
#define MTP_OP_OPEN_SESSION 0x1002U
#define MTP_OP_CLOSE_SESSION 0x1003U
#define MTP_OP_GET_STORAGE_IDS 0x1004U
#define MTP_OP_GET_STORAGE_INFO 0x1005U
#define MTP_OP_GET_NUM_OBJECTS 0x1006U
#define MTP_OP_GET_OBJECT_HANDLES 0x1007U
#define MTP_OP_GET_OBJECT_INFO 0x1008U
#define MTP_OP_GET_OBJECT 0x1009U
#define MTP_OP_GET_THUMB 0x100AU
#define MTP_OP_DELETE_OBJECT 0x100BU
#define MTP_OP_SEND_OBJECT_INFO 0x100CU
#define MTP_OP_SEND_OBJECT 0x100DU
#define MTP_OP_FORMAT_STORE 0x100FU
#define MTP_OP_RESET_DEVICE 0x1010U
#define MTP_OP_GET_DEVICE_PROP_DESC 0x1014U
#define MTP_OP_GET_DEVICE_PROP_VALUE 0x1015U
#define MTP_OP_SET_DEVICE_PROP_VALUE 0x1016U
#define MTP_OP_RESET_DEVICE_PROP_VALUE 0x1017U
#define MTP_OP_TERMINATE_OPEN_CAPTURE 0x1018U
#define MTP_OP_MOVE_OBJECT 0x1019U
#define MTP_OP_COPY_OBJECT 0x101AU
#define MTP_OP_GET_PARTIAL_OBJECT 0x101BU
#define MTP_OP_INITIATE_OPEN_CAPTURE 0x101CU
#define MTP_OP_GET_OBJECT_PROPS_SUPPORTED 0x9801U
#define MTP_OP_GET_OBJECT_PROP_DESC 0x9802U
#define MTP_OP_GET_OBJECT_PROP_VALUE 0x9803U
#define MTP_OP_SET_OBJECT_PROP_VALUE 0x9804U
#define MTP_OP_GET_OBJECT_PROPLIST 0x9805U
#define MTP_OP_GET_OBJECT_PROP_REFERENCES 0x9810U
#define MTP_OP_GETSERVICEIDS 0x9301U
#define MTP_OP_GETSERVICEINFO 0x9302U
#define MTP_OP_GETSERVICECAPABILITIES 0x9303U
#define MTP_OP_GETSERVICEPROPDESC 0x9304U
/*
* MTP Class specification Revision 1.1
* Appendix C. Device Properties
*/
/* MTP device properties code*/
#define MTP_DEV_PROP_UNDEFINED 0x5000U
#define MTP_DEV_PROP_BATTERY_LEVEL 0x5001U
#define MTP_DEV_PROP_FUNCTIONAL_MODE 0x5002U
#define MTP_DEV_PROP_IMAGE_SIZE 0x5003U
#define MTP_DEV_PROP_COMPRESSION_SETTING 0x5004U
#define MTP_DEV_PROP_WHITE_BALANCE 0x5005U
#define MTP_DEV_PROP_RGB_GAIN 0x5006U
#define MTP_DEV_PROP_F_NUMBER 0x5007U
#define MTP_DEV_PROP_FOCAL_LENGTH 0x5008U
#define MTP_DEV_PROP_FOCUS_DISTANCE 0x5009U
#define MTP_DEV_PROP_FOCUS_MODE 0x500AU
#define MTP_DEV_PROP_EXPOSURE_METERING_MODE 0x500BU
#define MTP_DEV_PROP_FLASH_MODE 0x500CU
#define MTP_DEV_PROP_EXPOSURE_TIME 0x500DU
#define MTP_DEV_PROP_EXPOSURE_PROGRAM_MODE 0x500EU
#define MTP_DEV_PROP_EXPOSURE_INDEX 0x500FU
#define MTP_DEV_PROP_EXPOSURE_BIAS_COMPENSATION 0x5010U
#define MTP_DEV_PROP_DATETIME 0x5011U
#define MTP_DEV_PROP_CAPTURE_DELAY 0x5012U
#define MTP_DEV_PROP_STILL_CAPTURE_MODE 0x5013U
#define MTP_DEV_PROP_CONTRAST 0x5014U
#define MTP_DEV_PROP_SHARPNESS 0x5015U
#define MTP_DEV_PROP_DIGITAL_ZOOM 0x5016U
#define MTP_DEV_PROP_EFFECT_MODE 0x5017U
#define MTP_DEV_PROP_BURST_NUMBER 0x5018U
#define MTP_DEV_PROP_BURST_INTERVAL 0x5019U
#define MTP_DEV_PROP_TIMELAPSE_NUMBER 0x501AU
#define MTP_DEV_PROP_TIMELAPSE_INTERVAL 0x501BU
#define MTP_DEV_PROP_FOCUS_METERING_MODE 0x501CU
#define MTP_DEV_PROP_UPLOAD_URL 0x501DU
#define MTP_DEV_PROP_ARTIST 0x501EU
#define MTP_DEV_PROP_COPYRIGHT_INFO 0x501FU
#define MTP_DEV_PROP_SYNCHRONIZATION_PARTNER 0xD401U
#define MTP_DEV_PROP_DEVICE_FRIENDLY_NAME 0xD402U
#define MTP_DEV_PROP_VOLUME 0xD403U
#define MTP_DEV_PROP_SUPPORTEDFORMATSORDERED 0xD404U
#define MTP_DEV_PROP_DEVICEICON 0xD405U
#define MTP_DEV_PROP_PLAYBACK_RATE 0xD410U
#define MTP_DEV_PROP_PLAYBACK_OBJECT 0xD411U
#define MTP_DEV_PROP_PLAYBACK_CONTAINER 0xD412U
#define MTP_DEV_PROP_SESSION_INITIATOR_VERSION_INFO 0xD406U
#define MTP_DEV_PROP_PERCEIVED_DEVICE_TYPE 0xD407U
/* Container Types */
#define MTP_CONT_TYPE_UNDEFINED 0U
#define MTP_CONT_TYPE_COMMAND 1U
#define MTP_CONT_TYPE_DATA 2U
#define MTP_CONT_TYPE_RESPONSE 3U
#define MTP_CONT_TYPE_EVENT 4U
#ifndef MTP_STORAGE_ID
#define MTP_STORAGE_ID 0x00010001U /* SD card is inserted*/
#endif /* MTP_STORAGE_ID */
#define MTP_NBR_STORAGE_ID 1U
#define FREE_SPACE_IN_OBJ_NOT_USED 0xFFFFFFFFU
/* MTP storage type */
#define MTP_STORAGE_UNDEFINED 0U
#define MTP_STORAGE_FIXED_ROM 0x0001U
#define MTP_STORAGE_REMOVABLE_ROM 0x0002U
#define MTP_STORAGE_FIXED_RAM 0x0003U
#define MTP_STORAGE_REMOVABLE_RAM 0x0004U
/* MTP file system type */
#define MTP_FILESYSTEM_UNDEFINED 0U
#define MTP_FILESYSTEM_GENERIC_FLAT 0x0001U
#define MTP_FILESYSTEM_GENERIC_HIERARCH 0x0002U
#define MTP_FILESYSTEM_DCF 0x0003U
/* MTP access capability */
#define MTP_ACCESS_CAP_RW 0U /* read write */
#define MTP_ACCESS_CAP_RO_WITHOUT_DEL 0x0001U
#define MTP_ACCESS_CAP_RO_WITH_DEL 0x0002U
/* MTP standard data types supported */
#define MTP_DATATYPE_INT8 0x0001U
#define MTP_DATATYPE_UINT8 0x0002U
#define MTP_DATATYPE_INT16 0x0003U
#define MTP_DATATYPE_UINT16 0x0004U
#define MTP_DATATYPE_INT32 0x0005U
#define MTP_DATATYPE_UINT32 0x0006U
#define MTP_DATATYPE_INT64 0x0007U
#define MTP_DATATYPE_UINT64 0x0008U
#define MTP_DATATYPE_UINT128 0x000AU
#define MTP_DATATYPE_STR 0xFFFFU
/* MTP reading only or reading/writing */
#define MTP_PROP_GET 0x00U
#define MTP_PROP_GET_SET 0x01U
/* MTP functional mode */
#define STANDARD_MODE 0U
#define SLEEP_STATE 1U
#define FUNCTIONAL_MODE STANDARD_MODE
/* MTP device info */
#define STANDARD_VERSION 100U
#define VEND_EXT_ID 0x06U
#define VEND_EXT_VERSION 100U
#define MANUF_LEN (sizeof(Manuf) / 2U)
#define MODEL_LEN (sizeof(Model) / 2U)
#define SUPP_OP_LEN (sizeof(SuppOP) / 2U)
#define SERIAL_NBR_LEN (sizeof(SerialNbr) / 2U)
#define DEVICE_VERSION_LEN (sizeof(DeviceVers) / 2U)
#define SUPP_IMG_FORMAT_LEN (sizeof(SuppImgFormat) / 2U)
#define SUPP_OBJ_PROP_LEN (sizeof(ObjectPropSupp) / 2U)
#ifndef MAX_FILE_NAME
#define MAX_FILE_NAME 255U
#endif /* MAX_FILE_NAME */
#ifndef MAX_OBJECT_HANDLE_LEN
#define MAX_OBJECT_HANDLE_LEN 100U
#endif /* MAX_OBJECT_HANDLE_LEN */
#ifndef DEVICE_PROP_DESC_DEF_LEN
#define DEVICE_PROP_DESC_DEF_LEN (uint8_t)(sizeof(DevicePropDefVal) / 2U)
#endif /* DEVICE_PROP_DESC_DEF_LEN */
#ifndef DEVICE_PROP_DESC_CUR_LEN
#define DEVICE_PROP_DESC_CUR_LEN (uint8_t)(sizeof(DevicePropCurDefVal) / 2U)
#endif /* DEVICE_PROP_DESC_CUR_LEN */
#ifndef DEFAULT_FILE_NAME_LEN
#define DEFAULT_FILE_NAME_LEN (uint8_t)(sizeof(DefaultFileName) / 2U)
#endif /* DEFAULT_FILE_NAME_LEN */
/**
* @}
*/
/** @defgroup USBD_MTP_OPT_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
static const uint16_t SuppOP[] = { MTP_OP_GET_DEVICE_INFO, MTP_OP_OPEN_SESSION, MTP_OP_CLOSE_SESSION,
MTP_OP_GET_STORAGE_IDS, MTP_OP_GET_STORAGE_INFO, MTP_OP_GET_NUM_OBJECTS,
MTP_OP_GET_OBJECT_HANDLES, MTP_OP_GET_OBJECT_INFO, MTP_OP_GET_OBJECT,
MTP_OP_DELETE_OBJECT, MTP_OP_SEND_OBJECT_INFO, MTP_OP_SEND_OBJECT,
MTP_OP_GET_DEVICE_PROP_DESC, MTP_OP_GET_DEVICE_PROP_VALUE,
MTP_OP_SET_OBJECT_PROP_VALUE, MTP_OP_GET_OBJECT_PROP_VALUE,
MTP_OP_GET_OBJECT_PROPS_SUPPORTED, MTP_OP_GET_OBJECT_PROPLIST,
MTP_OP_GET_OBJECT_PROP_DESC, MTP_OP_GET_OBJECT_PROP_REFERENCES
};
static const uint16_t SuppEvents[] = {MTP_EVENT_OBJECTADDED};
static const uint16_t SuppImgFormat[] = {MTP_OBJ_FORMAT_UNDEFINED, MTP_OBJ_FORMAT_TEXT, MTP_OBJ_FORMAT_ASSOCIATION,
MTP_OBJ_FORMAT_EXECUTABLE, MTP_OBJ_FORMAT_WAV, MTP_OBJ_FORMAT_MP3,
MTP_OBJ_FORMAT_EXIF_JPEG, MTP_OBJ_FORMAT_MPEG, MTP_OBJ_FORMAT_MP4_CONTAINER,
MTP_OBJ_FORMAT_WINDOWS_IMAGE_FORMAT, MTP_OBJ_FORMAT_PNG, MTP_OBJ_FORMAT_WMA,
MTP_OBJ_FORMAT_WMV
};
static const uint16_t SuppCaptFormat[] = {MTP_OBJ_FORMAT_UNDEFINED, MTP_OBJ_FORMAT_ASSOCIATION, MTP_OBJ_FORMAT_TEXT};
/* required for all object format : storageID, objectFormat, ObjectCompressedSize,
persistent unique object identifier, name*/
static const uint16_t ObjectPropSupp[] = {MTP_OB_PROP_STORAGE_ID, MTP_OB_PROP_OBJECT_FORMAT, MTP_OB_PROP_OBJECT_SIZE,
MTP_OB_PROP_OBJ_FILE_NAME, MTP_OB_PROP_PARENT_OBJECT, MTP_OB_PROP_NAME,
MTP_OB_PROP_PERS_UNIQ_OBJ_IDEN, MTP_OB_PROP_PROTECTION_STATUS
};
static const uint16_t DevicePropSupp[] = {MTP_DEV_PROP_DEVICE_FRIENDLY_NAME, MTP_DEV_PROP_BATTERY_LEVEL};
/* for all mtp struct */
typedef struct
{
uint32_t StorageIDS_len;
uint32_t StorageIDS[MTP_NBR_STORAGE_ID];
} MTP_StorageIDSTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint8_t FileName_len;
uint16_t FileName[MAX_FILE_NAME];
} MTP_FileNameTypeDef;
typedef struct
{
uint32_t ObjectHandle_len;
uint32_t ObjectHandle[MAX_OBJECT_HANDLE_LEN];
} MTP_ObjectHandleTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint32_t ObjectPropSupp_len;
uint16_t ObjectPropSupp[SUPP_OBJ_PROP_LEN];
} MTP_ObjectPropSuppTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint16_t StorageType;
uint16_t FilesystemType;
uint16_t AccessCapability;
uint64_t MaxCapability;
uint64_t FreeSpaceInBytes;
uint32_t FreeSpaceInObjects;
uint8_t StorageDescription;
uint8_t VolumeLabel;
} MTP_StorageInfoTypedef;
typedef union
{
uint16_t str[100];
uint8_t u8;
int8_t i8;
uint16_t u16;
int16_t i16;
uint32_t u32;
int32_t i32;
uint64_t u64;
int64_t i64;
} MTP_PropertyValueTypedef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint16_t ObjectPropertyCode;
uint16_t DataType;
uint8_t GetSet;
uint8_t *DefValue;
uint32_t GroupCode;
uint8_t FormFlag;
} MTP_ObjectPropDescTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint32_t ObjectHandle;
uint16_t PropertyCode;
uint16_t Datatype;
uint8_t *propval;
} MTP_PropertiesTypedef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint32_t MTP_Properties_len;
MTP_PropertiesTypedef MTP_Properties[SUPP_OBJ_PROP_LEN];
} MTP_PropertiesListTypedef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint32_t ref_len;
uint32_t ref[1];
} MTP_RefTypeDef;
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint16_t DevicePropertyCode;
uint16_t DataType;
uint8_t GetSet;
uint8_t DefValue_len;
uint16_t DefValue[DEVICE_PROP_DESC_DEF_LEN];
uint8_t curDefValue_len;
uint16_t curDefValue[DEVICE_PROP_DESC_CUR_LEN];
uint8_t FormFlag;
} MTP_DevicePropDescTypeDef;
/* MTP device info structure */
#if defined ( __GNUC__ )
typedef __PACKED_STRUCT
#else
__packed typedef struct
#endif /* __GNUC__ */
{
uint16_t StandardVersion;
uint32_t VendorExtensionID;
uint16_t VendorExtensionVersion;
uint8_t VendorExtensionDesc_len;
#if USBD_MTP_VEND_EXT_DESC_SUPPORTED == 1
uint16_t VendorExtensionDesc[VEND_EXT_DESC_LEN];
#endif /* USBD_MTP_VEND_EXT_DESC_SUPPORTED */
uint16_t FunctionalMode;
uint32_t OperationsSupported_len;
uint16_t OperationsSupported[SUPP_OP_LEN];
uint32_t EventsSupported_len;
#if USBD_MTP_EVENTS_SUPPORTED == 1
uint16_t EventsSupported[SUPP_EVENTS_LEN];
#endif /* USBD_MTP_EVENTS_SUPPORTED */
uint32_t DevicePropertiesSupported_len;
#if USBD_MTP_DEVICE_PROP_SUPPORTED == 1
uint16_t DevicePropertiesSupported[SUPP_DEVICE_PROP_LEN];
#endif /* USBD_MTP_DEVICE_PROP_SUPPORTED */
uint32_t CaptureFormats_len;
#if USBD_MTP_CAPTURE_FORMAT_SUPPORTED == 1
uint16_t CaptureFormats[SUPP_CAPT_FORMAT_LEN];
#endif /* USBD_MTP_CAPTURE_FORMAT_SUPPORTED */
uint32_t ImageFormats_len;
uint16_t ImageFormats[SUPP_IMG_FORMAT_LEN];
uint8_t Manufacturer_len;
uint16_t Manufacturer[MANUF_LEN];
uint8_t Model_len;
uint16_t Model[MODEL_LEN];
uint8_t DeviceVersion_len;
uint16_t DeviceVersion[DEVICE_VERSION_LEN];
uint8_t SerialNumber_len;
uint16_t SerialNumber[SERIAL_NBR_LEN];
} MTP_DeviceInfoTypedef;
/** @defgroup USBD_MTP_OPT_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_OPT_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_OPT_Exported_Functions
* @{
*/
void USBD_MTP_OPT_CreateObjectHandle(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetDeviceInfo(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetStorageIDS(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetStorageInfo(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectHandle(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectInfo(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectReferences(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectPropSupp(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectPropDesc(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectPropValue(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetObjectPropList(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_GetDevicePropDesc(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_SendObjectInfo(USBD_HandleTypeDef *pdev, uint8_t *buff, uint32_t len);
void USBD_MTP_OPT_SendObject(USBD_HandleTypeDef *pdev, uint8_t *buff, uint32_t len);
void USBD_MTP_OPT_GetObject(USBD_HandleTypeDef *pdev);
void USBD_MTP_OPT_DeleteObject(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MTP_OPT_H__ */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Inc\usbd_mtp_storage.h | /**
******************************************************************************
* @file usbd_mtp_storage.h
* @author MCD Application Team
* @brief header file for the usbd_mtp_storage.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_MTP_STORAGE_H__
#define __USBD_MTP_STORAGE_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ctlreq.h"
#include "usbd_mtp_opt.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_MTP_STORAGE
* @brief This file is the header file for usbd_template_core.c
* @{
*/
/** @defgroup USBD_MTP_STORAGE_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_STORAGE_Exported_TypesDefinitions
* @{
*/
typedef enum
{
DATA_TYPE = 0x00,
REP_TYPE = 0x01,
} MTP_CONTAINER_TYPE;
typedef enum
{
READ_FIRST_DATA = 0x00,
READ_REST_OF_DATA = 0x01,
} MTP_READ_DATA_STATUS;
/**
* @}
*/
/** @defgroup USBD_MTP_STORAGE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_STORAGE_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_STORAGE_Exported_Functions
* @{
*/
uint8_t USBD_MTP_STORAGE_Init(USBD_HandleTypeDef *pdev);
uint8_t USBD_MTP_STORAGE_DeInit(USBD_HandleTypeDef *pdev);
void USBD_MTP_STORAGE_Cancel(USBD_HandleTypeDef *pdev, MTP_ResponsePhaseTypeDef MTP_ResponsePhase);
uint8_t USBD_MTP_STORAGE_ReadData(USBD_HandleTypeDef *pdev);
uint8_t USBD_MTP_STORAGE_SendContainer(USBD_HandleTypeDef *pdev, MTP_CONTAINER_TYPE CONT_TYPE);
uint8_t USBD_MTP_STORAGE_ReceiveOpt(USBD_HandleTypeDef *pdev);
uint8_t USBD_MTP_STORAGE_ReceiveData(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_MTP_STORAGE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Src\usbd_mtp.c | /**
******************************************************************************
* @file usbd_mtp.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB MTP Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as MTP Device (and enumeration for each implemented memory interface)
* - OUT/IN data transfer
* - Command IN transfer (class requests management)
* - Error management
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
* @verbatim
*
* ===================================================================
* MTP Class Driver Description
* ===================================================================
* This driver manages the "Universal Serial Bus Class Definitions for Media Transfer Protocol
* Revision 1.1 April 6, 2011"
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as MTP device with 2 data endpoints (IN and OUT) and 1 command endpoint (IN)
* - Requests management
*
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_mtp.h"
#include "usbd_mtp_storage.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_MTP
* @brief usbd core module
* @{
*/
/** @defgroup USBD_MTP_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_MTP_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_MTP_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_MTP_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_MTP_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_MTP_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_MTP_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_MTP_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_MTP_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_MTP_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_MTP_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_MTP_Private_Variables
* @{
*/
/* MTP interface class callbacks structure */
USBD_ClassTypeDef USBD_MTP =
{
USBD_MTP_Init,
USBD_MTP_DeInit,
USBD_MTP_Setup,
NULL, /*EP0_TxSent*/
NULL, /*EP0_RxReady*/
USBD_MTP_DataIn,
USBD_MTP_DataOut,
NULL, /*SOF */
NULL, /*ISOIn*/
NULL, /*ISOOut*/
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_MTP_GetHSCfgDesc,
USBD_MTP_GetFSCfgDesc,
USBD_MTP_GetOtherSpeedCfgDesc,
USBD_MTP_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB MTP device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_MTP_CfgDesc[MTP_CONFIG_DESC_SIZ] __ALIGN_END =
{
/* Configuration Descriptor */
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
LOBYTE(MTP_CONFIG_DESC_SIZ), /* wTotalLength: Total size of the Config descriptor */
HIBYTE(MTP_CONFIG_DESC_SIZ),
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower (mA) */
/******************** MTP **** interface ********************/
MTP_INTERFACE_DESC_SIZE, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface descriptor type */
MTP_CMD_ITF_NBR, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x03, /* bNumEndpoints: */
USB_MTP_INTRERFACE_CLASS, /* bInterfaceClass: bInterfaceClass: user's interface for MTP */
USB_MTP_INTRERFACE_SUB_CLASS, /* bInterfaceSubClass:Abstract Control Model */
USB_MTP_INTRERFACE_PROTOCOL, /* bInterfaceProtocol: Common AT commands */
0x00, /* iInterface: */
/******************** MTP Endpoints ********************/
MTP_ENDPOINT_DESC_SIZE, /* Endpoint descriptor length = 7 */
USB_DESC_TYPE_ENDPOINT, /* Endpoint descriptor type */
MTP_IN_EP, /* Endpoint address (IN, address 1) */
USBD_EP_TYPE_BULK, /* Bulk endpoint type */
LOBYTE(MTP_DATA_MAX_FS_PACKET_SIZE),
HIBYTE(MTP_DATA_MAX_FS_PACKET_SIZE),
0x00, /* Polling interval in milliseconds */
MTP_ENDPOINT_DESC_SIZE, /* Endpoint descriptor length = 7 */
USB_DESC_TYPE_ENDPOINT, /* Endpoint descriptor type */
MTP_OUT_EP, /* Endpoint address (OUT, address 1) */
USBD_EP_TYPE_BULK, /* Bulk endpoint type */
LOBYTE(MTP_DATA_MAX_FS_PACKET_SIZE),
HIBYTE(MTP_DATA_MAX_FS_PACKET_SIZE),
0x00, /* Polling interval in milliseconds */
MTP_ENDPOINT_DESC_SIZE, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType:*/
MTP_CMD_EP, /* bEndpointAddress: Endpoint Address (IN) */
USBD_EP_TYPE_INTR, /* bmAttributes: Interrupt endpoint */
LOBYTE(MTP_CMD_PACKET_SIZE),
HIBYTE(MTP_CMD_PACKET_SIZE),
MTP_FS_BINTERVAL /* Polling interval in milliseconds */
};
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_MTP_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
uint8_t MTPInEpAdd = MTP_IN_EP;
uint8_t MTPOutEpAdd = MTP_OUT_EP;
uint8_t MTPCmdEpAdd = MTP_CMD_EP;
/**
* @}
*/
/** @defgroup USBD_MTP_Private_Functions
* @{
*/
/**
* @brief USBD_MTP_Init
* Initialize the MTP interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_MTP_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_MTP_HandleTypeDef *hmtp;
hmtp = (USBD_MTP_HandleTypeDef *)USBD_malloc(sizeof(USBD_MTP_HandleTypeDef));
if (hmtp == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
/* Setup the pClassData pointer */
pdev->pClassDataCmsit[pdev->classId] = (void *)hmtp;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MTPInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MTPCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Initialize all variables */
(void)USBD_memset(hmtp, 0, sizeof(USBD_MTP_HandleTypeDef));
/* Setup the max packet size according to selected speed */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
hmtp->MaxPcktLen = MTP_DATA_MAX_HS_PACKET_SIZE;
}
else
{
hmtp->MaxPcktLen = MTP_DATA_MAX_FS_PACKET_SIZE;
}
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, MTPInEpAdd, USBD_EP_TYPE_BULK, hmtp->MaxPcktLen);
pdev->ep_in[MTPInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, MTPOutEpAdd, USBD_EP_TYPE_BULK, hmtp->MaxPcktLen);
pdev->ep_out[MTPOutEpAdd & 0xFU].is_used = 1U;
/* Open INTR EP IN */
(void)USBD_LL_OpenEP(pdev, MTPCmdEpAdd, USBD_EP_TYPE_INTR, MTP_CMD_PACKET_SIZE);
pdev->ep_in[MTPCmdEpAdd & 0xFU].is_used = 1U;
/* Init the MTP layer */
(void)USBD_MTP_STORAGE_Init(pdev);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_DeInit
* DeInitialize the MTP layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_MTP_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this MTP class instance */
MTPInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MTPCmdEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_INTR, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, MTPInEpAdd);
pdev->ep_in[MTPInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, MTPOutEpAdd);
pdev->ep_out[MTPOutEpAdd & 0xFU].is_used = 0U;
/* Close EP Command */
(void)USBD_LL_CloseEP(pdev, MTPCmdEpAdd);
pdev->ep_in[MTPCmdEpAdd & 0xFU].is_used = 0U;
/* Free MTP Class Resources */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
/* De-Init the MTP layer */
(void)USBD_MTP_STORAGE_DeInit(pdev);
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_Setup
* Handle the MTP specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_MTP_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint16_t len = 0U;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this MTP class instance */
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hmtp == NULL)
{
return (uint8_t)USBD_FAIL;
}
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
/* Class request */
case USB_REQ_TYPE_CLASS :
switch (req->bRequest)
{
case MTP_REQ_CANCEL:
len = MIN(hmtp->MaxPcktLen, req->wLength);
(void)USBD_CtlPrepareRx(pdev, (uint8_t *)(hmtp->rx_buff), len);
break;
case MTP_REQ_GET_EXT_EVENT_DATA:
break;
case MTP_REQ_RESET:
/* Stop low layer file system operations if any */
USBD_MTP_STORAGE_Cancel(pdev, MTP_PHASE_IDLE);
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff, hmtp->MaxPcktLen);
break;
case MTP_REQ_GET_DEVICE_STATUS:
switch (hmtp->MTP_ResponsePhase)
{
case MTP_READ_DATA :
len = 4U;
hmtp->dev_status = ((uint32_t)MTP_RESPONSE_DEVICE_BUSY << 16) | len;
break;
case MTP_RECEIVE_DATA :
len = 4U;
hmtp->dev_status = ((uint32_t)MTP_RESPONSE_TRANSACTION_CANCELLED << 16) | len;
break;
case MTP_PHASE_IDLE :
len = 4U;
hmtp->dev_status = ((uint32_t)MTP_RESPONSE_OK << 16) | len;
break;
default:
break;
}
(void)USBD_CtlSendData(pdev, (uint8_t *)&hmtp->dev_status, len);
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
/* Interface & Endpoint request */
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_INTERFACE :
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
hmtp->alt_setting = 0U;
(void)USBD_CtlSendData(pdev, (uint8_t *)&hmtp->alt_setting, 1U);
}
break;
case USB_REQ_SET_INTERFACE :
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
/* Re-activate the EP */
(void)USBD_LL_CloseEP(pdev, (uint8_t)req->wIndex);
if ((((uint8_t)req->wIndex) & 0x80U) == 0x80U)
{
(void)USBD_LL_OpenEP(pdev, ((uint8_t)req->wIndex), USBD_EP_TYPE_BULK, hmtp->MaxPcktLen);
}
else
{
(void)USBD_LL_OpenEP(pdev, ((uint8_t)req->wIndex), USBD_EP_TYPE_BULK, hmtp->MaxPcktLen);
}
break;
default:
break;
}
break;
default:
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_MTP_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_MTP_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this MTP class instance */
MTPInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (epnum == (MTPInEpAdd & 0x7FU))
{
switch (hmtp->MTP_ResponsePhase)
{
case MTP_RESPONSE_PHASE :
(void)USBD_MTP_STORAGE_SendContainer(pdev, REP_TYPE);
/* prepare to receive next operation */
len = MIN(hmtp->MaxPcktLen, pdev->request.wLength);
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff, len);
hmtp->MTP_ResponsePhase = MTP_PHASE_IDLE;
break;
case MTP_READ_DATA :
(void)USBD_MTP_STORAGE_ReadData(pdev);
/* prepare to receive next operation */
len = MIN(hmtp->MaxPcktLen, pdev->request.wLength);
(void)USBD_LL_PrepareReceive(pdev, MTPInEpAdd, (uint8_t *)&hmtp->rx_buff, len);
break;
case MTP_PHASE_IDLE :
/* prepare to receive next operation */
len = MIN(hmtp->MaxPcktLen, pdev->request.wLength);
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff, len);
break;
default:
break;
}
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_MTP_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
UNUSED(epnum);
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t len;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this MTP class instance */
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
(void)USBD_MTP_STORAGE_ReceiveOpt(pdev);
switch (hmtp->MTP_ResponsePhase)
{
case MTP_RESPONSE_PHASE :
if (hmtp->ResponseLength == MTP_CONT_HEADER_SIZE)
{
(void)USBD_MTP_STORAGE_SendContainer(pdev, REP_TYPE);
hmtp->MTP_ResponsePhase = MTP_PHASE_IDLE;
}
else
{
(void)USBD_MTP_STORAGE_SendContainer(pdev, DATA_TYPE);
}
break;
case MTP_READ_DATA :
(void)USBD_MTP_STORAGE_ReadData(pdev);
break;
case MTP_RECEIVE_DATA :
(void)USBD_MTP_STORAGE_ReceiveData(pdev);
/* prepare endpoint to receive operations */
len = MIN(hmtp->MaxPcktLen, pdev->request.wLength);
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff, len);
break;
case MTP_PHASE_IDLE :
/* prepare to receive next operation */
len = MIN(hmtp->MaxPcktLen, pdev->request.wLength);
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff, len);
break;
default:
break;
}
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_MTP_GetHSCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_MTP_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MTP_DATA_MAX_HS_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MTP_DATA_MAX_HS_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = MTP_HS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_MTP_CfgDesc);
return USBD_MTP_CfgDesc;
}
/**
* @brief USBD_MTP_GetFSCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_MTP_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MTP_DATA_MAX_FS_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MTP_DATA_MAX_FS_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = MTP_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_MTP_CfgDesc);
return USBD_MTP_CfgDesc;
}
/**
* @brief USBD_MTP_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param speed : current device speed
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_MTP_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_OUT_EP);
USBD_EpDescTypeDef *pEpCmdDesc = USBD_GetEpDesc(USBD_MTP_CfgDesc, MTP_CMD_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = MTP_DATA_MAX_FS_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = MTP_DATA_MAX_FS_PACKET_SIZE;
}
if (pEpCmdDesc != NULL)
{
pEpCmdDesc->bInterval = MTP_FS_BINTERVAL;
}
*length = (uint16_t)sizeof(USBD_MTP_CfgDesc);
return USBD_MTP_CfgDesc;
}
/**
* @brief USBD_MTP_GetDeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_MTP_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)(sizeof(USBD_MTP_DeviceQualifierDesc));
return USBD_MTP_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_MTP_RegisterInterface
* @param pdev: device instance
* @param fops: CD Interface callback
* @retval status
*/
uint8_t USBD_MTP_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_MTP_ItfTypeDef *fops)
{
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Src\usbd_mtp_if_template.c | /**
******************************************************************************
* @file usbd_mtp_if.c
* @author MCD Application Team
* @brief Source file for USBD MTP file list_files.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_mtp_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/*
static FILE MyFile;
static FATFS SDFatFs;
static char SDPath[4];
static FolderLevel Fold_Lvl;
static FOLD_INFTypeDef FoldStruct;
static FILE_INFTypeDef FileStruct;
static SD_Object_TypeDef sd_object;
*/
extern USBD_HandleTypeDef USBD_Device;
uint32_t idx[200];
uint32_t parent;
/* static char path[255]; */
uint32_t sc_buff[MTP_IF_SCRATCH_BUFF_SZE / 4U];
uint32_t sc_len = 0U;
uint32_t pckt_cnt = 1U;
uint32_t foldsize;
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static uint8_t USBD_MTP_Itf_Init(void);
static uint8_t USBD_MTP_Itf_DeInit(void);
static uint32_t USBD_MTP_Itf_ReadData(uint32_t Param1, uint8_t *buff, MTP_DataLengthTypeDef *data_length);
static uint16_t USBD_MTP_Itf_Create_NewObject(MTP_ObjectInfoTypeDef ObjectInfo, uint32_t objhandle);
static uint32_t USBD_MTP_Itf_GetIdx(uint32_t Param3, uint32_t *obj_handle);
static uint32_t USBD_MTP_Itf_GetParentObject(uint32_t Param);
static uint16_t USBD_MTP_Itf_GetObjectFormat(uint32_t Param);
static uint8_t USBD_MTP_Itf_GetObjectName_len(uint32_t Param);
static void USBD_MTP_Itf_GetObjectName(uint32_t Param, uint8_t obj_len, uint16_t *buf);
static uint32_t USBD_MTP_Itf_GetObjectSize(uint32_t Param);
static uint64_t USBD_MTP_Itf_GetMaxCapability(void);
static uint64_t USBD_MTP_Itf_GetFreeSpaceInBytes(void);
static uint32_t USBD_MTP_Itf_GetNewIndex(uint16_t objformat);
static void USBD_MTP_Itf_WriteData(uint16_t len, uint8_t *buff);
static uint32_t USBD_MTP_Itf_GetContainerLength(uint32_t Param1);
static uint16_t USBD_MTP_Itf_DeleteObject(uint32_t Param1);
static void USBD_MTP_Itf_Cancel(uint32_t Phase);
/* static uint32_t USBD_MTP_Get_idx_to_delete(uint32_t Param, uint8_t *tab); */
USBD_MTP_ItfTypeDef USBD_MTP_fops =
{
USBD_MTP_Itf_Init,
USBD_MTP_Itf_DeInit,
USBD_MTP_Itf_ReadData,
USBD_MTP_Itf_Create_NewObject,
USBD_MTP_Itf_GetIdx,
USBD_MTP_Itf_GetParentObject,
USBD_MTP_Itf_GetObjectFormat,
USBD_MTP_Itf_GetObjectName_len,
USBD_MTP_Itf_GetObjectName,
USBD_MTP_Itf_GetObjectSize,
USBD_MTP_Itf_GetMaxCapability,
USBD_MTP_Itf_GetFreeSpaceInBytes,
USBD_MTP_Itf_GetNewIndex,
USBD_MTP_Itf_WriteData,
USBD_MTP_Itf_GetContainerLength,
USBD_MTP_Itf_DeleteObject,
USBD_MTP_Itf_Cancel,
sc_buff,
MTP_IF_SCRATCH_BUFF_SZE,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief USBD_MTP_Itf_Init
* Initialize the file system Layer
* @param None
* @retval status value
*/
static uint8_t USBD_MTP_Itf_Init(void)
{
return 0;
}
/**
* @brief USBD_MTP_Itf_DeInit
* Uninitialize the file system Layer
* @param None
* @retval status value
*/
static uint8_t USBD_MTP_Itf_DeInit(void)
{
return 0;
}
/**
* @brief USBD_MTP_Itf_GetIdx
* Get all object handle
* @param Param3: current object handle
* @param obj_handle: all objects handle (subfolders/files) in current object
* @retval number of object handle in current object
*/
static uint32_t USBD_MTP_Itf_GetIdx(uint32_t Param3, uint32_t *obj_handle)
{
uint32_t count = 0U;
UNUSED(Param3);
UNUSED(obj_handle);
return count;
}
/**
* @brief USBD_MTP_Itf_GetParentObject
* Get parent object
* @param Param: object handle (object index)
* @retval parent object
*/
static uint32_t USBD_MTP_Itf_GetParentObject(uint32_t Param)
{
uint32_t parentobj = 0U;
UNUSED(Param);
return parentobj;
}
/**
* @brief USBD_MTP_Itf_GetObjectFormat
* Get object format
* @param Param: object handle (object index)
* @retval object format
*/
static uint16_t USBD_MTP_Itf_GetObjectFormat(uint32_t Param)
{
uint16_t objformat = 0U;
UNUSED(Param);
return objformat;
}
/**
* @brief USBD_MTP_Itf_GetObjectName_len
* Get object name length
* @param Param: object handle (object index)
* @retval object name length
*/
static uint8_t USBD_MTP_Itf_GetObjectName_len(uint32_t Param)
{
uint8_t obj_len = 0U;
UNUSED(Param);
return obj_len;
}
/**
* @brief USBD_MTP_Itf_GetObjectName
* Get object name
* @param Param: object handle (object index)
* @param obj_len: length of object name
* @param buf: pointer to object name
* @retval object size in SD card
*/
static void USBD_MTP_Itf_GetObjectName(uint32_t Param, uint8_t obj_len, uint16_t *buf)
{
UNUSED(Param);
UNUSED(obj_len);
UNUSED(buf);
return;
}
/**
* @brief USBD_MTP_Itf_GetObjectSize
* Get size of current object
* @param Param: object handle (object index)
* @retval object size in SD card
*/
static uint32_t USBD_MTP_Itf_GetObjectSize(uint32_t Param)
{
uint32_t ObjCompSize = 0U;
UNUSED(Param);
return ObjCompSize;
}
/**
* @brief USBD_MTP_Itf_Create_NewObject
* Create new object in SD card and store necessary information for future use
* @param ObjectInfo: object information to use
* @param objhandle: object handle (object index)
* @retval None
*/
static uint16_t USBD_MTP_Itf_Create_NewObject(MTP_ObjectInfoTypeDef ObjectInfo, uint32_t objhandle)
{
uint16_t rep_code = 0U;
UNUSED(ObjectInfo);
UNUSED(objhandle);
return rep_code;
}
/**
* @brief USBD_MTP_Itf_GetMaxCapability
* Get max capability in SD card
* @param None
* @retval max capability
*/
static uint64_t USBD_MTP_Itf_GetMaxCapability(void)
{
uint64_t max_cap = 0U;
return max_cap;
}
/**
* @brief USBD_MTP_Itf_GetFreeSpaceInBytes
* Get free space in bytes in SD card
* @param None
* @retval free space in bytes
*/
static uint64_t USBD_MTP_Itf_GetFreeSpaceInBytes(void)
{
uint64_t f_space_inbytes = 0U;
return f_space_inbytes;
}
/**
* @brief USBD_MTP_Itf_GetNewIndex
* Create new object handle
* @param objformat: object format
* @retval object handle
*/
static uint32_t USBD_MTP_Itf_GetNewIndex(uint16_t objformat)
{
uint32_t n_index = 0U;
UNUSED(objformat);
return n_index;
}
/**
* @brief USBD_MTP_Itf_WriteData
* Write file data to SD card
* @param len: size of data to write
* @param buff: data to write in SD card
* @retval None
*/
static void USBD_MTP_Itf_WriteData(uint16_t len, uint8_t *buff)
{
UNUSED(len);
UNUSED(buff);
return;
}
/**
* @brief USBD_MTP_Itf_GetContainerLength
* Get length of generic container
* @param Param1: object handle
* @retval length of generic container
*/
static uint32_t USBD_MTP_Itf_GetContainerLength(uint32_t Param1)
{
uint32_t length = 0U;
UNUSED(Param1);
return length;
}
/**
* @brief USBD_MTP_Itf_DeleteObject
* delete object from SD card
* @param Param1: object handle (file/folder index)
* @retval response code
*/
static uint16_t USBD_MTP_Itf_DeleteObject(uint32_t Param1)
{
uint16_t rep_code = 0U;
UNUSED(Param1);
return rep_code;
}
/**
* @brief USBD_MTP_Get_idx_to_delete
* Get all files/foldres index to delete with descending order ( max depth)
* @param Param: object handle (file/folder index)
* @param tab: pointer to list of files/folders to delete
* @retval Number of files/folders to delete
*/
/* static uint32_t USBD_MTP_Get_idx_to_delete(uint32_t Param, uint8_t *tab)
{
uint32_t cnt = 0U;
return cnt;
}
*/
/**
* @brief USBD_MTP_Itf_ReadData
* Read data from SD card
* @param Param1: object handle
* @param buff: pointer to data to be read
* @param temp_length: current data size read
* @retval necessary information for next read/finish reading
*/
static uint32_t USBD_MTP_Itf_ReadData(uint32_t Param1, uint8_t *buff, MTP_DataLengthTypeDef *data_length)
{
UNUSED(Param1);
UNUSED(buff);
UNUSED(data_length);
return 0U;
}
/**
* @brief USBD_MTP_Itf_Cancel
* Close opened folder/file while cancelling transaction
* @param MTP_ResponsePhase: MTP current state
* @retval None
*/
static void USBD_MTP_Itf_Cancel(uint32_t Phase)
{
UNUSED(Phase);
/* Make sure to close open file while canceling transaction */
return;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Src\usbd_mtp_opt.c | /**
******************************************************************************
* @file usbd_mtp_opt.c
* @author MCD Application Team
* @brief This file includes the PTP operations layer
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_mtp_opt.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static uint8_t ObjInfo_buff[255];
static uint32_t objhandle;
static uint16_t obj_format;
static uint32_t storage_id;
static MTP_DeviceInfoTypedef MTP_DeviceInfo;
static MTP_StorageIDSTypeDef MTP_StorageIDS;
static MTP_StorageInfoTypedef MTP_StorageInfo;
static MTP_ObjectHandleTypeDef MTP_ObjectHandle;
static MTP_ObjectInfoTypeDef MTP_ObjectInfo;
static MTP_ObjectPropSuppTypeDef MTP_ObjectPropSupp;
static MTP_ObjectPropDescTypeDef MTP_ObjectPropDesc;
static MTP_PropertiesListTypedef MTP_PropertiesList;
static MTP_RefTypeDef MTP_Ref;
static MTP_PropertyValueTypedef MTP_PropertyValue;
static MTP_FileNameTypeDef MTP_FileName;
static MTP_DevicePropDescTypeDef MTP_DevicePropDesc;
/* Private function prototypes -----------------------------------------------*/
static void MTP_Get_DeviceInfo(void);
static void MTP_Get_StorageIDS(void);
static void MTP_Get_PayloadContent(USBD_HandleTypeDef *pdev);
static void MTP_Get_ObjectInfo(USBD_HandleTypeDef *pdev);
static void MTP_Get_StorageInfo(USBD_HandleTypeDef *pdev);
static void MTP_Get_ObjectHandle(USBD_HandleTypeDef *pdev);
static void MTP_Get_ObjectPropSupp(void);
static void MTP_Get_ObjectPropDesc(USBD_HandleTypeDef *pdev);
static void MTP_Get_ObjectPropList(USBD_HandleTypeDef *pdev);
static void MTP_Get_DevicePropDesc(void);
static uint8_t *MTP_Get_ObjectPropValue(USBD_HandleTypeDef *pdev);
static uint32_t MTP_build_data_propdesc(USBD_HandleTypeDef *pdev, MTP_ObjectPropDescTypeDef def);
static uint32_t MTP_build_data_ObjInfo(USBD_HandleTypeDef *pdev, MTP_ObjectInfoTypeDef objinfo);
static uint32_t MTP_build_data_proplist(USBD_HandleTypeDef *pdev,
MTP_PropertiesListTypedef proplist, uint32_t idx);
/* Private functions ---------------------------------------------------------*/
/**
* @}
*/
/**
* @brief USBD_MTP_OPT_CreateObjectHandle
* Open a new session
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_CreateObjectHandle(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmtp->OperationsContainer.Param1 == 0U) /* Param1 == Session ID*/
{
hmtp->ResponseCode = MTP_RESPONSE_INVALID_PARAMETER;
}
/* driver supports single session */
else if (hmtp->MTP_SessionState == MTP_SESSION_OPENED)
{
hmtp->ResponseCode = MTP_RESPONSE_SESSION_ALREADY_OPEN;
}
else
{
hmtp->ResponseCode = MTP_RESPONSE_OK;
hmtp->MTP_SessionState = MTP_SESSION_OPENED;
}
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
}
/**
* @brief USBD_MTP_OPT_GetDeviceInfo
* Get all device information
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetDeviceInfo(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hmtp->MTP_SessionState == MTP_SESSION_NOT_OPENED) /* no session opened */
{
/* if GetDevice Info called outside a session then SessionID and Transaction_ID shall be 0x00000000*/
/* Param1 == session ID*/
if ((hmtp->OperationsContainer.Param1 == 0U) && (hmtp->OperationsContainer.trans_id == 0U))
{
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
else
{
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->ResponseCode = MTP_RESPONSE_INVALID_PARAMETER;
hmtp->GenericContainer.length = MTP_CONT_HEADER_SIZE;
}
}
else
{
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
if (hmtp->ResponseCode == MTP_RESPONSE_OK)
{
hmtp->GenericContainer.code = MTP_OP_GET_DEVICE_INFO;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_DeviceInfo) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
}
}
/**
* @brief USBD_MTP_OPT_GetStorageIDS
* Get Storage IDs
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetStorageIDS(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_STORAGE_IDS;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_StorageIDS) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetStorageInfo
* Get Storage information
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetStorageInfo(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_STORAGE_INFO;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_StorageInfo) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectHandle
* Get all object handles
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectHandle(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_HANDLES;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = hmtp->ResponseLength + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectInfo
* Get all information about the object
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectInfo(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_INFO;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = hmtp->ResponseLength + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectReferences
* Get object references
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectReferences(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_PROP_REFERENCES;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_Ref) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectPropSupp
* Get all object properties supported
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectPropSupp(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_PROPS_SUPPORTED;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_ObjectPropSupp) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectPropDesc
* Get all descriptions about object properties
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectPropDesc(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_PROP_DESC;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = hmtp->ResponseLength + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectPropList
* Get the list of object properties
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectPropList(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_PROPLIST;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = hmtp->ResponseLength + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObjectPropValue
* Get current value of the object property
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObjectPropValue(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_OBJECT_PROP_VALUE;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = hmtp->ResponseLength + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetObject
* Get binary data from an object
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetObject(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
hmtp->GenericContainer.length = hmtpif->GetContainerLength(hmtp->OperationsContainer.Param1);
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_GetDevicePropDesc
* Get The DevicePropDesc dataset
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_GetDevicePropDesc(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->GenericContainer.code = MTP_OP_GET_DEVICE_PROP_DESC;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_DATA;
(void)MTP_Get_PayloadContent(pdev);
hmtp->ResponseLength = sizeof(MTP_DevicePropDesc) + MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_SendObject
* Send object from host to MTP device
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_SendObject(USBD_HandleTypeDef *pdev, uint8_t *buff, uint32_t len)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
static uint32_t tmp = 0U;
switch (hmtp->RECEIVE_DATA_STATUS)
{
case RECEIVE_IDLE_STATE:
hmtp->RECEIVE_DATA_STATUS = RECEIVE_COMMAND_DATA;
break;
case RECEIVE_COMMAND_DATA:
hmtp->RECEIVE_DATA_STATUS = RECEIVE_FIRST_DATA;
break;
case RECEIVE_FIRST_DATA:
if ((uint16_t)len < (hmtp->MaxPcktLen - MTP_CONT_HEADER_SIZE))
{
hmtp->GenericContainer.code = MTP_RESPONSE_OK;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->RECEIVE_DATA_STATUS = RECEIVE_IDLE_STATE;
}
else
{
hmtp->RECEIVE_DATA_STATUS = RECEIVE_REST_OF_DATA;
}
tmp = (uint32_t)buff;
hmtpif->WriteData(len, (uint8_t *)(tmp + 12U));
break;
case RECEIVE_REST_OF_DATA:
hmtpif->WriteData(len, buff);
break;
case SEND_RESPONSE:
hmtpif->WriteData(0, buff); /* send 0 length to stop write process */
hmtp->GenericContainer.code = MTP_RESPONSE_OK;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->RECEIVE_DATA_STATUS = RECEIVE_IDLE_STATE;
break;
default:
break;
}
hmtp->ResponseCode = MTP_RESPONSE_OK;
}
/**
* @brief USBD_MTP_OPT_SendObjectInfo
* Send the object information from host to MTP device
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_SendObjectInfo(USBD_HandleTypeDef *pdev, uint8_t *buff, uint32_t len)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
MTP_ObjectInfoTypeDef ObjectInfo;
uint8_t dataLength = offsetof(MTP_ObjectInfoTypeDef, Filename);
uint8_t *tmp;
switch (hmtp->RECEIVE_DATA_STATUS)
{
case RECEIVE_IDLE_STATE:
hmtp->RECEIVE_DATA_STATUS = RECEIVE_COMMAND_DATA;
break;
case RECEIVE_COMMAND_DATA:
/* store object handle and storage id for future use */
if (hmtp->OperationsContainer.Param2 == 0xFFFFFFFFU)
{
objhandle = 0U;
}
else
{
objhandle = hmtp->OperationsContainer.Param2;
}
storage_id = hmtp->OperationsContainer.Param1;
hmtp->RECEIVE_DATA_STATUS = RECEIVE_FIRST_DATA;
break;
case RECEIVE_FIRST_DATA:
tmp = buff;
(void)USBD_memcpy(ObjInfo_buff, tmp + 12U,
(uint16_t)(hmtp->MaxPcktLen - MTP_CONT_HEADER_SIZE));
hmtp->RECEIVE_DATA_STATUS = RECEIVE_REST_OF_DATA;
break;
case RECEIVE_REST_OF_DATA:
(void)USBD_memcpy(ObjInfo_buff + len, buff, hmtp->MaxPcktLen);
break;
case SEND_RESPONSE:
(void)USBD_memcpy((uint8_t *)&ObjectInfo, ObjInfo_buff, dataLength);
(void)USBD_memcpy((uint8_t *)&ObjectInfo.Filename, (ObjInfo_buff + dataLength),
((uint32_t)(ObjectInfo.Filename_len) * 2U));
obj_format = ObjectInfo.ObjectFormat;
hmtp->ResponseCode = hmtpif->Create_NewObject(ObjectInfo, objhandle);
hmtp->GenericContainer.code = (uint16_t)hmtp->ResponseCode;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE + (sizeof(uint32_t) * 3U); /* Header + 3 Param */
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
(void)MTP_Get_PayloadContent(pdev);
hmtp->RECEIVE_DATA_STATUS = RECEIVE_IDLE_STATE;
break;
default:
break;
}
}
/**
* @brief USBD_MTP_OPT_DeleteObject
* Delete the object from the device
* @param pdev: device instance
* @retval None
*/
void USBD_MTP_OPT_DeleteObject(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
hmtp->GenericContainer.trans_id = hmtp->OperationsContainer.trans_id;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->ResponseCode = hmtpif->DeleteObject(hmtp->OperationsContainer.Param1);
}
/**
* @brief MTP_Get_PayloadContent
* Get the payload data of generic container
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_PayloadContent(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
uint8_t *buffer = hmtp->GenericContainer.data;
uint32_t i;
uint32_t n_idx;
switch (hmtp->OperationsContainer.code)
{
case MTP_OP_GET_DEVICE_INFO:
(void)MTP_Get_DeviceInfo();
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_DeviceInfo, sizeof(MTP_DeviceInfo));
for (i = 0U; i < sizeof(MTP_StorageIDS); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_STORAGE_IDS:
(void)MTP_Get_StorageIDS();
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_StorageIDS, sizeof(MTP_StorageIDS));
for (i = 0U; i < sizeof(MTP_StorageIDS); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_STORAGE_INFO:
(void)MTP_Get_StorageInfo(pdev);
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_StorageInfo, sizeof(MTP_StorageInfo));
for (i = 0U; i < sizeof(MTP_StorageInfo); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_OBJECT_HANDLES:
(void)MTP_Get_ObjectHandle(pdev);
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_ObjectHandle, hmtp->ResponseLength);
for (i = 0U; i < hmtp->ResponseLength; i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_OBJECT_INFO:
(void)MTP_Get_ObjectInfo(pdev);
break;
case MTP_OP_GET_OBJECT_PROPS_SUPPORTED:
(void)MTP_Get_ObjectPropSupp();
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_ObjectPropSupp, sizeof(MTP_ObjectPropSupp));
for (i = 0U; i < sizeof(MTP_ObjectPropSupp); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_OBJECT_PROP_DESC:
(void)MTP_Get_ObjectPropDesc(pdev);
hmtp->ResponseLength = MTP_build_data_propdesc(pdev, MTP_ObjectPropDesc);
break;
case MTP_OP_GET_OBJECT_PROP_REFERENCES:
MTP_Ref.ref_len = 0U;
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_Ref.ref_len, sizeof(MTP_Ref.ref_len));
for (i = 0U; i < sizeof(MTP_Ref.ref_len); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_OBJECT_PROPLIST:
(void)MTP_Get_ObjectPropList(pdev);
break;
case MTP_OP_GET_OBJECT_PROP_VALUE:
buffer = MTP_Get_ObjectPropValue(pdev);
for (i = 0U; i < hmtp->ResponseLength; i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_GET_DEVICE_PROP_DESC:
(void)MTP_Get_DevicePropDesc();
(void)USBD_memcpy(buffer, (const uint8_t *)&MTP_DevicePropDesc, sizeof(MTP_DevicePropDesc));
for (i = 0U; i < sizeof(MTP_DevicePropDesc); i++)
{
hmtp->GenericContainer.data[i] = buffer[i];
}
break;
case MTP_OP_SEND_OBJECT_INFO:
n_idx = hmtpif->GetNewIndex(obj_format);
(void)USBD_memcpy(hmtp->GenericContainer.data, (const uint8_t *)&storage_id, sizeof(uint32_t));
(void)USBD_memcpy(hmtp->GenericContainer.data + 4U, (const uint8_t *)&objhandle, sizeof(uint32_t));
(void)USBD_memcpy(hmtp->GenericContainer.data + 8U, (const uint8_t *)&n_idx, sizeof(uint32_t));
break;
case MTP_OP_GET_OBJECT:
break;
default:
break;
}
}
/**
* @brief MTP_Get_DeviceInfo
* Fill the MTP_DeviceInfo struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_DeviceInfo(void)
{
MTP_DeviceInfo.StandardVersion = STANDARD_VERSION;
MTP_DeviceInfo.VendorExtensionID = VEND_EXT_ID;
MTP_DeviceInfo.VendorExtensionVersion = VEND_EXT_VERSION;
MTP_DeviceInfo.VendorExtensionDesc_len = (uint8_t)VEND_EXT_DESC_LEN;
uint32_t i;
#if USBD_MTP_VEND_EXT_DESC_SUPPORTED == 1
for (i = 0U; i < VEND_EXT_DESC_LEN; i++)
{
MTP_DeviceInfo.VendorExtensionDesc[i] = VendExtDesc[i];
}
#endif /* USBD_MTP_VEND_EXT_DESC_SUPPORTED */
MTP_DeviceInfo.FunctionalMode = FUNCTIONAL_MODE; /* device supports one mode , standard mode */
/* All supported operation */
MTP_DeviceInfo.OperationsSupported_len = SUPP_OP_LEN;
for (i = 0U; i < SUPP_OP_LEN; i++)
{
MTP_DeviceInfo.OperationsSupported[i] = SuppOP[i];
}
MTP_DeviceInfo.EventsSupported_len = SUPP_EVENTS_LEN; /* event that are currently generated by the device*/
#if USBD_MTP_EVENTS_SUPPORTED == 1
for (i = 0U; i < SUPP_EVENTS_LEN; i++)
{
MTP_DeviceInfo.EventsSupported[i] = SuppEvents[i];
}
#endif /* USBD_MTP_EVENTS_SUPPORTED */
MTP_DeviceInfo.DevicePropertiesSupported_len = SUPP_DEVICE_PROP_LEN;
#if USBD_MTP_DEVICE_PROP_SUPPORTED == 1
for (i = 0U; i < SUPP_DEVICE_PROP_LEN; i++)
{
MTP_DeviceInfo.DevicePropertiesSupported[i] = DevicePropSupp[i];
}
#endif /* USBD_MTP_DEVICE_PROP_SUPPORTED */
MTP_DeviceInfo.CaptureFormats_len = SUPP_CAPT_FORMAT_LEN;
#if USBD_MTP_CAPTURE_FORMAT_SUPPORTED == 1
for (i = 0U; i < SUPP_CAPT_FORMAT_LEN; i++)
{
MTP_DeviceInfo.CaptureFormats[i] = SuppCaptFormat[i];
}
#endif /* USBD_MTP_CAPTURE_FORMAT_SUPPORTED */
MTP_DeviceInfo.ImageFormats_len = SUPP_IMG_FORMAT_LEN; /* number of image formats that are supported by the device*/
for (i = 0U; i < SUPP_IMG_FORMAT_LEN; i++)
{
MTP_DeviceInfo.ImageFormats[i] = SuppImgFormat[i];
}
MTP_DeviceInfo.Manufacturer_len = (uint8_t)MANUF_LEN;
for (i = 0U; i < MANUF_LEN; i++)
{
MTP_DeviceInfo.Manufacturer[i] = Manuf[i];
}
MTP_DeviceInfo.Model_len = (uint8_t)MODEL_LEN;
for (i = 0U; i < MODEL_LEN; i++)
{
MTP_DeviceInfo.Model[i] = Model[i];
}
MTP_DeviceInfo.DeviceVersion_len = (uint8_t)DEVICE_VERSION_LEN;
for (i = 0U; i < DEVICE_VERSION_LEN; i++)
{
MTP_DeviceInfo.DeviceVersion[i] = DeviceVers[i];
}
MTP_DeviceInfo.SerialNumber_len = (uint8_t)SERIAL_NBR_LEN;
for (i = 0U; i < SERIAL_NBR_LEN; i++)
{
MTP_DeviceInfo.SerialNumber[i] = SerialNbr[i];
}
}
/**
* @brief MTP_Get_StorageInfo
* Fill the MTP_StorageInfo struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_StorageInfo(USBD_HandleTypeDef *pdev)
{
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
MTP_StorageInfo.StorageType = MTP_STORAGE_REMOVABLE_RAM;
MTP_StorageInfo.FilesystemType = MTP_FILESYSTEM_GENERIC_FLAT;
MTP_StorageInfo.AccessCapability = MTP_ACCESS_CAP_RW;
MTP_StorageInfo.MaxCapability = hmtpif->GetMaxCapability();
MTP_StorageInfo.FreeSpaceInBytes = hmtpif->GetFreeSpaceInBytes();
MTP_StorageInfo.FreeSpaceInObjects = FREE_SPACE_IN_OBJ_NOT_USED; /* not used */
MTP_StorageInfo.StorageDescription = 0U;
MTP_StorageInfo.VolumeLabel = 0U;
}
/**
* @brief MTP_Get_ObjectHandle
* Fill the MTP_ObjectHandle struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_ObjectHandle(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
MTP_ObjectHandle.ObjectHandle_len = (uint32_t)(hmtpif->GetIdx(hmtp->OperationsContainer.Param3,
MTP_ObjectHandle.ObjectHandle));
hmtp->ResponseLength = (MTP_ObjectHandle.ObjectHandle_len * sizeof(uint32_t)) + sizeof(uint32_t);
}
/**
* @brief MTP_Get_ObjectPropSupp
* Fill the MTP_ObjectPropSupp struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_ObjectPropSupp(void)
{
uint32_t i;
MTP_ObjectPropSupp.ObjectPropSupp_len = SUPP_OBJ_PROP_LEN;
for (i = 0U; i < SUPP_OBJ_PROP_LEN; i++)
{
MTP_ObjectPropSupp.ObjectPropSupp[i] = ObjectPropSupp[i];
}
}
/**
* @brief MTP_Get_ObjectPropDesc
* Fill the MTP_ObjectPropDesc struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_ObjectPropDesc(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t undef_format = MTP_OBJ_FORMAT_UNDEFINED;
uint32_t storageid = MTP_STORAGE_ID;
switch (hmtp->OperationsContainer.Param1) /* switch obj prop code */
{
case MTP_OB_PROP_OBJECT_FORMAT :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_UINT16;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_ObjectPropDesc.DefValue = (uint8_t *)&undef_format;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_STORAGE_ID :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_UINT32;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_ObjectPropDesc.DefValue = (uint8_t *)&storageid;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_OBJ_FILE_NAME :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_STR;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_FileName.FileName_len = DEFAULT_FILE_NAME_LEN;
(void)USBD_memcpy((void *) & (MTP_FileName.FileName), (const void *)DefaultFileName, sizeof(DefaultFileName));
MTP_ObjectPropDesc.DefValue = (uint8_t *)&MTP_FileName;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_PARENT_OBJECT :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_STR;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_ObjectPropDesc.DefValue = 0U;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_OBJECT_SIZE :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_UINT64;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_ObjectPropDesc.DefValue = 0U;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_NAME :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_STR;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_FileName.FileName_len = DEFAULT_FILE_NAME_LEN;
(void)USBD_memcpy((void *) & (MTP_FileName.FileName),
(const void *)DefaultFileName, sizeof(DefaultFileName));
MTP_ObjectPropDesc.DefValue = (uint8_t *)&MTP_FileName;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_PERS_UNIQ_OBJ_IDEN :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_UINT128;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET;
MTP_ObjectPropDesc.DefValue = 0U;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
case MTP_OB_PROP_PROTECTION_STATUS :
MTP_ObjectPropDesc.ObjectPropertyCode = (uint16_t)(hmtp->OperationsContainer.Param1);
MTP_ObjectPropDesc.DataType = MTP_DATATYPE_UINT16;
MTP_ObjectPropDesc.GetSet = MTP_PROP_GET_SET;
MTP_ObjectPropDesc.DefValue = 0U;
MTP_ObjectPropDesc.GroupCode = 0U;
MTP_ObjectPropDesc.FormFlag = 0U;
break;
default:
break;
}
}
/**
* @brief MTP_Get_ObjectPropValue
* Get the property value
* @param pdev: device instance
* @retval None
*/
static uint8_t *MTP_Get_ObjectPropValue(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
static uint8_t buf[512];
/* Add all other supported object properties */
switch (hmtp->OperationsContainer.Param2)
{
case MTP_OB_PROP_STORAGE_ID:
MTP_PropertyValue.u32 = MTP_STORAGE_ID;
(void)USBD_memcpy(buf, (const uint8_t *)&MTP_PropertyValue, sizeof(uint32_t));
hmtp->ResponseLength = sizeof(uint32_t);
break;
case MTP_OB_PROP_OBJECT_FORMAT:
MTP_PropertyValue.u16 = hmtpif->GetObjectFormat(hmtp->OperationsContainer.Param1);
(void)USBD_memcpy(buf, (const uint8_t *)&MTP_PropertyValue, sizeof(uint16_t));
hmtp->ResponseLength = sizeof(uint16_t);
break;
case MTP_OB_PROP_OBJ_FILE_NAME:
MTP_FileName.FileName_len = hmtpif->GetObjectName_len(hmtp->OperationsContainer.Param1);
hmtpif->GetObjectName(hmtp->OperationsContainer.Param1, MTP_FileName.FileName_len, (uint16_t *)buf);
(void)USBD_memcpy(MTP_FileName.FileName, (uint16_t *)buf, ((uint32_t)MTP_FileName.FileName_len * 2U) + 1U);
hmtp->ResponseLength = ((uint32_t)MTP_FileName.FileName_len * 2U) + 1U;
break;
case MTP_OB_PROP_PARENT_OBJECT :
MTP_PropertyValue.u32 = hmtpif->GetParentObject(hmtp->OperationsContainer.Param1);
(void)USBD_memcpy(buf, (const uint8_t *)&MTP_PropertyValue, sizeof(uint32_t));
hmtp->ResponseLength = sizeof(uint32_t);
break;
case MTP_OB_PROP_OBJECT_SIZE :
MTP_PropertyValue.u64 = hmtpif->GetObjectSize(hmtp->OperationsContainer.Param1);
(void)USBD_memcpy(buf, (const uint8_t *)&MTP_PropertyValue, sizeof(uint64_t));
hmtp->ResponseLength = sizeof(uint64_t);
break;
default:
break;
}
return buf;
}
/**
* @brief MTP_Get_ObjectPropList
* Get the object property list data to be transmitted
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_ObjectPropList(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
uint16_t filename[255];
uint32_t storageid = MTP_STORAGE_ID;
uint32_t default_val = 0U;
uint32_t i;
uint16_t format;
uint64_t objsize;
uint32_t parent_proval;
MTP_PropertiesList.MTP_Properties_len = SUPP_OBJ_PROP_LEN;
hmtp->ResponseLength = 4U; /* size of MTP_PropertiesList.MTP_Properties_len */
(void)USBD_memcpy(hmtp->GenericContainer.data,
(const uint8_t *)&MTP_PropertiesList.MTP_Properties_len, hmtp->ResponseLength);
for (i = 0U; i < SUPP_OBJ_PROP_LEN; i++)
{
MTP_PropertiesList.MTP_Properties[i].ObjectHandle = hmtp->OperationsContainer.Param1;
switch (ObjectPropSupp[i])
{
case MTP_OB_PROP_STORAGE_ID :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_STORAGE_ID;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT32;
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&storageid;
break;
case MTP_OB_PROP_OBJECT_FORMAT :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_OBJECT_FORMAT;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT16;
format = hmtpif->GetObjectFormat(hmtp->OperationsContainer.Param1);
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&format;
break;
case MTP_OB_PROP_OBJ_FILE_NAME:
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_OBJ_FILE_NAME;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_STR;
/* MTP_FileName.FileName_len value shall be set before USBD_MTP_FS_GetObjectName */
MTP_FileName.FileName_len = hmtpif->GetObjectName_len(hmtp->OperationsContainer.Param1);
hmtpif->GetObjectName(hmtp->OperationsContainer.Param1, MTP_FileName.FileName_len, filename);
(void)USBD_memcpy(MTP_FileName.FileName, filename, ((uint32_t)MTP_FileName.FileName_len * 2U) + 1U);
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&MTP_FileName;
break;
case MTP_OB_PROP_PARENT_OBJECT :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_PARENT_OBJECT;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT32;
parent_proval = hmtpif->GetParentObject(hmtp->OperationsContainer.Param1);
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&parent_proval;
break;
case MTP_OB_PROP_OBJECT_SIZE :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_OBJECT_SIZE;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT64;
objsize = hmtpif->GetObjectSize(hmtp->OperationsContainer.Param1);
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&objsize;
break;
case MTP_OB_PROP_NAME :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_NAME;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_STR;
/* MTP_FileName.FileName_len value shall be set before USBD_MTP_FS_GetObjectName */
MTP_FileName.FileName_len = hmtpif->GetObjectName_len(hmtp->OperationsContainer.Param1);
hmtpif->GetObjectName(hmtp->OperationsContainer.Param1, MTP_FileName.FileName_len, filename);
(void)USBD_memcpy(MTP_FileName.FileName, filename, ((uint32_t)MTP_FileName.FileName_len * 2U) + 1U);
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&MTP_FileName;
break;
case MTP_OB_PROP_PERS_UNIQ_OBJ_IDEN :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_PERS_UNIQ_OBJ_IDEN;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT128;
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&hmtp->OperationsContainer.Param1;
break;
case MTP_OB_PROP_PROTECTION_STATUS :
MTP_PropertiesList.MTP_Properties[i].PropertyCode = MTP_OB_PROP_PROTECTION_STATUS;
MTP_PropertiesList.MTP_Properties[i].Datatype = MTP_DATATYPE_UINT16;
MTP_PropertiesList.MTP_Properties[i].propval = (uint8_t *)&default_val;
break;
default:
break;
}
hmtp->ResponseLength = MTP_build_data_proplist(pdev, MTP_PropertiesList, i);
}
}
/**
* @brief MTP_Get_DevicePropDesc
* Fill the MTP_DevicePropDesc struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_DevicePropDesc(void)
{
MTP_DevicePropDesc.DevicePropertyCode = MTP_DEV_PROP_DEVICE_FRIENDLY_NAME;
MTP_DevicePropDesc.DataType = MTP_DATATYPE_STR;
MTP_DevicePropDesc.GetSet = MTP_PROP_GET_SET;
MTP_DevicePropDesc.DefValue_len = DEVICE_PROP_DESC_DEF_LEN;
uint32_t i;
for (i = 0U; i < (sizeof(DevicePropDefVal) / 2U); i++)
{
MTP_DevicePropDesc.DefValue[i] = DevicePropDefVal[i];
}
MTP_DevicePropDesc.curDefValue_len = DEVICE_PROP_DESC_CUR_LEN;
for (i = 0U; i < (sizeof(DevicePropCurDefVal) / 2U); i++)
{
MTP_DevicePropDesc.curDefValue[i] = DevicePropCurDefVal[i];
}
MTP_DevicePropDesc.FormFlag = 0U;
}
/**
* @brief MTP_Get_ObjectInfo
* Fill the MTP_ObjectInfo struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_ObjectInfo(USBD_HandleTypeDef *pdev)
{
USBD_MTP_ItfTypeDef *hmtpif = (USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId];
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint16_t filename[255];
MTP_ObjectInfo.Storage_id = MTP_STORAGE_ID;
MTP_ObjectInfo.ObjectFormat = hmtpif->GetObjectFormat(hmtp->OperationsContainer.Param1);
MTP_ObjectInfo.ObjectCompressedSize = hmtpif->GetObjectSize(hmtp->OperationsContainer.Param1);
MTP_ObjectInfo.ProtectionStatus = 0U;
MTP_ObjectInfo.ThumbFormat = MTP_OBJ_FORMAT_UNDEFINED;
MTP_ObjectInfo.ThumbCompressedSize = 0U;
MTP_ObjectInfo.ThumbPixWidth = 0U; /* not supported or not an image */
MTP_ObjectInfo.ThumbPixHeight = 0U;
MTP_ObjectInfo.ImagePixWidth = 0U;
MTP_ObjectInfo.ImagePixHeight = 0U;
MTP_ObjectInfo.ImageBitDepth = 0U;
MTP_ObjectInfo.ParentObject = hmtpif->GetParentObject(hmtp->OperationsContainer.Param1);
MTP_ObjectInfo.AssociationType = 0U;
MTP_ObjectInfo.AssociationDesc = 0U;
MTP_ObjectInfo.SequenceNumber = 0U;
/* we have to get this value before MTP_ObjectInfo.Filename */
MTP_ObjectInfo.Filename_len = hmtpif->GetObjectName_len(hmtp->OperationsContainer.Param1);
hmtpif->GetObjectName(hmtp->OperationsContainer.Param1, MTP_ObjectInfo.Filename_len, filename);
(void)USBD_memcpy(MTP_ObjectInfo.Filename, filename, ((uint32_t)MTP_FileName.FileName_len * 2U) + 1U);
MTP_ObjectInfo.CaptureDate = 0U;
MTP_ObjectInfo.ModificationDate = 0U;
MTP_ObjectInfo.Keywords = 0U;
hmtp->ResponseLength = MTP_build_data_ObjInfo(pdev, MTP_ObjectInfo);
}
/**
* @brief MTP_Get_StorageIDS
* Fill the MTP_StorageIDS struct
* @param pdev: device instance
* @retval None
*/
static void MTP_Get_StorageIDS(void)
{
MTP_StorageIDS.StorageIDS_len = MTP_NBR_STORAGE_ID;
MTP_StorageIDS.StorageIDS[0] = MTP_STORAGE_ID;
}
/**
* @brief MTP_build_data_propdesc
* Copy the MTP_ObjectPropDesc dataset to the payload data
* @param pdev: device instance
* @retval None
*/
static uint32_t MTP_build_data_propdesc(USBD_HandleTypeDef *pdev, MTP_ObjectPropDescTypeDef def)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t DefValue_size = (MTP_FileName.FileName_len * 2U) + 1U;
uint32_t dataLength = offsetof(MTP_ObjectPropDescTypeDef, DefValue);
(void)USBD_memcpy(hmtp->GenericContainer.data, (const uint8_t *)&def, dataLength);
switch (def.DataType)
{
case MTP_DATATYPE_UINT16:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength, def.DefValue, sizeof(uint16_t));
dataLength += sizeof(uint16_t);
break;
case MTP_DATATYPE_UINT32:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength, def.DefValue, sizeof(uint32_t));
dataLength += sizeof(uint32_t);
break;
case MTP_DATATYPE_UINT64:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength, def.DefValue, sizeof(uint64_t));
dataLength += sizeof(uint64_t);
break;
case MTP_DATATYPE_STR:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength, def.DefValue, DefValue_size);
dataLength += DefValue_size;
break;
case MTP_DATATYPE_UINT128:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength, def.DefValue, (sizeof(uint64_t) * 2U));
dataLength += (sizeof(uint64_t) * 2U);
break;
default:
break;
}
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
(const uint8_t *)&MTP_ObjectPropDesc.GroupCode, sizeof(MTP_ObjectPropDesc.GroupCode));
dataLength += sizeof(MTP_ObjectPropDesc.GroupCode);
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
(const uint8_t *)&MTP_ObjectPropDesc.FormFlag, sizeof(MTP_ObjectPropDesc.FormFlag));
dataLength += sizeof(MTP_ObjectPropDesc.FormFlag);
return dataLength;
}
/**
* @brief MTP_build_data_proplist
* Copy the MTP_PropertiesList dataset to the payload data
* @param pdev: device instance
* @retval None
*/
static uint32_t MTP_build_data_proplist(USBD_HandleTypeDef *pdev,
MTP_PropertiesListTypedef proplist, uint32_t idx)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint8_t propval_size = (MTP_FileName.FileName_len * 2U) + 1U;
uint32_t dataLength;
dataLength = offsetof(MTP_PropertiesTypedef, propval);
(void)USBD_memcpy(hmtp->GenericContainer.data + hmtp->ResponseLength,
(const uint8_t *)&proplist.MTP_Properties[idx], dataLength);
dataLength += hmtp->ResponseLength;
switch (proplist.MTP_Properties[idx].Datatype)
{
case MTP_DATATYPE_UINT16:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
proplist.MTP_Properties[idx].propval, sizeof(uint16_t));
dataLength += sizeof(uint16_t);
break;
case MTP_DATATYPE_UINT32:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
proplist.MTP_Properties[idx].propval, sizeof(uint32_t));
dataLength += sizeof(uint32_t);
break;
case MTP_DATATYPE_STR:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
proplist.MTP_Properties[idx].propval, propval_size);
dataLength += propval_size;
break;
case MTP_DATATYPE_UINT64:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
proplist.MTP_Properties[idx].propval, sizeof(uint64_t));
dataLength += sizeof(uint64_t);
break;
case MTP_DATATYPE_UINT128:
(void)USBD_memcpy(hmtp->GenericContainer.data + dataLength,
proplist.MTP_Properties[idx].propval, (sizeof(uint64_t) * 2U));
dataLength += (sizeof(uint64_t) * 2U);
break;
default:
break;
}
return dataLength;
}
/**
* @brief MTP_build_data_ObjInfo
* Copy the MTP_ObjectInfo dataset to the payload data
* @param pdev: device instance
* @retval None
*/
static uint32_t MTP_build_data_ObjInfo(USBD_HandleTypeDef *pdev, MTP_ObjectInfoTypeDef objinfo)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t ObjInfo_len = offsetof(MTP_ObjectInfoTypeDef, Filename);
(void)USBD_memcpy(hmtp->GenericContainer.data, (const uint8_t *)&objinfo, ObjInfo_len);
(void)USBD_memcpy(hmtp->GenericContainer.data + ObjInfo_len,
(const uint8_t *)&objinfo.Filename, objinfo.Filename_len * sizeof(uint16_t));
ObjInfo_len = ObjInfo_len + (objinfo.Filename_len * sizeof(uint16_t));
(void)USBD_memcpy(hmtp->GenericContainer.data + ObjInfo_len,
(const uint8_t *)&objinfo.CaptureDate, sizeof(objinfo.CaptureDate));
ObjInfo_len = ObjInfo_len + sizeof(objinfo.CaptureDate);
return ObjInfo_len;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP | D://workCode//uploadProject\stm32_mw_usb_device\Class\MTP\Src\usbd_mtp_storage.c | /**
******************************************************************************
* @file usbd_mtp_storage.c
* @author MCD Application Team
* @brief This file provides all the transfer command functions for MTP
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_mtp_storage.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
extern uint8_t MTPInEpAdd;
extern uint8_t MTPOutEpAdd;
/* Private variables ---------------------------------------------------------*/
static MTP_DataLengthTypeDef MTP_DataLength;
static MTP_READ_DATA_STATUS ReadDataStatus;
/* Private function prototypes -----------------------------------------------*/
static uint8_t USBD_MTP_STORAGE_DecodeOperations(USBD_HandleTypeDef *pdev);
static uint8_t USBD_MTP_STORAGE_ReceiveContainer(USBD_HandleTypeDef *pdev, uint32_t *pDst, uint32_t len);
static uint8_t USBD_MTP_STORAGE_SendData(USBD_HandleTypeDef *pdev, uint8_t *buf, uint32_t len);
/* Private functions ---------------------------------------------------------*/
/**
* @}
*/
/**
* @brief USBD_MTP_STORAGE_Init
* Initialize the MTP USB Layer
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_Init(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Initialize the HW layyer of the file system */
(void)((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
/* Prepare EP to Receive First Operation */
(void)USBD_LL_PrepareReceive(pdev, MTPOutEpAdd, (uint8_t *)&hmtp->rx_buff,
hmtp->MaxPcktLen);
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_DeInit
* Uninitialize the MTP Machine
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_DeInit(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
/* DeInit physical Interface components */
hmtp->MTP_SessionState = MTP_SESSION_NOT_OPENED;
/* Stop low layer file system operations if any */
USBD_MTP_STORAGE_Cancel(pdev, MTP_PHASE_IDLE);
/* Free low layer file system resources */
(void)((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_ReadData
* Read data from device objects and send it to the host
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_ReadData(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t *data_buff;
/* Get the data buffer pointer from the low layer interface */
data_buff = ((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->ScratchBuff;
switch (ReadDataStatus)
{
case READ_FIRST_DATA:
/* Reset the data length */
MTP_DataLength.temp_length = 0U;
/* Perform the low layer read operation on the scratch buffer */
(void)((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->ReadData(hmtp->OperationsContainer.Param1,
(uint8_t *)data_buff, &MTP_DataLength);
/* Add the container header to the data buffer */
(void)USBD_memcpy((uint8_t *)data_buff, (uint8_t *)&hmtp->GenericContainer, MTP_CONT_HEADER_SIZE);
/* Start USB data transmission to the host */
(void)USBD_MTP_STORAGE_SendData(pdev, (uint8_t *)data_buff,
MTP_DataLength.readbytes + MTP_CONT_HEADER_SIZE);
/* Check if this will be the last packet to send ? */
if (MTP_DataLength.readbytes < ((uint32_t)hmtp->MaxPcktLen - MTP_CONT_HEADER_SIZE))
{
/* Move to response phase */
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
}
else
{
/* Continue to the next packets sending */
ReadDataStatus = READ_REST_OF_DATA;
}
break;
case READ_REST_OF_DATA:
/* Perform the low layer read operation on the scratch buffer */
(void)((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->ReadData(hmtp->OperationsContainer.Param1,
(uint8_t *)data_buff, &MTP_DataLength);
/* Check if more data need to be sent */
if (MTP_DataLength.temp_length == MTP_DataLength.totallen)
{
/* Start USB data transmission to the host */
(void)USBD_MTP_STORAGE_SendData(pdev, (uint8_t *)data_buff, MTP_DataLength.readbytes);
/* Move to response phase */
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
/* Reset the stat machine */
ReadDataStatus = READ_FIRST_DATA;
}
else
{
/* Start USB data transmission to the host */
(void)USBD_MTP_STORAGE_SendData(pdev, (uint8_t *)data_buff, MTP_DataLength.readbytes);
/* Keep the state machine into sending next packet of data */
ReadDataStatus = READ_REST_OF_DATA;
}
break;
default:
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_SendContainer
* Send generic container to the host
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_SendContainer(USBD_HandleTypeDef *pdev, MTP_CONTAINER_TYPE CONT_TYPE)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
switch (CONT_TYPE)
{
case DATA_TYPE:
/* send header + data : hmtp->ResponseLength = header size + data size */
(void)USBD_MTP_STORAGE_SendData(pdev, (uint8_t *)&hmtp->GenericContainer, hmtp->ResponseLength);
break;
case REP_TYPE:
/* send header without data */
hmtp->GenericContainer.code = (uint16_t)hmtp->ResponseCode;
hmtp->ResponseLength = MTP_CONT_HEADER_SIZE;
hmtp->GenericContainer.length = hmtp->ResponseLength;
hmtp->GenericContainer.type = MTP_CONT_TYPE_RESPONSE;
(void)USBD_MTP_STORAGE_SendData(pdev, (uint8_t *)&hmtp->GenericContainer, hmtp->ResponseLength);
break;
default:
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_ReceiveOpt
* Data length Packet Received from host
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_ReceiveOpt(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t *pMsgBuffer;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MTPOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
MTP_DataLength.rx_length = USBD_GetRxCount(pdev, MTPOutEpAdd);
switch (hmtp->RECEIVE_DATA_STATUS)
{
case RECEIVE_REST_OF_DATA:
/* we don't need to do anything here because we receive only data without operation header*/
break;
case RECEIVE_FIRST_DATA:
/* Expected Data Length Packet Received */
pMsgBuffer = (uint32_t *) &hmtp->OperationsContainer;
/* Fill hmtp->OperationsContainer Data Buffer from USB Buffer */
(void)USBD_MTP_STORAGE_ReceiveContainer(pdev, pMsgBuffer, MTP_DataLength.rx_length);
break;
default:
/* Expected Data Length Packet Received */
pMsgBuffer = (uint32_t *) &hmtp->OperationsContainer;
/* Fill hmtp->OperationsContainer Data Buffer from USB Buffer */
(void)USBD_MTP_STORAGE_ReceiveContainer(pdev, pMsgBuffer, MTP_DataLength.rx_length);
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_ReceiveData
* Receive objects or object info from host
* @param pdev: device instance
* @retval status value
*/
uint8_t USBD_MTP_STORAGE_ReceiveData(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
switch (hmtp->RECEIVE_DATA_STATUS)
{
case RECEIVE_COMMAND_DATA :
if (hmtp->OperationsContainer.type == MTP_CONT_TYPE_COMMAND)
{
MTP_DataLength.temp_length = 0;
MTP_DataLength.prv_len = 0;
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
}
break;
case RECEIVE_FIRST_DATA :
if (hmtp->OperationsContainer.type == MTP_CONT_TYPE_DATA)
{
MTP_DataLength.totallen = hmtp->OperationsContainer.length;
MTP_DataLength.temp_length = MTP_DataLength.rx_length;
MTP_DataLength.rx_length = MTP_DataLength.temp_length - MTP_CONT_HEADER_SIZE;
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
if (MTP_DataLength.temp_length < hmtp->MaxPcktLen) /* we received all data, we don't need to go to next state */
{
hmtp->RECEIVE_DATA_STATUS = SEND_RESPONSE;
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
/* send response header after receiving all data successfully */
(void)USBD_MTP_STORAGE_SendContainer(pdev, DATA_TYPE);
}
}
break;
case RECEIVE_REST_OF_DATA :
MTP_DataLength.prv_len = MTP_DataLength.temp_length - MTP_CONT_HEADER_SIZE;
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
MTP_DataLength.temp_length = MTP_DataLength.temp_length + MTP_DataLength.rx_length;
if (MTP_DataLength.temp_length == MTP_DataLength.totallen) /* we received all data*/
{
hmtp->RECEIVE_DATA_STATUS = SEND_RESPONSE;
(void)USBD_MTP_STORAGE_DecodeOperations(pdev);
/* send response header after receiving all data successfully */
(void)USBD_MTP_STORAGE_SendContainer(pdev, DATA_TYPE);
}
break;
default :
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_DecodeOperations
* Parse the operations and Process operations
* @param pdev: device instance
* @retval status value
*/
static uint8_t USBD_MTP_STORAGE_DecodeOperations(USBD_HandleTypeDef *pdev)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
switch (hmtp->OperationsContainer.code)
{
case MTP_OP_GET_DEVICE_INFO:
USBD_MTP_OPT_GetDeviceInfo(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_OPEN_SESSION:
USBD_MTP_OPT_CreateObjectHandle(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_STORAGE_IDS:
USBD_MTP_OPT_GetStorageIDS(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_STORAGE_INFO:
USBD_MTP_OPT_GetStorageInfo(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_HANDLES:
USBD_MTP_OPT_GetObjectHandle(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_INFO:
USBD_MTP_OPT_GetObjectInfo(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_PROP_REFERENCES:
USBD_MTP_OPT_GetObjectReferences(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_PROPS_SUPPORTED:
USBD_MTP_OPT_GetObjectPropSupp(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_PROP_DESC:
USBD_MTP_OPT_GetObjectPropDesc(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_PROPLIST:
USBD_MTP_OPT_GetObjectPropList(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT_PROP_VALUE:
USBD_MTP_OPT_GetObjectPropValue(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_DEVICE_PROP_DESC:
USBD_MTP_OPT_GetDevicePropDesc(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
case MTP_OP_GET_OBJECT:
USBD_MTP_OPT_GetObject(pdev);
hmtp->MTP_ResponsePhase = MTP_READ_DATA;
break;
case MTP_OP_SEND_OBJECT_INFO:
USBD_MTP_OPT_SendObjectInfo(pdev, (uint8_t *)(hmtp->rx_buff), MTP_DataLength.prv_len);
hmtp->MTP_ResponsePhase = MTP_RECEIVE_DATA;
break;
case MTP_OP_SEND_OBJECT:
USBD_MTP_OPT_SendObject(pdev, (uint8_t *)(hmtp->rx_buff), MTP_DataLength.rx_length);
hmtp->MTP_ResponsePhase = MTP_RECEIVE_DATA;
break;
case MTP_OP_DELETE_OBJECT:
USBD_MTP_OPT_DeleteObject(pdev);
hmtp->MTP_ResponsePhase = MTP_RESPONSE_PHASE;
break;
default:
break;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_ReceiveContainer
* Receive the Data from USB BulkOut Buffer to Pointer
* @param pdev: device instance
* @param pDst: destination address to copy the buffer
* @param len: length of data to copy
* @retval status value
*/
static uint8_t USBD_MTP_STORAGE_ReceiveContainer(USBD_HandleTypeDef *pdev,
uint32_t *pDst, uint32_t len)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t Counter;
uint32_t *pdst = pDst;
for (Counter = 0; Counter < len; Counter++)
{
*pdst = (hmtp->rx_buff[Counter]);
pdst++;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_MTP_STORAGE_Cancel
* Reinitialize all states and cancel transfer through Bulk transfer
* @param pdev: device instance
* @param MTP_ResponsePhase: MTP current state
* @retval None
*/
void USBD_MTP_STORAGE_Cancel(USBD_HandleTypeDef *pdev,
MTP_ResponsePhaseTypeDef MTP_ResponsePhase)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
hmtp->MTP_ResponsePhase = MTP_PHASE_IDLE;
ReadDataStatus = READ_FIRST_DATA;
hmtp->RECEIVE_DATA_STATUS = RECEIVE_IDLE_STATE;
if (MTP_ResponsePhase == MTP_RECEIVE_DATA)
{
((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->Cancel(1U);
}
else
{
((USBD_MTP_ItfTypeDef *)pdev->pUserData[pdev->classId])->Cancel(0U);
}
}
/**
* @brief USBD_MTP_STORAGE_SendData
* Send the data on bulk-in EP
* @param pdev: device instance
* @param buf: pointer to data buffer
* @param len: Data Length
* @retval status value
*/
static uint8_t USBD_MTP_STORAGE_SendData(USBD_HandleTypeDef *pdev, uint8_t *buf,
uint32_t len)
{
USBD_MTP_HandleTypeDef *hmtp = (USBD_MTP_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
uint32_t length = MIN(hmtp->GenericContainer.length, len);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
MTPInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
(void)USBD_LL_Transmit(pdev, MTPInEpAdd, buf, length);
return (uint8_t)USBD_OK;
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer | D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer\Inc\usbd_printer.h | /**
******************************************************************************
* @file usbd_printer.h
* @author MCD Application Team
* @brief header file for the usbd_printer.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_PRNT_H
#define __USB_PRNT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup usbd_PRNT
* @brief This file is the Header file for usbd_PRNT.c
* @{
*/
/** @defgroup usbd_PRNT_Exported_Defines
* @{
*/
#ifndef PRNT_IN_EP
#define PRNT_IN_EP 0x81U /* Default: EP1 for data IN */
#endif /* PRNT_IN_EP */
#ifndef PRNT_OUT_EP
#define PRNT_OUT_EP 0x01U /* Default: EP1 for data OUT */
#endif /* PRNT_OUT_EP */
#ifndef PRNT_DATA_HS_MAX_PACKET_SIZE
#define PRNT_DATA_HS_MAX_PACKET_SIZE 512U /* Endpoint IN & OUT Packet size */
#endif /* PRNT_DATA_HS_MAX_PACKET_SIZE */
#ifndef PRNT_DATA_FS_MAX_PACKET_SIZE
#define PRNT_DATA_FS_MAX_PACKET_SIZE 64U /* Endpoint IN & OUT Packet size */
#endif /* PRNT_DATA_FS_MAX_PACKET_SIZE */
#define USB_PRNT_CONFIG_DESC_SIZ 32U
#define PRNT_DATA_HS_IN_PACKET_SIZE PRNT_DATA_HS_MAX_PACKET_SIZE
#define PRNT_DATA_HS_OUT_PACKET_SIZE PRNT_DATA_HS_MAX_PACKET_SIZE
#define PRNT_DATA_FS_IN_PACKET_SIZE PRNT_DATA_FS_MAX_PACKET_SIZE
#define PRNT_DATA_FS_OUT_PACKET_SIZE PRNT_DATA_FS_MAX_PACKET_SIZE
/*---------------------------------------------------------------------*/
/* PRNT definitions */
/*---------------------------------------------------------------------*/
#define PRNT_STATUS_PAPER_EMPTY 0x10U
#define PRNT_STATUS_SELECTED 0x08U
#define PRNT_STATUS_NO_ERROR 0x00U
#define USB_PRNT_SUBCLASS 0x01U
#define USB_PRNT_UNIDIRECTIONAL 0x01U
#define USB_PRNT_BIDIRECTIONAL 0x02U
/* USB PRNT Request types */
#define PRNT_GET_DEVICE_ID 0x00U
#define PRNT_GET_PORT_STATUS 0x01U
#define PRNT_SOFT_RESET 0x02U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
typedef struct _USBD_PRNT_Itf
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control_req)(uint8_t req, uint8_t *pbuf, uint16_t *length);
int8_t (* Receive)(uint8_t *Buf, uint32_t *Len);
} USBD_PRNT_ItfTypeDef;
typedef struct
{
uint32_t data[PRNT_DATA_HS_MAX_PACKET_SIZE / 4U]; /* Force 32-bit alignment */
uint8_t CmdOpCode;
uint8_t CmdLength;
uint8_t *RxBuffer;
uint8_t *TxBuffer;
uint32_t RxLength;
uint32_t TxLength;
__IO uint32_t TxState;
__IO uint32_t RxState;
} USBD_PRNT_HandleTypeDef;
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_PRNT;
#define USBD_PRNT_CLASS &USBD_PRNT
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_PRNT_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_PRNT_ItfTypeDef *fops);
uint8_t USBD_PRNT_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff);
uint8_t USBD_PRNT_ReceivePacket(USBD_HandleTypeDef *pdev);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_PRNT_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer | D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer\Inc\usbd_printer_if_template.h | /**
******************************************************************************
* @file usbd_printer_if_template.h
* @author MCD Application Team
* @brief Header for usbd_PRNT_if_template.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_PRNT_IF_TEMPLATE_H
#define __USBD_PRNT_IF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_printer.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
extern USBD_PRNT_ItfTypeDef USBD_PRNT_Template_fops;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#ifdef __cplusplus
}
#endif
#endif /* __USBD_PRNT_IF_TEMPLATE_H */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer | D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer\Src\usbd_printer.c | /**
******************************************************************************
* @file usbd_printer.c
* @author MCD Application Team
* @brief This file provides the high layer firmware functions to manage the
* following functionalities of the USB printer Class:
* - Initialization and Configuration of high and low layer
* - Enumeration as printer Device (and enumeration for each implemented memory interface)
* - OUT data transfer
* - Command OUT transfer (class requests management)
* - Error management
*
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
* @verbatim
*
* ===================================================================
* PRINTER Class Driver Description
* ===================================================================
* This driver manages the "Universal Serial Bus Class Definitions for Communications Devices
* Revision 1.2 November 16, 2007" and the sub-protocol specification of "Universal Serial Bus
* printer Class Subclass Specification for PSTN Devices Revision 1.2 February 9, 2007"
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Enumeration as printer device with 2 data endpoints (IN and OUT)
* - Control Requests management (PRNT_GET_DEVICE_ID,PRNT_GET_PORT_STATUS,PRNT_SOFT_RESET)
* - protocol USB_PRNT_BIDIRECTIONAL
*
*
*
* These aspects may be enriched or modified for a specific user application.
*
* This driver doesn't implement the following aspects of the specification
* (but it is possible to manage these features with some modifications on this driver):
* - Any class-specific aspect relative to communication classes should be managed by user application.
* - All communication classes other than PSTN are not managed
*
* @endverbatim
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_printer.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_PRNT
* @brief usbd core module
* @{
*/
/** @defgroup USBD_PRNT_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
static uint32_t usbd_PRNT_altset = 0U;
/** @defgroup USBD_PRNT_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_PRNT_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_PRNT_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_PRNT_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_PRNT_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_PRNT_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_PRNT_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_PRNT_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_PRNT_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_PRNT_GetOtherSpeedCfgDesc(uint16_t *length);
uint8_t *USBD_PRNT_GetDeviceQualifierDescriptor(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_Variables
* @{
*/
/* PRNT interface class callbacks structure */
USBD_ClassTypeDef USBD_PRNT =
{
USBD_PRNT_Init,
USBD_PRNT_DeInit,
USBD_PRNT_Setup,
NULL,
NULL,
USBD_PRNT_DataIn,
USBD_PRNT_DataOut,
NULL,
NULL,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_PRNT_GetHSCfgDesc,
USBD_PRNT_GetFSCfgDesc,
USBD_PRNT_GetOtherSpeedCfgDesc,
USBD_PRNT_GetDeviceQualifierDescriptor,
#endif /* USE_USBD_COMPOSITE */
};
#ifndef USE_USBD_COMPOSITE
/* USB PRNT device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_PRNT_CfgDesc[] __ALIGN_END =
{
/*Configuration Descriptor*/
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_PRNT_CONFIG_DESC_SIZ, /* wTotalLength:no of returned bytes */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Self Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* MaxPower in mA */
/*Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: Interface */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x02, /* bNumEndpoints: 2 endpoints used */
0x07, /* bInterfaceClass: Communication Interface Class */
0x01, /* bInterfaceSubClass: Abstract Control Model */
USB_PRNT_BIDIRECTIONAL, /* bDeviceProtocol */
0x00, /* iInterface */
/*Endpoint IN Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
PRNT_IN_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(PRNT_DATA_FS_IN_PACKET_SIZE), /* wMaxPacketSize */
HIBYTE(PRNT_DATA_FS_IN_PACKET_SIZE),
0x00, /* bInterval */
/*Endpoint OUT Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: Endpoint */
PRNT_OUT_EP, /* bEndpointAddress */
0x02, /* bmAttributes: Bulk */
LOBYTE(PRNT_DATA_FS_OUT_PACKET_SIZE),/* wMaxPacketSize */
HIBYTE(PRNT_DATA_FS_OUT_PACKET_SIZE),
0x00 /* bInterval */
};
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_PRNT_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t PRNTInEpAdd = PRNT_IN_EP;
static uint8_t PRNTOutEpAdd = PRNT_OUT_EP;
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_Functions
* @{
*/
/**
* @brief USBD_PRNT_Init
* Initialize the PRNT interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_PRNT_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
USBD_PRNT_HandleTypeDef *hPRNT;
uint16_t mps;
hPRNT = (USBD_PRNT_HandleTypeDef *)USBD_malloc(sizeof(USBD_PRNT_HandleTypeDef));
if (hPRNT == NULL)
{
pdev->pClassDataCmsit[pdev->classId] = NULL;
return (uint8_t)USBD_EMEM;
}
(void)USBD_memset(hPRNT, 0, sizeof(USBD_PRNT_HandleTypeDef));
/* Setup the pClassData pointer */
pdev->pClassDataCmsit[pdev->classId] = (void *)hPRNT;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
PRNTInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
PRNTOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Setup the max packet size according to selected speed */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
mps = PRNT_DATA_HS_IN_PACKET_SIZE;
}
else
{
mps = PRNT_DATA_FS_IN_PACKET_SIZE;
}
/* Open EP IN */
(void)USBD_LL_OpenEP(pdev, PRNTInEpAdd, USBD_EP_TYPE_BULK, mps);
/* Set endpoint as used */
pdev->ep_in[PRNTInEpAdd & 0xFU].is_used = 1U;
/* Open EP OUT */
(void)USBD_LL_OpenEP(pdev, PRNTOutEpAdd, USBD_EP_TYPE_BULK, mps);
/* Set endpoint as used */
pdev->ep_out[PRNTOutEpAdd & 0xFU].is_used = 1U;
hPRNT->RxBuffer = NULL;
/* Init physical Interface components */
((USBD_PRNT_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
if (hPRNT->RxBuffer == NULL)
{
return (uint8_t)USBD_EMEM;
}
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, PRNTOutEpAdd, hPRNT->RxBuffer, mps);
/* End of initialization phase */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_PRNT_DeInit
* DeInitialize the PRNT layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_PRNT_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
PRNTInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
PRNTOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, PRNTInEpAdd);
pdev->ep_in[PRNTInEpAdd & 0xFU].is_used = 0U;
/* Close EP OUT */
(void)USBD_LL_CloseEP(pdev, PRNTOutEpAdd);
pdev->ep_out[PRNTOutEpAdd & 0xFU].is_used = 0U;
/* DeInit physical Interface components */
if (pdev->pClassDataCmsit[pdev->classId] != NULL)
{
((USBD_PRNT_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
(void)USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
}
return 0U;
}
/**
* @brief USBD_PRNT_Setup
* Handle the PRNT specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_PRNT_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_PRNT_HandleTypeDef *hPRNT = (USBD_PRNT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
USBD_PRNT_ItfTypeDef *hPRNTitf = (USBD_PRNT_ItfTypeDef *)pdev->pUserData[pdev->classId];
USBD_StatusTypeDef ret = USBD_OK;
uint16_t status_info = 0U;
uint16_t data_length;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS :
if (req->wLength != 0U)
{
data_length = MIN(req->wLength, PRNT_DATA_HS_MAX_PACKET_SIZE);
if ((req->bmRequest & 0x80U) != 0U)
{
/* Call the User class interface function to process the command */
hPRNTitf->Control_req(req->bRequest, (uint8_t *)hPRNT->data, &data_length);
/* Return the answer to host */
(void) USBD_CtlSendData(pdev, (uint8_t *)hPRNT->data, data_length);
}
else
{
/* Prepare for control data reception */
(void) USBD_CtlPrepareRx(pdev, (uint8_t *)hPRNT->data, data_length);
}
}
else
{
data_length = 0U;
hPRNTitf->Control_req(req->bRequest, (uint8_t *)req, &data_length);
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_GET_INTERFACE:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&usbd_PRNT_altset, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE:
if (pdev->dev_state != USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_PRNT_DataIn
* Data sent on non-control IN endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_PRNT_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_PRNT_HandleTypeDef *hPRNT = (USBD_PRNT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
PCD_HandleTypeDef *hpcd = pdev->pData;
if (hPRNT == NULL)
{
return (uint8_t)USBD_FAIL;
}
if ((pdev->ep_in[epnum & 0xFU].total_length > 0U) &&
((pdev->ep_in[epnum & 0xFU].total_length % hpcd->IN_ep[epnum & 0xFU].maxpacket) == 0U))
{
/* Update the packet total length */
pdev->ep_in[epnum & 0xFU].total_length = 0U;
/* Send ZLP */
(void) USBD_LL_Transmit(pdev, epnum, NULL, 0U);
}
else
{
hPRNT->TxState = 0U;
}
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_PRNT_DataOut
* Data received on non-control Out endpoint
* @param pdev: device instance
* @param epnum: endpoint number
* @retval status
*/
static uint8_t USBD_PRNT_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_PRNT_HandleTypeDef *hPRNT = (USBD_PRNT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
if (hPRNT == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Get the received data length */
hPRNT->RxLength = USBD_LL_GetRxDataSize(pdev, epnum);
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the application Xfer */
((USBD_PRNT_ItfTypeDef *)pdev->pUserData[pdev->classId])->Receive(hPRNT->RxBuffer, &hPRNT->RxLength);
return (uint8_t)USBD_OK;
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_PRNT_GetFSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_PRNT_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_OUT_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = PRNT_DATA_FS_IN_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = PRNT_DATA_FS_OUT_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_PRNT_CfgDesc);
return USBD_PRNT_CfgDesc;
}
/**
* @brief USBD_PRNT_GetHSCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_PRNT_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_OUT_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = PRNT_DATA_HS_IN_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = PRNT_DATA_HS_OUT_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_PRNT_CfgDesc);
return USBD_PRNT_CfgDesc;
}
/**
* @brief USBD_PRNT_GetOtherSpeedCfgDesc
* Return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_PRNT_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpInDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_IN_EP);
USBD_EpDescTypeDef *pEpOutDesc = USBD_GetEpDesc(USBD_PRNT_CfgDesc, PRNT_OUT_EP);
if (pEpInDesc != NULL)
{
pEpInDesc->wMaxPacketSize = PRNT_DATA_FS_IN_PACKET_SIZE;
}
if (pEpOutDesc != NULL)
{
pEpOutDesc->wMaxPacketSize = PRNT_DATA_FS_OUT_PACKET_SIZE;
}
*length = (uint16_t) sizeof(USBD_PRNT_CfgDesc);
return USBD_PRNT_CfgDesc;
}
/**
* @brief USBD_PRNT_GetDeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_PRNT_GetDeviceQualifierDescriptor(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_PRNT_DeviceQualifierDesc);
return USBD_PRNT_DeviceQualifierDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_PRNT_RegisterInterface
* @param pdev: device instance
* @param fops: Interface callbacks
* @retval status
*/
uint8_t USBD_PRNT_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_PRNT_ItfTypeDef *fops)
{
/* Check if the fops pointer is valid */
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Setup the fops pointer */
pdev->pUserData[pdev->classId] = fops;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_PRNT_SetRxBuffer
* @param pdev: device instance
* @param pbuff: Rx Buffer
* @retval status
*/
uint8_t USBD_PRNT_SetRxBuffer(USBD_HandleTypeDef *pdev, uint8_t *pbuff)
{
USBD_PRNT_HandleTypeDef *hPRNT = (USBD_PRNT_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
hPRNT->RxBuffer = pbuff;
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_PRNT_ReceivePacket
* prepare OUT Endpoint for reception
* @param pdev: device instance
* @retval status
*/
uint8_t USBD_PRNT_ReceivePacket(USBD_HandleTypeDef *pdev)
{
USBD_PRNT_HandleTypeDef *hPRNT = (USBD_PRNT_HandleTypeDef *)pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
PRNTInEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
PRNTOutEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_OUT, USBD_EP_TYPE_BULK, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (hPRNT == NULL)
{
return (uint8_t)USBD_FAIL;
}
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, PRNTOutEpAdd, hPRNT->RxBuffer,
PRNT_DATA_HS_OUT_PACKET_SIZE);
}
else
{
/* Prepare Out endpoint to receive next packet */
(void)USBD_LL_PrepareReceive(pdev, PRNTOutEpAdd, hPRNT->RxBuffer,
PRNT_DATA_FS_OUT_PACKET_SIZE);
}
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer | D://workCode//uploadProject\stm32_mw_usb_device\Class\Printer\Src\usbd_printer_if_template.c | /**
******************************************************************************
* @file usbd_printer_if_template.c
* @author MCD Application Team
* @brief Generic media access Layer.
******************************************************************************
* @attention
*
* Copyright (c) 2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_printer_if_template.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_PRNT
* @brief usbd core module
* @{
*/
/** @defgroup USBD_PRNT_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_PRNT_Private_FunctionPrototypes
* @{
*/
static int8_t TEMPLATE_Init(void);
static int8_t TEMPLATE_DeInit(void);
static int8_t TEMPLATE_Control_req(uint8_t req, uint8_t *pbuf, uint16_t *length);
static int8_t TEMPLATE_Receive(uint8_t *pbuf, uint32_t *Len);
/*printer Private function prototypes*/
void TEMPLATE_PRNT_PageEndManager(uint8_t *Buf, uint32_t Len);
USBD_PRNT_ItfTypeDef USBD_PRNT_Template_fops =
{
TEMPLATE_Init,
TEMPLATE_DeInit,
TEMPLATE_Control_req,
TEMPLATE_Receive
};
static uint8_t PRNT_DEVICE_ID[] =
{
0x00, 0x6D,
'M', 'A', 'N', 'U', 'F', 'A', 'C', 'T', 'U', 'R', 'E', 'R', ':',
'S', 'T', 'M', 'i', 'c', 'r', 'o', 'e', 'l', 'e', 'c', 't', 'r', 'o', 'n', 'i', 'c', 's', ';',
'C', 'O', 'M', 'M', 'A', 'N', 'D', ' ', 'S', 'E', 'T', ':',
'P', 'D', 'L', ',', 'P', 'C', 'P', ';',
'M', 'O', 'D', 'E', 'L', ':',
'U', 'S', 'B', 'P', 'r', 'i', 'n', 't', 'e', 'r', ';',
'C', 'O', 'M', 'M', 'E', 'N', 'T', ':',
'G', 'o', 'o', 'd', ' ', '!', ';',
'A', 'C', 'T', 'I', 'V', 'E', ' ', 'C', 'O', 'M', 'M', 'A', 'N', 'D', ' ', 'S', 'E', 'T', ':',
'P', 'C', 'P', ';'
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief TEMPLATE_Init
* Initializes the PRNT media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Init(void)
{
/*
Add your initialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_DeInit
* DeInitializes the PRNT media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_DeInit(void)
{
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_Receive
* Data received over USB OUT endpoint are sent over PRNT interface
* through this function.
*
* @note
* This function will issue a NAK packet on any OUT packet received on
* USB endpoint until exiting this function. If you exit this function
* before transfer is complete on PRNT interface (ie. using DMA controller)
* it will result in receiving more data while previous ones are still
* not sent.
*
* @param Buf: Buffer of data to be received
* @param Len: Number of data received (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Receive(uint8_t *Buf, uint32_t *Len)
{
UNUSED(Buf);
UNUSED(Len);
return (0);
}
/**
* @brief TEMPLATE_Control_req
* Manage the PRNT class requests
* @param req: Command code
* @param pbuf: Buffer containing command data (request parameters)
* @param length: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_Control_req(uint8_t req, uint8_t *pbuf, uint16_t *length)
{
uint32_t i = 0U;
/* Check on the setup request value */
switch (req)
{
/* Get Printer Device ID request */
case PRNT_GET_DEVICE_ID:
/* Not using for loop here due to MISRA-C2012-Rule-16.1 */
while (i < sizeof(PRNT_DEVICE_ID))
{
pbuf[i] = PRNT_DEVICE_ID[i];
i++;
}
*length = (uint16_t)i;
break;
/* Get Printer current status */
case PRNT_GET_PORT_STATUS:
pbuf[0] = PRNT_STATUS_PAPER_EMPTY |
PRNT_STATUS_SELECTED |
PRNT_STATUS_NO_ERROR;
*length = 1U;
break;
/* Printer SOFT RESET request: cleanup pending tasks */
case PRNT_SOFT_RESET:
break;
default:
/* Unknown commands are not managed */
break;
}
return (0);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Template | D://workCode//uploadProject\stm32_mw_usb_device\Class\Template\Inc\usbd_template.h | /**
******************************************************************************
* @file usbd_template_core.h
* @author MCD Application Team
* @brief Header file for the usbd_template_core.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_TEMPLATE_CORE_H
#define __USB_TEMPLATE_CORE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_TEMPLATE
* @brief This file is the header file for usbd_template_core.c
* @{
*/
/** @defgroup USBD_TEMPLATE_Exported_Defines
* @{
*/
#define TEMPLATE_EPIN_ADDR 0x81U
#define TEMPLATE_EPIN_SIZE 0x10U
#define USB_TEMPLATE_CONFIG_DESC_SIZ 64U
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_TEMPLATE_ClassDriver;
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_TEMPLATE_CORE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\Template | D://workCode//uploadProject\stm32_mw_usb_device\Class\Template\Src\usbd_template.c | /**
******************************************************************************
* @file usbd_template.c
* @author MCD Application Team
* @brief This file provides the HID core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* TEMPLATE Class Description
* ===================================================================
*
*
*
*
*
*
* @note In HS mode and when the DMA is used, all variables and data structures
* dealing with the DMA during the transaction process should be 32-bit aligned.
*
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_template.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_TEMPLATE
* @brief usbd core module
* @{
*/
/** @defgroup USBD_TEMPLATE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_TEMPLATE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_TEMPLATE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_TEMPLATE_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_TEMPLATE_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_TEMPLATE_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_TEMPLATE_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_TEMPLATE_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_TEMPLATE_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_TEMPLATE_EP0_RxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_TEMPLATE_EP0_TxReady(USBD_HandleTypeDef *pdev);
static uint8_t USBD_TEMPLATE_SOF(USBD_HandleTypeDef *pdev);
static uint8_t USBD_TEMPLATE_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_TEMPLATE_IsoOutIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t *USBD_TEMPLATE_GetCfgDesc(uint16_t *length);
static uint8_t *USBD_TEMPLATE_GetDeviceQualifierDesc(uint16_t *length);
/**
* @}
*/
/** @defgroup USBD_TEMPLATE_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_TEMPLATE_ClassDriver =
{
USBD_TEMPLATE_Init,
USBD_TEMPLATE_DeInit,
USBD_TEMPLATE_Setup,
USBD_TEMPLATE_EP0_TxReady,
USBD_TEMPLATE_EP0_RxReady,
USBD_TEMPLATE_DataIn,
USBD_TEMPLATE_DataOut,
USBD_TEMPLATE_SOF,
USBD_TEMPLATE_IsoINIncomplete,
USBD_TEMPLATE_IsoOutIncomplete,
USBD_TEMPLATE_GetCfgDesc,
USBD_TEMPLATE_GetCfgDesc,
USBD_TEMPLATE_GetCfgDesc,
USBD_TEMPLATE_GetDeviceQualifierDesc,
};
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
/* USB TEMPLATE device Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_TEMPLATE_CfgDesc[USB_TEMPLATE_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION, /* bDescriptorType: Configuration */
USB_TEMPLATE_CONFIG_DESC_SIZ,
/* wTotalLength: Bytes returned */
0x00,
0x01, /*bNumInterfaces: 1 interface*/
0x01, /*bConfigurationValue: Configuration value*/
0x02, /*iConfiguration: Index of string descriptor describing the configuration*/
0xC0, /*bmAttributes: bus powered and Supports Remote Wakeup */
0x32, /*MaxPower 100 mA: this current is used for detecting Vbus*/
/* 09 */
/********** Descriptor of TEMPLATE interface 0 Alternate setting 0 **************/
};
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_TEMPLATE_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0x00,
0x00,
0x00,
0x40,
0x01,
0x00,
};
/**
* @}
*/
/** @defgroup USBD_TEMPLATE_Private_Functions
* @{
*/
/**
* @brief USBD_TEMPLATE_Init
* Initialize the TEMPLATE interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_TEMPLATE_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_Init
* DeInitialize the TEMPLATE layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_TEMPLATE_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_Setup
* Handle the TEMPLATE specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_TEMPLATE_Setup(USBD_HandleTypeDef *pdev,
USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS :
switch (req->bRequest)
{
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = USBD_FAIL;
break;
}
return (uint8_t)ret;
}
/**
* @brief USBD_TEMPLATE_GetCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_TEMPLATE_GetCfgDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_TEMPLATE_CfgDesc);
return USBD_TEMPLATE_CfgDesc;
}
/**
* @brief USBD_TEMPLATE_GetDeviceQualifierDesc
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_TEMPLATE_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)sizeof(USBD_TEMPLATE_DeviceQualifierDesc);
return USBD_TEMPLATE_DeviceQualifierDesc;
}
/**
* @brief USBD_TEMPLATE_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_TEMPLATE_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_EP0_RxReady
* handle EP0 Rx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_TEMPLATE_EP0_RxReady(USBD_HandleTypeDef *pdev)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_EP0_TxReady
* handle EP0 TRx Ready event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_TEMPLATE_EP0_TxReady(USBD_HandleTypeDef *pdev)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_SOF
* handle SOF event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_TEMPLATE_SOF(USBD_HandleTypeDef *pdev)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_IsoINIncomplete
* handle data ISO IN Incomplete event
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_TEMPLATE_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_IsoOutIncomplete
* handle data ISO OUT Incomplete event
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_TEMPLATE_IsoOutIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_TEMPLATE_DataOut
* handle data OUT Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_TEMPLATE_DataOut(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO | D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO\Inc\usbd_video.h | /**
******************************************************************************
* @file usbd_video.h
* @author MCD Application Team
* @brief header file for the usbd_video.c file.
******************************************************************************
* @attention
*
* Copyright (c) 2020 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_VIDEO_H
#define __USBD_VIDEO_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_VIDEO
* @brief This file is the Header file for usbd_video.c
* @{
*/
/** @defgroup usbd_VIDEO_Exported_Defines
* @{
*/
/* USB Video device class specification version 1.10 */
#ifdef UVC_1_0
#define UVC_VERSION 0x0100U /* UVC 1.0 */
#else
#define UVC_VERSION 0x0110U /* UVC 1.1 */
#endif /* UVC_1_0 */
/* bEndpointAddress in Endpoint Descriptor */
#ifndef UVC_IN_EP
#define UVC_IN_EP 0x81U
#endif /* UVC_IN_EP */
/* These defines shall be updated in the usbd_conf.h file */
#ifndef UVC_WIDTH
#define UVC_WIDTH 400U
#endif /* UVC_WIDTH */
#ifndef UVC_HEIGHT
#define UVC_HEIGHT 240U
#endif /* UVC_HEIGHT */
#ifndef UVC_CAM_FPS_FS
#define UVC_CAM_FPS_FS 10U
#endif /* UVC_CAM_FPS_FS */
#ifndef UVC_CAM_FPS_HS
#define UVC_CAM_FPS_HS 5U
#endif /* UVC_CAM_FPS_HS */
#ifndef UVC_PACKET_SIZE
#define UVC_PACKET_SIZE 512U
#endif /* UVC_PACKET_SIZE */
#ifndef UVC_MAX_FRAME_SIZE
#define UVC_MAX_FRAME_SIZE (UVC_WIDTH * UVC_HEIGHT * 16U / 2U)
#endif /* UVC_MAX_FRAME_SIZE */
#ifndef UVC_COLOR_PRIMARIE
#define UVC_COLOR_PRIMARIE 0x01U
#endif /* UVC_COLOR_PRIMARIE */
#ifndef UVC_TFR_CHARACTERISTICS
#define UVC_TFR_CHARACTERISTICS 0x01U
#endif /* UVC_TFR_CHARACTERISTICS */
#ifndef UVC_MATRIX_COEFFICIENTS
#define UVC_MATRIX_COEFFICIENTS 0x04U
#endif /* UVC_MATRIX_COEFFICIENTS */
#ifndef UVC_BITS_PER_PIXEL
#define UVC_BITS_PER_PIXEL 12U
#endif /* UVC_BITS_PER_PIXEL */
#define UVC_GUID_YUY2 0x32595559U
#define UVC_GUID_NV12 0x3231564EU
#ifndef UVC_UNCOMPRESSED_GUID
#define UVC_UNCOMPRESSED_GUID UVC_GUID_NV12
#endif /* UVC_UNCOMPRESSED_GUID */
#define UVC_INTERVAL(n) (10000000U/(n))
#define UVC_MIN_BIT_RATE(n) (UVC_WIDTH * UVC_HEIGHT * 16U * (n)) /* 16 bit */
#define UVC_MAX_BIT_RATE(n) (UVC_WIDTH * UVC_HEIGHT * 16U * (n)) /* 16 bit */
#define UVC_PACKETS_IN_FRAME(n) (UVC_MAX_FRAME_SIZE / (n))
#ifndef UVC_ISO_FS_MPS
#define UVC_ISO_FS_MPS 256U
#endif /* UVC_ISO_FS_MPS */
#ifndef UVC_ISO_HS_MPS
#define UVC_ISO_HS_MPS 512U
#endif /* UVC_ISO_HS_MPS */
#ifndef UVC_HEADER_PACKET_CNT
#define UVC_HEADER_PACKET_CNT 0x01U
#endif /* UVC_HEADER_PACKET_CNT */
#define UVC_REQ_READ_MASK 0x80U
#define UVC_VC_IF_NUM 0x00U
#define UVC_VS_IF_NUM 0x01U
#define UVC_TOTAL_IF_NUM 0x02U
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
#define UVC_CONFIG_DESC_SIZ (0x88U + 0x16U)
#else
#define UVC_CONFIG_DESC_SIZ 0x88U
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
#define USBD_VC_GIUD_FORMAT_SIZE 16U
#define UVC_TOTAL_BUF_SIZE 0x04U
#define UVC_VC_EP_DESC_SIZE 0x05U
#define UVC_STREAMING_EP_DESC_SIZE 0x07U
#define UVC_EP_DESC_TYPE 0x25U
/* Video Interface Class Codes*/
#define UVC_CC_VIDEO 0x0EU
#define UVC_PLAY_STATUS_STOP 0x00U
#define UVC_PLAY_STATUS_READY 0x01U
#define UVC_PLAY_STATUS_STREAMING 0x02U
#ifndef WBVAL
#define WBVAL(x) ((x) & 0xFFU),(((x) >> 8) & 0xFFU)
#endif /* WBVAL */
#ifndef DBVAL
#define DBVAL(x) ((x)& 0xFFU),(((x) >> 8) & 0xFFU),(((x)>> 16) & 0xFFU),(((x) >> 24) & 0xFFU)
#endif /* DBVAL */
/* Video Interface Protocol Codes */
#define PC_PROTOCOL_UNDEFINED 0x00U
#define VIDEO_VC_IF_HEADER_DESC_SIZE 0x0DU
#define VIDEO_IN_TERMINAL_DESC_SIZE 0x08U
#define VIDEO_OUT_TERMINAL_DESC_SIZE 0x09U
#define VIDEO_VS_IF_IN_HEADER_DESC_SIZE 0x0EU
#define VS_FORMAT_UNCOMPRESSED_DESC_SIZE 0x1BU
#define VS_FORMAT_MJPEG_DESC_SIZE 0x0BU
#define VS_FRAME_DESC_SIZE 0x1EU
#define VS_COLOR_MATCHING_DESC_SIZE 0x06U
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
#define VS_FORMAT_DESC_SIZE VS_FORMAT_UNCOMPRESSED_DESC_SIZE
#define VS_FORMAT_SUBTYPE VS_FORMAT_UNCOMPRESSED
#define VS_FRAME_SUBTYPE VS_FRAME_UNCOMPRESSED
#define VC_HEADER_SIZE (VIDEO_VS_IF_IN_HEADER_DESC_SIZE + \
VS_FORMAT_UNCOMPRESSED_DESC_SIZE + \
VS_FRAME_DESC_SIZE + \
VS_COLOR_MATCHING_DESC_SIZE)
#else
#define VS_FORMAT_DESC_SIZE VS_FORMAT_MJPEG_DESC_SIZE
#define VS_FORMAT_SUBTYPE VS_FORMAT_MJPEG
#define VS_FRAME_SUBTYPE VS_FRAME_MJPEG
#define VC_HEADER_SIZE (VIDEO_VS_IF_IN_HEADER_DESC_SIZE + \
VS_FORMAT_DESC_SIZE + \
VS_FRAME_DESC_SIZE)
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
/*
* Video Class specification release 1.1
* Appendix A. Video Device Class Codes defines
*/
/* Video Interface Subclass values */
#define SC_UNDEFINED 0x00U
#define SC_VIDEOCONTROL 0x01U
#define SC_VIDEOSTREAMING 0x02U
#define SC_VIDEO_INTERFACE_COLLECTION 0x03U
/* Video Class-Specific Descriptor Types */
#define CS_UNDEFINED 0x20U
#define CS_DEVICE 0x21U
#define CS_CONFIGURATION 0x22U
#define CS_STRING 0x23U
#define CS_INTERFACE 0x24U
#define CS_ENDPOINT 0x25U
/* Video Class-Specific VideoControl Interface Descriptor Subtypes */
#define VC_DESCRIPTOR_UNDEFINED 0x00U
#define VC_HEADER 0x01U
#define VC_INPUT_TERMINAL 0x02U
#define VC_OUTPUT_TERMINAL 0x03U
#define VC_SELECTOR_UNIT 0x04U
#define VC_PROCESSING_UNIT 0x05U
#define VC_EXTENSION_UNIT 0x06U
/* Video Class-Specific VideoStreaming Interface Descriptor Subtypes */
#define VS_UNDEFINED 0x00U
#define VS_INPUT_HEADER 0x01U
#define VS_OUTPUT_HEADER 0x02U
#define VS_STILL_IMAGE_FRAME 0x03U
#define VS_FORMAT_UNCOMPRESSED 0x04U
#define VS_FRAME_UNCOMPRESSED 0x05U
#define VS_FORMAT_MJPEG 0x06U
#define VS_FRAME_MJPEG 0x07U
#define VS_FORMAT_MPEG2TS 0x0AU
#define VS_FORMAT_DV 0x0CU
#define VS_COLORFORMAT 0x0DU
#define VS_FORMAT_FRAME_BASED 0x10U
#define VS_FRAME_FRAME_BASED 0x11U
#define VS_FORMAT_STREAM_BASED 0x12U
/* Video Class-Specific Request values */
#define UVC_RQ_UNDEFINED 0x00U
#define UVC_SET_CUR 0x01U
#define UVC_GET_CUR 0x81U
#define UVC_GET_MIN 0x82U
#define UVC_GET_MAX 0x83U
#define UVC_GET_RES 0x84U
#define UVC_GET_LEN 0x85U
#define UVC_GET_INFO 0x86U
#define UVC_GET_DEF 0x87U
/* VideoControl Interface Control Selectors */
#define VC_CONTROL_UNDEFINED 0x00U
#define VC_VIDEO_POWER_MODE_CONTROL 0x01U
#define VC_REQUEST_ERROR_CODE_CONTROL 0x02U
/* Request Error Code Control */
#define UVC_NO_ERROR_ERR 0x00U
#define UVC_NOT_READY_ERR 0x01U
#define UVC_WRONG_STATE_ERR 0x02U
#define UVC_POWER_ERR 0x03U
#define UVC_OUT_OF_RANGE_ERR 0x04U
#define UVC_INVALID_UNIT_ERR 0x05U
#define UVC_INVALID_CONTROL_ERR 0x06U
#define UVC_INVALID_REQUEST_ERR 0x07U
#define UVC_UNKNOWN_ERR 0xFFU
/*Terminal Control Selectors*/
#define TE_CONTROL_UNDEFINED 0x00U
/* Selector Unit Control Selectors */
#define SU_CONTROL_UNDEFINED 0x00U
#define SU_INPUT_SELECT_CONTROL 0x01U
/* Camera Terminal Control Selectors */
#define CT_CONTROL_UNDEFINED 0x00U
#define CT_SCANNING_MODE_CONTROL 0x01U
#define CT_AE_MODE_CONTROL 0x02U
#define CT_AE_PRIORITY_CONTROL 0x03U
#define CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x04U
#define CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x05U
#define CT_FOCUS_ABSOLUTE_CONTROL 0x06U
#define CT_FOCUS_RELATIVE_CONTROL 0x07U
#define CT_FOCUS_AUTO_CONTROL 0x08U
#define CT_IRIS_ABSOLUTE_CONTROL 0x09U
#define CT_IRIS_RELATIVE_CONTROL 0x0AU
#define CT_ZOOM_ABSOLUTE_CONTROL 0x0BU
#define CT_ZOOM_RELATIVE_CONTROL 0x0CU
#define CT_PANTILT_ABSOLUTE_CONTROL 0x0DU
#define CT_PANTILT_RELATIVE_CONTROL 0x0EU
#define CT_ROLL_ABSOLUTE_CONTROL 0x0FU
#define CT_ROLL_RELATIVE_CONTROL 0x10U
#define CT_PRIVACY_CONTROL 0x11U
/* Processing Unit Control Selectors */
#define PU_CONTROL_UNDEFINED 0x00U
#define PU_BACKLIGHT_COMPENSATION_CONTROL 0x01U
#define PU_BRIGHTNESS_CONTROL 0x02U
#define PU_CONTRAST_CONTROL 0x03U
#define PU_GAIN_CONTROL 0x04U
#define PU_POWER_LINE_FREQUENCY_CONTROL 0x05U
#define PU_HUE_CONTROL 0x06U
#define PU_SATURATION_CONTROL 0x07U
#define PU_SHARPNESS_CONTROL 0x08U
#define PU_GAMMA_CONTROL 0x09U
#define PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x0AU
#define PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x0BU
#define PU_WHITE_BALANCE_COMPONENT_CONTROL 0x0CU
#define PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x0DU
#define PU_DIGITAL_MULTIPLIER_CONTROL 0x0EU
#define PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x0FU
#define PU_HUE_AUTO_CONTROL 0x10U
#define PU_ANALOG_VIDEO_STANDARD_CONTROL 0x11U
#define PU_ANALOG_LOCK_STATUS_CONTROL 0x12U
/*Extension Unit Control Selectors */
#define XU_CONTROL_UNDEFINED 0x00U
/* VideoStreaming Interface Control Selectors */
#define VS_CONTROL_UNDEFINED 0x00U
#define VS_PROBE_CONTROL 0x100U
#define VS_COMMIT_CONTROL 0x200U
#define VS_STILL_PROBE_CONTROL 0x03U
#define VS_STILL_COMMIT_CONTROL 0x04U
#define VS_STILL_IMAGE_TRIGGER_CONTROL 0x05U
#define VS_STREAM_ERROR_CODE_CONTROL 0x06U
#define VS_GENERATE_KEY_FRAME_CONTROL 0x07U
#define VS_UPDATE_FRAME_SEGMENT_CONTROL 0x08U
#define VS_SYNC_DELAY_CONTROL 0x09U
/* Control Capabilities */
#define UVC_SUPPORTS_GET 0x01U
#define UVC_SUPPORTS_SET 0x02U
#define UVC_STATE_DISABLED 0x04U
#define UVC_AUTOUPDATE_CONTROL 0x08U
#define UVC_ASYNCHRONOUS_CONTROL 0x10U
/* USB Terminal Types */
#define TT_VENDOR_SPECIFIC 0x0100U
#define TT_STREAMING 0x0101U
/* Input Terminal Types */
#define ITT_VENDOR_SPECIFIC 0x0200U
#define ITT_CAMERA 0x0201U
#define ITT_MEDIA_TRANSPORT_INPUT 0x0202U
/*Output Terminal Types */
#define OTT_VENDOR_SPECIFIC 0x0300U
#define OTT_DISPLAY 0x0301U
#define OTT_MEDIA_TRANSPORT_OUTPUT 0x0302U
/* External Terminal Types */
#define EXTERNAL_VENDOR_SPECIFIC 0x0400U
#define COMPOSITE_CONNECTOR 0x0401U
#define SVIDEO_CONNECTOR 0x0402U
#define COMPONENT_CONNECTOR 0x0403U
/* VIDEO Commands enumeration */
typedef enum
{
VIDEO_CMD_START = 1U,
VIDEO_CMD_PLAY,
VIDEO_CMD_STOP,
} VIDEO_CMD_TypeDef;
typedef enum
{
VIDEO_OFFSET_NONE = 0U,
VIDEO_OFFSET_HALF,
VIDEO_OFFSET_FULL,
VIDEO_OFFSET_UNKNOWN,
} VIDEO_OffsetTypeDef;
typedef struct
{
uint8_t cmd;
uint8_t data[USB_MAX_EP0_SIZE];
uint8_t len;
uint8_t unit;
} USBD_VIDEO_ControlTypeDef;
typedef struct
{
uint32_t interface;
uint32_t uvc_state;
uint32_t uvc_size;
uint8_t *uvc_buffer;
VIDEO_OffsetTypeDef offset;
USBD_VIDEO_ControlTypeDef control;
} USBD_VIDEO_HandleTypeDef;
typedef struct
{
int8_t (* Init)(void);
int8_t (* DeInit)(void);
int8_t (* Control)(uint8_t, uint8_t *, uint16_t);
int8_t (* Data)(uint8_t **, uint16_t *, uint16_t *);
} USBD_VIDEO_ItfTypeDef;
/* UVC uses only 26 first bytes */
typedef struct
{
uint16_t bmHint;
uint8_t bFormatIndex;
uint8_t bFrameIndex;
uint32_t dwFrameInterval;
uint16_t wKeyFrameRate;
uint16_t wPFrameRate;
uint16_t wCompQuality;
uint16_t wCompWindowSize;
uint16_t wDelay;
uint32_t dwMaxVideoFrameSize;
uint32_t dwMaxPayloadTransferSize;
uint32_t dwClockFrequency;
uint8_t bmFramingInfo;
uint8_t bPreferedVersion;
uint8_t bMinVersion;
uint8_t bMaxVersion;
} __PACKED USBD_VideoControlTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iFunction;
} __PACKED USBD_StandardVCIfDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bcdUVC;
uint16_t wTotalLength;
uint32_t dwClockFrequency;
uint8_t baInterfaceNr;
uint8_t iTerminal;
} __PACKED USBD_specificVCInDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t iTerminal;
} __PACKED USBD_InputTerminalDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bSourceID;
uint8_t iTerminal;
} __PACKED USBD_OutputTerminalDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint16_t bNumFormats;
uint8_t bVideoControlSize;
uint8_t bEndPointAddress;
uint8_t bmInfo;
uint8_t bTerminalLink;
uint8_t bStillCaptureMethod;
uint8_t bTriggerSupport;
uint8_t bTriggerUsage;
uint8_t bControlSize;
uint8_t bmaControls;
} __PACKED USBD_ClassSpecificVsHeaderDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint8_t bNumFrameDescriptor;
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
uint8_t pGiudFormat[USBD_VC_GIUD_FORMAT_SIZE];
uint8_t bBitsPerPixel;
#else
uint8_t bmFlags;
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
uint8_t bDefaultFrameIndex;
uint8_t bAspectRatioX;
uint8_t bAspectRatioY;
uint8_t bInterlaceFlags;
uint8_t bCopyProtect;
} __PACKED USBD_PayloadFormatDescTypeDef;
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bColorPrimarie;
uint8_t bTransferCharacteristics;
uint8_t bMatrixCoefficients;
} __PACKED USBD_ColorMatchingDescTypeDef;
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} __PACKED USBD_StandardVCDataEPDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFrameIndex;
uint8_t bmCapabilities;
uint16_t wWidth;
uint16_t wHeight;
uint32_t dwMinBitRate;
uint32_t dwMaxBitRate;
uint32_t dwMaxVideoFrameBufSize;
uint32_t dwDefaultFrameInterval;
uint8_t bFrameIntervalType;
uint32_t dwMinFrameInterval;
} __PACKED USBD_VIDEO_VSFrameDescTypeDef;
extern USBD_ClassTypeDef USBD_VIDEO;
#define USBD_VIDEO_CLASS &USBD_VIDEO
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_VIDEO_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_VIDEO_ItfTypeDef *fops);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* _USBD_VIDEO_H_ */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO | D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO\Inc\usbd_video_if_template.h | /**
******************************************************************************
* @file usbd_video_if_template.h
* @author MCD Application Team
* @brief Template Header file for the video Interface application layer functions
******************************************************************************
* @attention
*
* Copyright (c) 2020 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_VIDEO_IF_H__
#define __USBD_VIDEO_IF_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_video.h"
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @brief For Usb device.
* @{
*/
/** @defgroup USBD_VIDEO_IF
* @brief Usb VIDEO interface device module.
* @{
*/
/** @defgroup USBD_VIDEO_IF_Exported_Defines
* @brief Defines.
* @{
*/
/* USER CODE BEGIN EXPORTED_DEFINES */
/* USER CODE END EXPORTED_DEFINES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Exported_Types
* @brief Types.
* @{
*/
/* USER CODE BEGIN EXPORTED_TYPES */
/* USER CODE END EXPORTED_TYPES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Exported_Macros
* @brief Aliases.
* @{
*/
/* USER CODE BEGIN EXPORTED_MACRO */
/* USER CODE END EXPORTED_MACRO */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Exported_Variables
* @brief Public variables.
* @{
*/
/** VIDEO_IF Interface callback. */
extern USBD_VIDEO_ItfTypeDef USBD_VIDEO_fops_FS;
/* USER CODE BEGIN EXPORTED_VARIABLES */
/* USER CODE END EXPORTED_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Exported_FunctionsPrototype
* @brief Public functions declaration.
* @{
*/
/**
* @brief Manages the DMA full transfer complete event.
* @retval None
*/
void TransferComplete_CallBack_FS(void);
/**
* @brief Manages the DMA half transfer complete event.
* @retval None
*/
void HalfTransfer_CallBack_FS(void);
#define IMG_NBR 1U
#define IMAGE_SIZE 0x1U
const uint8_t image[] = {0x00};
const uint8_t *tImagesList[] = {image};
uint16_t tImagesSizes[] = {IMAGE_SIZE};
/* Time laps between video frames in ms.
Please adjust this value depending on required speed.
Please note that this define uses the system HAL_Delay() which uses the systick.
In case of changes on HAL_Delay, please ensure the values in ms correspond. */
#ifdef USE_USB_HS
#define USBD_VIDEO_IMAGE_LAPS 160U
#else
#define USBD_VIDEO_IMAGE_LAPS 80U
#endif /* USE_USB_HS */
/* USER CODE BEGIN EXPORTED_FUNCTIONS */
/* USER CODE END EXPORTED_FUNCTIONS */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* USBD_VIDEO_IF_H_ */
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO | D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO\Src\usbd_video.c | /**
******************************************************************************
* @file usbd_video.c
* @author MCD Application Team
* @brief This file provides the Video core functions.
*
******************************************************************************
* @attention
*
* Copyright (c) 2020 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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
*
* ===================================================================
* VIDEO Class Description
* ===================================================================
* This driver manages the Video Class 1.1 following the "USB Device Class Definition for
* Video Devices V1.0 Mar 18, 98".
* This driver implements the following aspects of the specification:
* - Device descriptor management
* - Configuration descriptor management
* - Interface Association Descriptor
* -Standard VC Interface Descriptor = interface 0
* -Standard Vs Interface Descriptor = interface 1
* - 1 Video Streaming Interface
* - 1 Video Streaming Endpoint
* - 1 Video Terminal Input (camera)
* - Video Class-Specific AC Interfaces
* - Video Class-Specific AS Interfaces
* - VideoControl Requests
* - Video Synchronization type: Asynchronous
* The current Video class version supports the following Video features:
* - image JPEG format
* - Asynchronous Endpoints
*
* @note In HS mode and when the USB DMA is used, all variables and data structures
* dealing with the DMA during the transaction process should be 32-bit aligned.
*
*
* @endverbatim
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_video.h"
#include "usbd_ctlreq.h"
#include "usbd_core.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_VIDEO
* @brief USB Device Video Class core module
* @{
*/
/** @defgroup USBD_VIDEO_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_VIDEO_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_VIDEO_Private_Macros
* @{
*/
/* VIDEO Device library callbacks */
static uint8_t USBD_VIDEO_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_VIDEO_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
static uint8_t USBD_VIDEO_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
#ifndef USE_USBD_COMPOSITE
static uint8_t *USBD_VIDEO_GetFSCfgDesc(uint16_t *length);
static uint8_t *USBD_VIDEO_GetHSCfgDesc(uint16_t *length);
static uint8_t *USBD_VIDEO_GetOtherSpeedCfgDesc(uint16_t *length);
static uint8_t *USBD_VIDEO_GetDeviceQualifierDesc(uint16_t *length);
#endif /* USE_USBD_COMPOSITE */
static uint8_t USBD_VIDEO_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum);
static uint8_t USBD_VIDEO_SOF(USBD_HandleTypeDef *pdev);
static uint8_t USBD_VIDEO_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
/* VIDEO Requests management functions */
static void VIDEO_REQ_GetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void VIDEO_REQ_SetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
#ifndef USE_USBD_COMPOSITE
static void *USBD_VIDEO_GetVSFrameDesc(uint8_t *pConfDesc);
#endif /* USE_USBD_COMPOSITE */
static void *USBD_VIDEO_GetVideoHeaderDesc(uint8_t *pConfDesc);
/**
* @}
*/
/** @defgroup USBD_VIDEO_Private_Variables
* @{
*/
USBD_ClassTypeDef USBD_VIDEO =
{
USBD_VIDEO_Init,
USBD_VIDEO_DeInit,
USBD_VIDEO_Setup,
NULL,
NULL,
USBD_VIDEO_DataIn,
NULL,
USBD_VIDEO_SOF,
USBD_VIDEO_IsoINIncomplete,
NULL,
#ifdef USE_USBD_COMPOSITE
NULL,
NULL,
NULL,
NULL,
#else
USBD_VIDEO_GetHSCfgDesc,
USBD_VIDEO_GetFSCfgDesc,
USBD_VIDEO_GetOtherSpeedCfgDesc,
USBD_VIDEO_GetDeviceQualifierDesc,
#endif /* USE_USBD_COMPOSITE */
};
/* USB VIDEO device Configuration Descriptor (same for all speeds thanks to user defines) */
__ALIGN_BEGIN static uint8_t USBD_VIDEO_CfgDesc[] __ALIGN_END =
{
/* Configuration 1 */
USB_CONF_DESC_SIZE, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
LOBYTE(UVC_CONFIG_DESC_SIZ), /* wTotalLength: no of returned bytes */
HIBYTE(UVC_CONFIG_DESC_SIZ),
0x02, /* bNumInterfaces: 2 interfaces */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor
describing the configuration */
#if (USBD_SELF_POWERED == 1U)
0xC0, /* bmAttributes: Bus Powered according to user configuration */
#else
0x80, /* bmAttributes: Bus Powered according to user configuration */
#endif /* USBD_SELF_POWERED */
USBD_MAX_POWER, /* bMaxPower in mA according to user configuration */
/* Interface Association Descriptor */
USB_IAD_DESC_SIZE, /* bLength: Interface Association Descriptor size */
USB_DESC_TYPE_IAD, /* bDescriptorType: interface association */
0x00, /* bFirstInterface */
0x02, /* bInterfaceCount */
UVC_CC_VIDEO, /* bFunctionClass: Video class */
SC_VIDEO_INTERFACE_COLLECTION, /* bFunctionSubClass: Video Interface Collection */
PC_PROTOCOL_UNDEFINED, /* bInterfaceProtocol: protocol undefined */
0x00, /* iFunction */
/* Standard VC (Video Control) Interface Descriptor = interface 0 */
USB_IF_DESC_SIZE, /* bLength: interface descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType: interface */
UVC_VC_IF_NUM, /* bInterfaceNumber: interface number */
0x00, /* bAlternateSetting: index of this alternate setting */
0x00, /* bNumEndpoints: No endpoints used for this interface */
UVC_CC_VIDEO, /* bInterfaceClass: Video Class */
SC_VIDEOCONTROL, /* bInterfaceSubClass: Video Control */
PC_PROTOCOL_UNDEFINED, /* bInterfaceProtocol: protocol is undefined */
0x00, /* iFunction: index of string descriptor relative to this item */
/* Class-specific VC Interface Descriptor */
VIDEO_VC_IF_HEADER_DESC_SIZE, /* bLength */
CS_INTERFACE, /* bDescriptorType */
VC_HEADER, /* bDescriptorSubtype */
LOBYTE(UVC_VERSION),
HIBYTE(UVC_VERSION), /* bcdUVC: UVC1.0 or UVC1.1 revision */
VS_FRAME_DESC_SIZE, /* wTotalLength: total size of class-specific descriptors */
0x00,
0x00, /* dwClockFrequency: not used. 48 Mhz value is set, but not used */
0x6C,
0xDC,
0x02,
0x01, /* bInCollection: number of streaming interfaces */
0x01, /* baInterfaceNr(1): VideoStreaming interface 1 is part
of VC interface */
/* Input Terminal Descriptor */
VIDEO_IN_TERMINAL_DESC_SIZE, /* bLength: Input terminal descriptor size */
CS_INTERFACE, /* bDescriptorType: INTERFACE */
VC_INPUT_TERMINAL, /* bDescriptorSubtype: INPUT_TERMINAL */
0x01, /* bTerminalID: ID of this Terminal */
LOBYTE(ITT_VENDOR_SPECIFIC), /* wTerminalType: 0x0200 ITT_VENDOR_SPECIFIC */
HIBYTE(ITT_VENDOR_SPECIFIC),
0x00, /* bAssocTerminal: no Terminal is associated */
0x00, /* iTerminal: index of string descriptor relative to this item */
/* Output Terminal Descriptor */
VIDEO_OUT_TERMINAL_DESC_SIZE, /* bLength: output terminal descriptor size */
CS_INTERFACE, /* bDescriptorType */
VC_OUTPUT_TERMINAL, /* bDescriptorSubtype */
0x02, /* bTerminalID */
LOBYTE(TT_STREAMING), /* wTerminalType: USB streaming terminal */
HIBYTE(TT_STREAMING),
0x00, /* bAssocTerminal: no Terminal is associated */
0x01, /* bSourceID: input is connected to output unit ID 1 */
0x00, /* iTerminal: index of string descriptor relative to this item */
/* Standard VS (Video Streaming) Interface Descriptor = interface 1, alternate setting 0 = Zero Bandwidth
(when no data are sent from the device) */
USB_IF_DESC_SIZE, /* bLength: interface descriptor size */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */
UVC_VS_IF_NUM, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x00, /* bNumEndpoints: no endpoints used for alternate setting 0 */
UVC_CC_VIDEO, /* bInterfaceClass */
SC_VIDEOSTREAMING, /* bInterfaceSubClass */
PC_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface: index of string descriptor relative to this item */
/* Class-specific VS Header Descriptor (Input) */
VIDEO_VS_IF_IN_HEADER_DESC_SIZE, /* bLength */
CS_INTERFACE, /* bDescriptorType */
VS_INPUT_HEADER, /* bDescriptorSubtype */
0x01, /* bNumFormats: 1 format descriptor is used */
VC_HEADER_SIZE,
0x00, /* Total size of Video Control Specific Descriptors */
UVC_IN_EP, /* bEndPointAddress: In endpoint is used for the alternate setting */
0x00, /* bmInfo: dynamic format change not supported */
0x02, /* bTerminalLink: output to terminal ID 2 */
0x00, /* bStillCaptureMethod: not supported */
0x00, /* bTriggerSupport: not supported */
0x00, /* bTriggerUsage: not supported */
0x01, /* bControlSize: 1 byte field size */
0x00, /* bmaControls: No specific controls used */
/* Payload Format Descriptor */
VS_FORMAT_DESC_SIZE, /* blength */
CS_INTERFACE, /* bDescriptorType */
VS_FORMAT_SUBTYPE, /* bDescriptorSubType */
0x01, /* bFormatIndex */
0x01, /* bNumFrameDescriptor */
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
DBVAL(UVC_UNCOMPRESSED_GUID), /* Giud Format: YUY2 {32595559-0000-0010-8000-00AA00389B71} */
0x00, 0x00,
0x10, 0x00,
0x80, 0x00,
0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71,
UVC_BITS_PER_PIXEL, /* bBitsPerPixel : Number of bits per pixel */
#else
0x01, /* bmFlags: FixedSizeSamples */
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
0x01, /* bDefaultFrameIndex: default frame used is frame 1
(only one frame used) */
0x00, /* bAspectRatioX: not required by specification */
0x00, /* bAspectRatioY: not required by specification */
0x00, /* bInterlaceFlags: non interlaced stream */
0x00, /* bCopyProtect: no protection restrictions */
/* Class-specific VS (Video Streaming) Frame Descriptor */
VS_FRAME_DESC_SIZE, /* bLength */
CS_INTERFACE, /* bDescriptorType */
VS_FRAME_SUBTYPE, /* bDescriptorSubType */
0x01, /* bFrameIndex */
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
0x00, /* bmCapabilities: no till image capture */
#else
0x02, /* bmCapabilities: fixed frame rate supported */
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
WBVAL(UVC_WIDTH), /* wWidth: Image Frame Width */
WBVAL(UVC_HEIGHT), /* wHeight: Image Frame Height */
DBVAL(UVC_MIN_BIT_RATE(UVC_CAM_FPS_FS)), /* dwMinBitRate: Minimum supported bit rate in bits/s */
DBVAL(UVC_MAX_BIT_RATE(UVC_CAM_FPS_FS)), /* dwMaxBitRate: Maximum supported bit rate in bits/s */
DBVAL(UVC_MAX_FRAME_SIZE), /* dwMaxVideoFrameBufSize: Maximum video frame size, in bytes */
DBVAL(UVC_INTERVAL(UVC_CAM_FPS_FS)), /* dwDefaultFrameInterval: following number of FPS */
0x01, /* bFrameIntervalType: Discrete frame interval type */
DBVAL(UVC_INTERVAL(UVC_CAM_FPS_FS)), /* dwMinFrameInterval: One supported value of interval (FPS) */
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
/* Color Matching Descriptor */
VS_COLOR_MATCHING_DESC_SIZE, /* bLength */
CS_INTERFACE, /* bDescriptorType: CS_INTERFACE */
VS_COLORFORMAT, /* bDescriptorSubType: VS_COLORFORMAT */
UVC_COLOR_PRIMARIE, /* bColorPrimarie: 1: BT.709, sRGB (default) */
UVC_TFR_CHARACTERISTICS, /* bTransferCharacteristics: 1: BT.709 (default) */
UVC_MATRIX_COEFFICIENTS, /* bMatrixCoefficients: 4: BT.601, (default) */
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
/* Standard VS Interface Descriptor = interface 1, alternate setting 1 = data transfer mode */
USB_IF_DESC_SIZE, /* bLength */
USB_DESC_TYPE_INTERFACE, /* bDescriptorType */
UVC_VS_IF_NUM, /* bInterfaceNumber */
0x01, /* bAlternateSetting */
0x01, /* bNumEndpoints: one endpoint is used */
UVC_CC_VIDEO, /* bInterfaceClass */
SC_VIDEOSTREAMING, /* bInterfaceSubClass */
PC_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface: index of string descriptor relative to this item */
/* Standard VS (Video Streaming) data Endpoint */
USB_EP_DESC_SIZE, /* bLength */
USB_DESC_TYPE_ENDPOINT, /* bDescriptorType */
UVC_IN_EP, /* bEndpointAddress */
0x05, /* bmAttributes: ISO transfer */
LOBYTE(UVC_ISO_FS_MPS), /* wMaxPacketSize */
LOBYTE(UVC_ISO_FS_MPS),
0x01, /* bInterval: 1 frame interval */
};
#ifndef USE_USBD_COMPOSITE
/* USB Standard Device Descriptor */
__ALIGN_BEGIN static uint8_t USBD_VIDEO_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
USB_LEN_DEV_QUALIFIER_DESC,
USB_DESC_TYPE_DEVICE_QUALIFIER,
0x00,
0x02,
0xEF,
0x02,
0x01,
0x40,
0x01,
0x00,
};
#endif /* USE_USBD_COMPOSITE */
static uint8_t VIDEOinEpAdd = UVC_IN_EP;
/* Video Commit data structure */
static USBD_VideoControlTypeDef video_Commit_Control =
{
.bmHint = 0x0000U,
.bFormatIndex = 0x01U,
.bFrameIndex = 0x01U,
.dwFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS),
.wKeyFrameRate = 0x0000U,
.wPFrameRate = 0x0000U,
.wCompQuality = 0x0000U,
.wCompWindowSize = 0x0000U,
.wDelay = 0x0000U,
.dwMaxVideoFrameSize = 0x0000U,
.dwMaxPayloadTransferSize = 0x00000000U,
.dwClockFrequency = 0x00000000U,
.bmFramingInfo = 0x00U,
.bPreferedVersion = 0x00U,
.bMinVersion = 0x00U,
.bMaxVersion = 0x00U,
};
/* Video Probe data structure */
static USBD_VideoControlTypeDef video_Probe_Control =
{
.bmHint = 0x0000U,
.bFormatIndex = 0x01U,
.bFrameIndex = 0x01U,
.dwFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS),
.wKeyFrameRate = 0x0000U,
.wPFrameRate = 0x0000U,
.wCompQuality = 0x0000U,
.wCompWindowSize = 0x0000U,
.wDelay = 0x0000U,
.dwMaxVideoFrameSize = 0x0000U,
.dwMaxPayloadTransferSize = 0x00000000U,
.dwClockFrequency = 0x00000000U,
.bmFramingInfo = 0x00U,
.bPreferedVersion = 0x00U,
.bMinVersion = 0x00U,
.bMaxVersion = 0x00U,
};
/**
* @}
*/
/** @defgroup USBD_VIDEO_Private_Functions
* @{
*/
/**
* @brief USBD_VIDEO_Init
* Initialize the VIDEO interface
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_VIDEO_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
USBD_VIDEO_HandleTypeDef *hVIDEO;
/* Allocate memory for the video control structure */
hVIDEO = (USBD_VIDEO_HandleTypeDef *)USBD_malloc(sizeof(USBD_VIDEO_HandleTypeDef));
/* Check if allocated point is NULL, then exit with error code */
if (hVIDEO == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Assign the pClassData pointer to the allocated structure */
pdev->pClassDataCmsit[pdev->classId] = (void *)hVIDEO;
pdev->pClassData = pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Open EP IN */
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
(void)USBD_LL_OpenEP(pdev, VIDEOinEpAdd, USBD_EP_TYPE_ISOC, UVC_ISO_HS_MPS);
pdev->ep_in[VIDEOinEpAdd & 0xFU].is_used = 1U;
pdev->ep_in[VIDEOinEpAdd & 0xFU].maxpacket = UVC_ISO_HS_MPS;
}
else
{
(void)USBD_LL_OpenEP(pdev, VIDEOinEpAdd, USBD_EP_TYPE_ISOC, UVC_ISO_FS_MPS);
pdev->ep_in[VIDEOinEpAdd & 0xFU].is_used = 1U;
pdev->ep_in[VIDEOinEpAdd & 0xFU].maxpacket = UVC_ISO_FS_MPS;
}
/* Init physical Interface components */
((USBD_VIDEO_ItfTypeDef *)pdev->pUserData[pdev->classId])->Init();
/* Init Xfer states */
hVIDEO->interface = 0U;
/* Some calls to unused variables, to comply with MISRA-C 2012 rules */
UNUSED(USBD_VIDEO_CfgDesc);
UNUSED(cfgidx);
/* Exit with no error code */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_VIDEO_DeInit
* DeInitialize the VIDEO layer
* @param pdev: device instance
* @param cfgidx: Configuration index
* @retval status
*/
static uint8_t USBD_VIDEO_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
UNUSED(cfgidx);
/* Check if the video structure pointer is valid */
if (pdev->pClassDataCmsit[pdev->classId] == NULL)
{
return (uint8_t)USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Close EP IN */
(void)USBD_LL_CloseEP(pdev, VIDEOinEpAdd);
pdev->ep_in[VIDEOinEpAdd & 0xFU].is_used = 0U;
/* DeInit physical Interface components */
((USBD_VIDEO_ItfTypeDef *)pdev->pUserData[pdev->classId])->DeInit();
USBD_free(pdev->pClassDataCmsit[pdev->classId]);
pdev->pClassDataCmsit[pdev->classId] = NULL;
pdev->pClassData = NULL;
/* Exit with no error code */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_VIDEO_Setup
* Handle the VIDEO specific requests
* @param pdev: instance
* @param req: usb requests
* @retval status
*/
static uint8_t USBD_VIDEO_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_VIDEO_HandleTypeDef *hVIDEO = (USBD_VIDEO_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
uint8_t ret = (uint8_t)USBD_OK;
uint16_t status_info = 0U;
uint16_t len;
uint8_t *pbuf;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
/* Class Requests -------------------------------*/
case USB_REQ_TYPE_CLASS:
switch (req->bRequest)
{
case UVC_GET_CUR:
case UVC_GET_DEF:
case UVC_GET_MIN:
case UVC_GET_MAX:
VIDEO_REQ_GetCurrent(pdev, req);
break;
case UVC_GET_RES:
case UVC_GET_LEN:
case UVC_GET_INFO:
break;
case UVC_SET_CUR:
VIDEO_REQ_SetCurrent(pdev, req);
break;
default:
(void) USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
break;
}
break;
/* Standard Requests -------------------------------*/
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_STATUS:
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void) USBD_CtlSendData(pdev, (uint8_t *)&status_info, 2U);
}
else
{
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
}
break;
case USB_REQ_GET_DESCRIPTOR:
if ((req->wValue >> 8) == CS_DEVICE)
{
pbuf = (uint8_t *)USBD_VIDEO_GetVideoHeaderDesc(pdev->pConfDesc);
if (pbuf != NULL)
{
len = MIN((uint16_t)USB_CONF_DESC_SIZE, (uint16_t)req->wLength);
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
}
}
break;
case USB_REQ_GET_INTERFACE :
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
(void)USBD_CtlSendData(pdev, (uint8_t *)&hVIDEO->interface, 1U);
}
else
{
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
}
break;
case USB_REQ_SET_INTERFACE :
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (req->wValue <= USBD_MAX_NUM_INTERFACES)
{
hVIDEO->interface = LOBYTE(req->wValue);
if (hVIDEO->interface == 1U)
{
/* Start Streaming (First endpoint writing will be done on next SOF) */
(void)USBD_LL_FlushEP(pdev, VIDEOinEpAdd);
hVIDEO->uvc_state = UVC_PLAY_STATUS_READY;
}
else
{
/* Stop Streaming */
hVIDEO->uvc_state = UVC_PLAY_STATUS_STOP;
(void)USBD_LL_FlushEP(pdev, VIDEOinEpAdd);
}
}
else
{
/* Call the error management function (command will be NAKed) */
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
}
}
else
{
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
}
break;
case USB_REQ_CLEAR_FEATURE:
break;
default:
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
break;
}
break;
default:
USBD_CtlError(pdev, req);
ret = (uint8_t)USBD_FAIL;
break;
}
return ret;
}
/**
* @brief USBD_VIDEO_DataIn
* handle data IN Stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_VIDEO_DataIn(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_VIDEO_HandleTypeDef *hVIDEO = (USBD_VIDEO_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
static uint8_t packet[UVC_PACKET_SIZE + (UVC_HEADER_PACKET_CNT * 2U)] = {0x00U};
static uint8_t *Pcktdata = packet;
static uint16_t PcktIdx = 0U;
static uint16_t PcktSze = UVC_PACKET_SIZE;
static uint8_t payload_header[2] = {0x02U, 0x00U};
uint8_t i = 0U;
uint32_t RemainData = 0U;
uint32_t DataOffset = 0U;
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Check if the Streaming has already been started */
if (hVIDEO->uvc_state == UVC_PLAY_STATUS_STREAMING)
{
/* Get the current packet buffer, index and size from the application layer */
((USBD_VIDEO_ItfTypeDef *)pdev->pUserData[pdev->classId])->Data(&Pcktdata, &PcktSze, &PcktIdx);
/* Check if end of current image has been reached */
if (PcktSze > 2U)
{
/* Check if this is the first packet in current image */
if (PcktIdx == 0U)
{
/* Set the packet start index */
payload_header[1] ^= 0x01U;
}
RemainData = PcktSze;
/* fill the Transmit buffer */
while (RemainData > 0U)
{
packet[((DataOffset + 0U) * i)] = payload_header[0];
packet[((DataOffset + 0U) * i) + 1U] = payload_header[1];
if (RemainData > pdev->ep_in[VIDEOinEpAdd & 0xFU].maxpacket)
{
DataOffset = pdev->ep_in[VIDEOinEpAdd & 0xFU].maxpacket;
(void)USBD_memcpy((packet + ((DataOffset + 0U) * i) + 2U),
Pcktdata + ((DataOffset - 2U) * i), (DataOffset - 2U));
RemainData -= DataOffset;
i++;
}
else
{
(void)USBD_memcpy((packet + ((DataOffset + 0U) * i) + 2U),
Pcktdata + ((DataOffset - 2U) * i), (RemainData - 2U));
RemainData = 0U;
}
}
}
else
{
/* Add the packet header */
packet[0] = payload_header[0];
packet[1] = payload_header[1];
}
hVIDEO->uvc_buffer = (uint8_t *)&packet;
hVIDEO->uvc_size = (uint32_t)PcktSze;
/* Transmit the packet on Endpoint */
(void)USBD_LL_Transmit(pdev, (uint8_t)(epnum | 0x80U),
hVIDEO->uvc_buffer, hVIDEO->uvc_size);
}
/* Exit with no error code */
return (uint8_t) USBD_OK;
}
/**
* @brief USBD_VIDEO_SOF
* handle SOF event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_VIDEO_SOF(USBD_HandleTypeDef *pdev)
{
USBD_VIDEO_HandleTypeDef *hVIDEO = (USBD_VIDEO_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
uint8_t payload[2] = {0x02U, 0x00U};
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
/* Check if the Streaming has already been started by SetInterface AltSetting 1 */
if (hVIDEO->uvc_state == UVC_PLAY_STATUS_READY)
{
hVIDEO->uvc_buffer = (uint8_t *)&payload;
hVIDEO->uvc_size = 2U;
/* Transmit the first packet indicating that Streaming is starting */
(void)USBD_LL_Transmit(pdev, VIDEOinEpAdd, hVIDEO->uvc_buffer, hVIDEO->uvc_size);
/* Enable Streaming state */
hVIDEO->uvc_state = UVC_PLAY_STATUS_STREAMING;
}
/* Exit with no error code */
return (uint8_t)USBD_OK;
}
/**
* @brief USBD_VIDEO_IsoINIncomplete
* handle data ISO IN Incomplete event
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_VIDEO_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum)
{
USBD_VIDEO_HandleTypeDef *hVIDEO = (USBD_VIDEO_HandleTypeDef *) pdev->pClassDataCmsit[pdev->classId];
#ifdef USE_USBD_COMPOSITE
/* Get the Endpoints addresses allocated for this class instance */
VIDEOinEpAdd = USBD_CoreGetEPAdd(pdev, USBD_EP_IN, USBD_EP_TYPE_ISOC, (uint8_t)pdev->classId);
#endif /* USE_USBD_COMPOSITE */
if (epnum == (VIDEOinEpAdd & 0xFU))
{
(void)USBD_LL_Transmit(pdev, VIDEOinEpAdd, hVIDEO->uvc_buffer, hVIDEO->uvc_size);
}
return (uint8_t)USBD_OK;
}
/**
* @brief VIDEO_Req_GetCurrent
* Handles the GET_CUR VIDEO control request.
* @param pdev: instance
* @param req: setup class request
* @retval status
*/
static void VIDEO_REQ_GetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_VIDEO_HandleTypeDef *hVIDEO;
hVIDEO = (USBD_VIDEO_HandleTypeDef *)(pdev->pClassDataCmsit[pdev->classId]);
static __IO uint8_t EntityStatus[8] = {0};
/* Reset buffer to zeros */
(void) USBD_memset(hVIDEO->control.data, 0, USB_MAX_EP0_SIZE);
/* Manage Video Control interface requests */
if (LOBYTE(req->wIndex) == 0x00U)
{
if (HIBYTE(req->wValue) == 0x02U)
{
/* Get the status of the current requested Entity */
EntityStatus[0] = 0x06U;
/* Send current status */
(void) USBD_CtlSendData(pdev, (uint8_t *)&EntityStatus, 1U);
}
else
{
/* Unknown request */
USBD_CtlError(pdev, req);
}
}
/* Manage Video Streaming interface requests */
else
{
if (LOBYTE(req->wValue) == (uint8_t)VS_PROBE_CONTROL)
{
/* Update bPreferedVersion, bMinVersion and bMaxVersion which must be set only by Device */
video_Probe_Control.bPreferedVersion = 0x00U;
video_Probe_Control.bMinVersion = 0x00U;
video_Probe_Control.bMaxVersion = 0x00U;
video_Probe_Control.dwMaxVideoFrameSize = UVC_MAX_FRAME_SIZE;
video_Probe_Control.dwClockFrequency = 0x02DC6C00U;
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
video_Probe_Control.dwFrameInterval = (UVC_INTERVAL(UVC_CAM_FPS_HS));
video_Probe_Control.dwMaxPayloadTransferSize = UVC_ISO_HS_MPS;
}
else
{
video_Probe_Control.dwFrameInterval = (UVC_INTERVAL(UVC_CAM_FPS_FS));
video_Probe_Control.dwMaxPayloadTransferSize = UVC_ISO_FS_MPS;
}
/* Probe Request */
(void)USBD_CtlSendData(pdev, (uint8_t *)&video_Probe_Control,
MIN(req->wLength, sizeof(USBD_VideoControlTypeDef)));
}
else if (LOBYTE(req->wValue) == (uint8_t)VS_COMMIT_CONTROL)
{
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
video_Commit_Control.dwFrameInterval = (UVC_INTERVAL(UVC_CAM_FPS_HS));
video_Commit_Control.dwMaxPayloadTransferSize = UVC_ISO_HS_MPS;
}
else
{
video_Commit_Control.dwFrameInterval = (UVC_INTERVAL(UVC_CAM_FPS_FS));
video_Commit_Control.dwMaxPayloadTransferSize = UVC_ISO_FS_MPS;
}
/* Commit Request */
(void)USBD_CtlSendData(pdev, (uint8_t *)&video_Commit_Control,
MIN(req->wLength, sizeof(USBD_VideoControlTypeDef)));
}
else
{
/* Send the current state */
(void) USBD_CtlSendData(pdev, hVIDEO->control.data,
MIN(req->wLength, USB_MAX_EP0_SIZE));
}
}
}
/**
* @brief VIDEO_Req_SetCurrent
* Handles the SET_CUR VIDEO control request.
* @param pdev: instance
* @param req: setup class request
* @retval status
*/
static void VIDEO_REQ_SetCurrent(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
/* Check that the request has control data */
if (req->wLength > 0U)
{
/* Prepare the reception of the buffer over EP0 */
if (req->wValue == (uint16_t)VS_PROBE_CONTROL)
{
/* Probe Request */
(void) USBD_CtlPrepareRx(pdev, (uint8_t *)&video_Probe_Control,
MIN(req->wLength, sizeof(USBD_VideoControlTypeDef)));
}
else if (req->wValue == (uint16_t)VS_COMMIT_CONTROL)
{
/* Commit Request */
(void) USBD_CtlPrepareRx(pdev, (uint8_t *)&video_Commit_Control,
MIN(req->wLength, sizeof(USBD_VideoControlTypeDef)));
}
else
{
(void)USBD_LL_StallEP(pdev, 0x80U);
}
}
}
#ifndef USE_USBD_COMPOSITE
/**
* @brief USBD_VIDEO_GetFSCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_VIDEO_GetFSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_VIDEO_CfgDesc, VIDEOinEpAdd);
USBD_VIDEO_VSFrameDescTypeDef *pVSFrameDesc = USBD_VIDEO_GetVSFrameDesc(USBD_VIDEO_CfgDesc);
if (pEpDesc != NULL)
{
pEpDesc->wMaxPacketSize = UVC_ISO_FS_MPS;
}
if (pVSFrameDesc != NULL)
{
pVSFrameDesc->dwMinBitRate = UVC_MIN_BIT_RATE(UVC_CAM_FPS_FS);
pVSFrameDesc->dwMaxBitRate = UVC_MAX_BIT_RATE(UVC_CAM_FPS_FS);
pVSFrameDesc->dwDefaultFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
pVSFrameDesc->dwMinFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
}
*length = (uint16_t)(sizeof(USBD_VIDEO_CfgDesc));
return USBD_VIDEO_CfgDesc;
}
/**
* @brief USBD_VIDEO_GetHSCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_VIDEO_GetHSCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_VIDEO_CfgDesc, VIDEOinEpAdd);
USBD_VIDEO_VSFrameDescTypeDef *pVSFrameDesc = USBD_VIDEO_GetVSFrameDesc(USBD_VIDEO_CfgDesc);
if (pEpDesc != NULL)
{
pEpDesc->wMaxPacketSize = UVC_ISO_HS_MPS;
}
if (pVSFrameDesc != NULL)
{
pVSFrameDesc->dwMinBitRate = UVC_MIN_BIT_RATE(UVC_CAM_FPS_HS);
pVSFrameDesc->dwMaxBitRate = UVC_MAX_BIT_RATE(UVC_CAM_FPS_HS);
pVSFrameDesc->dwDefaultFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_HS);
pVSFrameDesc->dwMinFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_HS);
}
*length = (uint16_t)(sizeof(USBD_VIDEO_CfgDesc));
return USBD_VIDEO_CfgDesc;
}
/**
* @brief USBD_VIDEO_GetOtherSpeedCfgDesc
* return configuration descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_VIDEO_GetOtherSpeedCfgDesc(uint16_t *length)
{
USBD_EpDescTypeDef *pEpDesc = USBD_GetEpDesc(USBD_VIDEO_CfgDesc, VIDEOinEpAdd);
USBD_VIDEO_VSFrameDescTypeDef *pVSFrameDesc = USBD_VIDEO_GetVSFrameDesc(USBD_VIDEO_CfgDesc);
if (pEpDesc != NULL)
{
pEpDesc->wMaxPacketSize = UVC_ISO_FS_MPS;
}
if (pVSFrameDesc != NULL)
{
pVSFrameDesc->dwMinBitRate = UVC_MIN_BIT_RATE(UVC_CAM_FPS_FS);
pVSFrameDesc->dwMaxBitRate = UVC_MAX_BIT_RATE(UVC_CAM_FPS_FS);
pVSFrameDesc->dwDefaultFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
pVSFrameDesc->dwMinFrameInterval = UVC_INTERVAL(UVC_CAM_FPS_FS);
}
*length = (uint16_t)(sizeof(USBD_VIDEO_CfgDesc));
return USBD_VIDEO_CfgDesc;
}
/**
* @brief DeviceQualifierDescriptor
* return Device Qualifier descriptor
* @param length : pointer data length
* @retval pointer to descriptor buffer
*/
static uint8_t *USBD_VIDEO_GetDeviceQualifierDesc(uint16_t *length)
{
*length = (uint16_t)(sizeof(USBD_VIDEO_DeviceQualifierDesc));
return USBD_VIDEO_DeviceQualifierDesc;
}
/**
* @brief USBD_VIDEO_GetVSFrameDesc
* This function return the Video Endpoint descriptor
* @param pdev: device instance
* @param pConfDesc: pointer to Bos descriptor
* @retval pointer to video endpoint descriptor
*/
static void *USBD_VIDEO_GetVSFrameDesc(uint8_t *pConfDesc)
{
USBD_DescHeaderTypeDef *pdesc = (USBD_DescHeaderTypeDef *)(void *)pConfDesc;
USBD_ConfigDescTypeDef *desc = (USBD_ConfigDescTypeDef *)(void *)pConfDesc;
USBD_VIDEO_VSFrameDescTypeDef *pVSFrameDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_GetNextDesc((uint8_t *)pdesc, &ptr);
if (((pdesc->bDescriptorSubType == VS_FRAME_MJPEG) ||
(pdesc->bDescriptorSubType == VS_FRAME_UNCOMPRESSED)) &&
(pdesc->bLength == VS_FRAME_DESC_SIZE))
{
pVSFrameDesc = (USBD_VIDEO_VSFrameDescTypeDef *)(void *)pdesc;
break;
}
}
}
return (void *)pVSFrameDesc;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_VIDEO_GetVideoHeaderDesc
* This function return the Video Header descriptor
* @param pdev: device instance
* @param pConfDesc: pointer to Bos descriptor
* @retval pointer to the Video Header descriptor
*/
static void *USBD_VIDEO_GetVideoHeaderDesc(uint8_t *pConfDesc)
{
USBD_ConfigDescTypeDef *desc = (USBD_ConfigDescTypeDef *)(void *)pConfDesc;
USBD_DescHeaderTypeDef *pdesc = (USBD_DescHeaderTypeDef *)(void *)pConfDesc;
uint8_t *pVideoDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_GetNextDesc((uint8_t *)pdesc, &ptr);
if ((pdesc->bDescriptorType == CS_INTERFACE) &&
(pdesc->bDescriptorSubType == VC_HEADER))
{
pVideoDesc = (uint8_t *)pdesc;
break;
}
}
}
return pVideoDesc;
}
/**
* @brief USBD_VIDEO_RegisterInterface
* @param pdev: instance
* @param fops: VIDEO interface callback
* @retval status
*/
uint8_t USBD_VIDEO_RegisterInterface(USBD_HandleTypeDef *pdev, USBD_VIDEO_ItfTypeDef *fops)
{
/* Check if the FOPS pointer is valid */
if (fops == NULL)
{
return (uint8_t)USBD_FAIL;
}
/* Assign the FOPS pointer */
pdev->pUserData[pdev->classId] = fops;
/* Exit with no error code */
return (uint8_t)USBD_OK;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO | D://workCode//uploadProject\stm32_mw_usb_device\Class\VIDEO\Src\usbd_video_if_template.c | /**
******************************************************************************
* @file usbd_video_if_template.c
* @author MCD Application Team
* @brief Template file for Video Interface application layer functions
******************************************************************************
* @attention
*
* Copyright (c) 2020 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_video_if_template.h"
/* Include you image binary file here
Binary image template shall provide:
- tImagesList: table containing pointers to all images
- tImagesSizes: table containing sizes of each image respectively
- img_count: global image counter variable
- IMG_NBR: Total image number
To generate such file, it is possible to use tools converting video to MJPEG then to JPEG images.
*/
/* #include "img_bin.h" */
/* USER CODE BEGIN INCLUDE */
/* USER CODE END INCLUDE */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
uint8_t img_count;
/* USER CODE END PV */
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @brief Usb device library.
* @{
*/
/** @addtogroup USBD_VIDEO_IF
* @{
*/
/** @defgroup USBD_VIDEO_IF_Private_TypesDefinitions
* @brief Private types.
* @{
*/
/* USER CODE BEGIN PRIVATE_TYPES */
/* USER CODE END PRIVATE_TYPES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Private_Defines
* @brief Private defines.
* @{
*/
/* USER CODE BEGIN PRIVATE_DEFINES */
/* USER CODE END PRIVATE_DEFINES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Private_Macros
* @brief Private macros.
* @{
*/
/* USER CODE BEGIN PRIVATE_MACRO */
/* USER CODE END PRIVATE_MACRO */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Private_Variables
* @brief Private variables.
* @{
*/
/* USER CODE BEGIN PRIVATE_VARIABLES */
/* USER CODE END PRIVATE_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Exported_Variables
* @brief Public variables.
* @{
*/
/* USER CODE BEGIN EXPORTED_VARIABLES */
/* USER CODE END EXPORTED_VARIABLES */
/**
* @}
*/
/** @defgroup USBD_VIDEO_IF_Private_FunctionPrototypes
* @brief Private functions declaration.
* @{
*/
static int8_t VIDEO_Itf_Init(void);
static int8_t VIDEO_Itf_DeInit(void);
static int8_t VIDEO_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length);
static int8_t VIDEO_Itf_Data(uint8_t **pbuf, uint16_t *psize, uint16_t *pcktidx);
/* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */
/* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */
/**
* @}
*/
USBD_VIDEO_ItfTypeDef USBD_VIDEO_fops_FS =
{
VIDEO_Itf_Init,
VIDEO_Itf_DeInit,
VIDEO_Itf_Control,
VIDEO_Itf_Data,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the VIDEO media low layer over USB FS IP
* @param VIDEOFreq: VIDEO frequency used to play the VIDEO stream.
* @param Volume: Initial volume level (from 0 (Mute) to 100 (Max))
* @param options: Reserved for future use
* @retval USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t VIDEO_Itf_Init(void)
{
/*
Add your initialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_DeInit
* DeInitializes the UVC media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t VIDEO_Itf_DeInit(void)
{
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_Control
* Manage the UVC class requests
* @param Cmd: Command code
* @param Buf: Buffer containing command data (request parameters)
* @param Len: Number of data to be sent (in bytes)
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t VIDEO_Itf_Control(uint8_t cmd, uint8_t *pbuf, uint16_t length)
{
UNUSED(cmd);
UNUSED(pbuf);
UNUSED(length);
return (0);
}
/**
* @brief TEMPLATE_Data
* Manage the UVC data packets
* @param pbuf: pointer to the buffer data to be filled
* @param psize: pointer tot he current packet size to be filled
* @param pcktidx: pointer to the current packet index in the current image
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t VIDEO_Itf_Data(uint8_t **pbuf, uint16_t *psize, uint16_t *pcktidx)
{
/*
Implementation of this function is mandatory to provide the video data to the USB video class
This function shall parse the MJPEG images and provide each time the buffer packet relative to
current packet index and its size.
If the packet is the first packet in the current MJPEG image, then packet size shall be zero and
the pbuf is ignored and pcktidx shall be zero.
Below is typical implementation of this function based on a binary image template.
Binary image template shall provide:
- tImagesList: table containing pointers to all images
- tImagesSizes: table containing sizes of each image respectively
- img_count: global image counter variable
- IMG_NBR: Total image number
To generate such file, it is possible to use tools converting video to MJPEG then to JPEG images.
*/
const uint8_t *(*ImagePtr) = tImagesList;
uint32_t packet_count = (tImagesSizes[img_count]) / ((UVC_PACKET_SIZE - (UVC_HEADER_PACKET_CNT * 2U)));
uint32_t packet_remainder = (tImagesSizes[img_count]) % ((UVC_PACKET_SIZE - (UVC_HEADER_PACKET_CNT * 2U)));
static uint8_t packet_index = 0U;
/* Check if end of current image has been reached */
if (packet_index < packet_count)
{
/* Set the current packet size */
*psize = (uint16_t)UVC_PACKET_SIZE;
/* Get the pointer to the next packet to be transmitted */
*pbuf = (uint8_t *)(*(ImagePtr + img_count) + \
(packet_index * ((uint16_t)(UVC_PACKET_SIZE - (UVC_HEADER_PACKET_CNT * 2U)))));
}
else if ((packet_index == packet_count))
{
if (packet_remainder != 0U)
{
/* Get the pointer to the next packet to be transmitted */
*pbuf = (uint8_t *)(*(ImagePtr + img_count) + \
(packet_index * ((uint16_t)(UVC_PACKET_SIZE - (UVC_HEADER_PACKET_CNT * 2U)))));
/* Set the current packet size */
*psize = (uint16_t)(packet_remainder + (UVC_HEADER_PACKET_CNT * 2U));
}
else
{
packet_index++;
/* New image to be started, send only the packet header */
*psize = 2;
}
}
else
{
/* New image to be started, send only the packet header */
*psize = 2;
}
/* Update the packet index */
*pcktidx = packet_index;
/* Increment the packet count and check if it reached the end of current image buffer */
if (packet_index++ >= (packet_count + 1U))
{
/* Reset the packet count to zero */
packet_index = 0U;
/* Move to the next image in the images table */
img_count++;
USBD_Delay(USBD_VIDEO_IMAGE_LAPS);
/* Check if images count has been reached, then reset to zero (go back to first image in circular loop) */
if (img_count == IMG_NBR)
{
img_count = 0U;
}
}
return (0);
}
/* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */
/* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_conf_template.h | /**
******************************************************************************
* @file usbd_conf_template.h
* @author MCD Application Team
* @brief Header file for the usbd_conf_template.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_CONF_TEMPLATE_H
#define __USBD_CONF_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32fxxx.h" /* replace 'stm32xxx' with your HAL driver header filename, ex: stm32f4xx.h */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CONF
* @brief USB device low level driver configuration file
* @{
*/
/** @defgroup USBD_CONF_Exported_Defines
* @{
*/
#define USBD_MAX_NUM_INTERFACES 1U
#define USBD_MAX_NUM_CONFIGURATION 1U
#define USBD_MAX_STR_DESC_SIZ 0x100U
#define USBD_SELF_POWERED 1U
#define USBD_DEBUG_LEVEL 2U
/* #define USBD_USER_REGISTER_CALLBACK 1U */
/* ECM, RNDIS, DFU Class Config */
#define USBD_SUPPORT_USER_STRING_DESC 1U
/* BillBoard Class Config */
#define USBD_CLASS_USER_STRING_DESC 1U
#define USBD_CLASS_BOS_ENABLED 1U
#define USB_BB_MAX_NUM_ALT_MODE 0x2U
/* MSC Class Config */
#define MSC_MEDIA_PACKET 8192U
/* CDC Class Config */
#define USBD_CDC_INTERVAL 2000U
/* DFU Class Config */
/* #define USBD_DFU_VENDOR_CMD_ENABLED 1U */
/* #define USBD_DFU_VENDOR_EXIT_ENABLED 1U */
#define USBD_DFU_MAX_ITF_NUM 1U
#define USBD_DFU_XFERS_IZE 1024U
/* AUDIO Class Config */
#define USBD_AUDIO_FREQ 22100U
/* CustomHID Class Config */
#define CUSTOM_HID_HS_BINTERVAL 0x05U
#define CUSTOM_HID_FS_BINTERVAL 0x05U
#define USBD_CUSTOMHID_OUTREPORT_BUF_SIZE 0x02U
#define USBD_CUSTOM_HID_REPORT_DESC_SIZE 163U
/* #define USBD_CUSTOMHID_CTRL_REQ_GET_REPORT_ENABLED */
/* #define USBD_CUSTOMHID_OUT_PREPARE_RECEIVE_DISABLED */
/* #define USBD_CUSTOMHID_EP0_OUT_PREPARE_RECEIVE_DISABLED */
/* #define USBD_CUSTOMHID_CTRL_REQ_COMPLETE_CALLBACK_ENABLED */
/* VIDEO Class Config */
#define UVC_1_1 /* #define UVC_1_0 */
/* To be used only with YUY2 and NV12 Video format, shouldn't be defined for MJPEG format */
#define USBD_UVC_FORMAT_UNCOMPRESSED
#ifdef USBD_UVC_FORMAT_UNCOMPRESSED
#define UVC_BITS_PER_PIXEL 12U
#define UVC_UNCOMPRESSED_GUID UVC_GUID_NV12 /* UVC_GUID_YUY2 */
/* refer to Table 3-18 Color Matching Descriptor video class v1.1 */
#define UVC_COLOR_PRIMARIE 0x01U
#define UVC_TFR_CHARACTERISTICS 0x01U
#define UVC_MATRIX_COEFFICIENTS 0x04U
#endif /* USBD_UVC_FORMAT_UNCOMPRESSED */
/* Video Stream frame width and height */
#define UVC_WIDTH 176U
#define UVC_HEIGHT 144U
/* bEndpointAddress in Endpoint Descriptor */
#define UVC_IN_EP 0x81U
#define UVC_CAM_FPS_FS 10U
#define UVC_CAM_FPS_HS 5U
#define UVC_ISO_FS_MPS 512U
#define UVC_ISO_HS_MPS 512U
#define UVC_PACKET_SIZE UVC_ISO_FS_MPS
/* To be used with Device Only IP supporting double buffer mode */
/* #define UVC_HEADER_PACKET_CNT 0x02U */
/* #define UVC_PACKET_SIZE (UVC_ISO_FS_MPS * UVC_HEADER_PACKET_CNT) */
#define UVC_MAX_FRAME_SIZE (UVC_WIDTH * UVC_HEIGHT * 16U / 8U)
/** @defgroup USBD_Exported_Macros
* @{
*/
/* Memory management macros make sure to use static memory allocation */
/** Alias for memory allocation. */
#define USBD_malloc (void *)USBD_static_malloc
/** Alias for memory release. */
#define USBD_free USBD_static_free
/** Alias for memory set. */
#define USBD_memset memset
/** Alias for memory copy. */
#define USBD_memcpy memcpy
/** Alias for delay. */
#define USBD_Delay HAL_Delay
/* DEBUG macros */
#if (USBD_DEBUG_LEVEL > 0U)
#define USBD_UsrLog(...) do { \
printf(__VA_ARGS__); \
printf("\n"); \
} while (0)
#else
#define USBD_UsrLog(...) do {} while (0)
#endif /* (USBD_DEBUG_LEVEL > 0U) */
#if (USBD_DEBUG_LEVEL > 1U)
#define USBD_ErrLog(...) do { \
printf("ERROR: ") ; \
printf(__VA_ARGS__); \
printf("\n"); \
} while (0)
#else
#define USBD_ErrLog(...) do {} while (0)
#endif /* (USBD_DEBUG_LEVEL > 1U) */
#if (USBD_DEBUG_LEVEL > 2U)
#define USBD_DbgLog(...) do { \
printf("DEBUG : ") ; \
printf(__VA_ARGS__); \
printf("\n"); \
} while (0)
#else
#define USBD_DbgLog(...) do {} while (0)
#endif /* (USBD_DEBUG_LEVEL > 2U) */
/**
* @}
*/
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CONF_Exported_FunctionsPrototype
* @{
*/
/* Exported functions -------------------------------------------------------*/
void *USBD_static_malloc(uint32_t size);
void USBD_static_free(void *p);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CONF_TEMPLATE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_core.h | /**
******************************************************************************
* @file usbd_core.h
* @author MCD Application Team
* @brief Header file for usbd_core.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_CORE_H
#define __USBD_CORE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_conf.h"
#include "usbd_def.h"
#include "usbd_ioreq.h"
#include "usbd_ctlreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CORE
* @brief This file is the Header file for usbd_core.c file
* @{
*/
/** @defgroup USBD_CORE_Exported_Defines
* @{
*/
#ifndef USBD_DEBUG_LEVEL
#define USBD_DEBUG_LEVEL 0U
#endif /* USBD_DEBUG_LEVEL */
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
#define USBD_SOF USBD_LL_SOF
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id);
USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_Start(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_Stop(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass);
#if (USBD_USER_REGISTER_CALLBACK == 1U)
USBD_StatusTypeDef USBD_RegisterDevStateCallback(USBD_HandleTypeDef *pdev, USBD_DevStateCallbackTypeDef pUserCallback);
#endif /* USBD_USER_REGISTER_CALLBACK */
#ifdef USE_USBD_COMPOSITE
USBD_StatusTypeDef USBD_RegisterClassComposite(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass,
USBD_CompositeClassTypeDef classtype, uint8_t *EpAddr);
USBD_StatusTypeDef USBD_UnRegisterClassComposite(USBD_HandleTypeDef *pdev);
uint8_t USBD_CoreGetEPAdd(USBD_HandleTypeDef *pdev, uint8_t ep_dir, uint8_t ep_type, uint8_t ClassId);
#endif /* USE_USBD_COMPOSITE */
uint8_t USBD_CoreFindIF(USBD_HandleTypeDef *pdev, uint8_t index);
uint8_t USBD_CoreFindEP(USBD_HandleTypeDef *pdev, uint8_t index);
USBD_StatusTypeDef USBD_RunTestMode(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx);
USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup);
USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev, uint8_t epnum, uint8_t *pdata);
USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev, uint8_t epnum, uint8_t *pdata);
USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed);
USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum);
USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev);
/* USBD Low Level Driver */
USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t ep_type, uint16_t ep_mps);
USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev, uint8_t dev_addr);
USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t *pbuf, uint32_t size);
USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t *pbuf, uint32_t size);
#ifdef USBD_HS_TESTMODE_ENABLE
USBD_StatusTypeDef USBD_LL_SetTestMode(USBD_HandleTypeDef *pdev, uint8_t testmode);
#endif /* USBD_HS_TESTMODE_ENABLE */
uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
void USBD_LL_Delay(uint32_t Delay);
void *USBD_GetEpDesc(uint8_t *pConfDesc, uint8_t EpAddr);
USBD_DescHeaderTypeDef *USBD_GetNextDesc(uint8_t *pbuf, uint16_t *ptr);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_CORE_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_ctlreq.h | /**
******************************************************************************
* @file usbd_req.h
* @author MCD Application Team
* @brief Header file for the usbd_req.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USB_REQUEST_H
#define __USB_REQUEST_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_REQ
* @brief header file for the usbd_req.c file
* @{
*/
/** @defgroup USBD_REQ_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_StdDevReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
USBD_StatusTypeDef USBD_StdItfReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
USBD_StatusTypeDef USBD_StdEPReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
void USBD_CtlError(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata);
void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_REQUEST_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_def.h | /**
******************************************************************************
* @file usbd_def.h
* @author MCD Application Team
* @brief General defines for the usb device library
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_DEF_H
#define __USBD_DEF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_conf.h"
/** @addtogroup STM32_USBD_DEVICE_LIBRARY
* @{
*/
/** @defgroup USB_DEF
* @brief general defines for the usb device library file
* @{
*/
/** @defgroup USB_DEF_Exported_Defines
* @{
*/
#ifndef NULL
#define NULL 0U
#endif /* NULL */
#ifndef USBD_MAX_NUM_INTERFACES
#define USBD_MAX_NUM_INTERFACES 1U
#endif /* USBD_MAX_NUM_CONFIGURATION */
#ifndef USBD_MAX_NUM_CONFIGURATION
#define USBD_MAX_NUM_CONFIGURATION 1U
#endif /* USBD_MAX_NUM_CONFIGURATION */
#ifdef USE_USBD_COMPOSITE
#ifndef USBD_MAX_SUPPORTED_CLASS
#define USBD_MAX_SUPPORTED_CLASS 4U
#endif /* USBD_MAX_SUPPORTED_CLASS */
#else
#ifndef USBD_MAX_SUPPORTED_CLASS
#define USBD_MAX_SUPPORTED_CLASS 1U
#endif /* USBD_MAX_SUPPORTED_CLASS */
#endif /* USE_USBD_COMPOSITE */
#ifndef USBD_MAX_CLASS_ENDPOINTS
#define USBD_MAX_CLASS_ENDPOINTS 5U
#endif /* USBD_MAX_CLASS_ENDPOINTS */
#ifndef USBD_MAX_CLASS_INTERFACES
#define USBD_MAX_CLASS_INTERFACES 5U
#endif /* USBD_MAX_CLASS_INTERFACES */
#ifndef USBD_LPM_ENABLED
#define USBD_LPM_ENABLED 0U
#endif /* USBD_LPM_ENABLED */
#ifndef USBD_SELF_POWERED
#define USBD_SELF_POWERED 1U
#endif /*USBD_SELF_POWERED */
#ifndef USBD_MAX_POWER
#define USBD_MAX_POWER 0x32U /* 100 mA */
#endif /* USBD_MAX_POWER */
#ifndef USBD_SUPPORT_USER_STRING_DESC
#define USBD_SUPPORT_USER_STRING_DESC 0U
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#ifndef USBD_CLASS_USER_STRING_DESC
#define USBD_CLASS_USER_STRING_DESC 0U
#endif /* USBD_CLASS_USER_STRING_DESC */
#define USB_LEN_DEV_QUALIFIER_DESC 0x0AU
#define USB_LEN_DEV_DESC 0x12U
#define USB_LEN_CFG_DESC 0x09U
#define USB_LEN_IF_DESC 0x09U
#define USB_LEN_EP_DESC 0x07U
#define USB_LEN_OTG_DESC 0x03U
#define USB_LEN_LANGID_STR_DESC 0x04U
#define USB_LEN_OTHER_SPEED_DESC_SIZ 0x09U
#define USBD_IDX_LANGID_STR 0x00U
#define USBD_IDX_MFC_STR 0x01U
#define USBD_IDX_PRODUCT_STR 0x02U
#define USBD_IDX_SERIAL_STR 0x03U
#define USBD_IDX_CONFIG_STR 0x04U
#define USBD_IDX_INTERFACE_STR 0x05U
#define USB_REQ_TYPE_STANDARD 0x00U
#define USB_REQ_TYPE_CLASS 0x20U
#define USB_REQ_TYPE_VENDOR 0x40U
#define USB_REQ_TYPE_MASK 0x60U
#define USB_REQ_RECIPIENT_DEVICE 0x00U
#define USB_REQ_RECIPIENT_INTERFACE 0x01U
#define USB_REQ_RECIPIENT_ENDPOINT 0x02U
#define USB_REQ_RECIPIENT_MASK 0x03U
#define USB_REQ_GET_STATUS 0x00U
#define USB_REQ_CLEAR_FEATURE 0x01U
#define USB_REQ_SET_FEATURE 0x03U
#define USB_REQ_SET_ADDRESS 0x05U
#define USB_REQ_GET_DESCRIPTOR 0x06U
#define USB_REQ_SET_DESCRIPTOR 0x07U
#define USB_REQ_GET_CONFIGURATION 0x08U
#define USB_REQ_SET_CONFIGURATION 0x09U
#define USB_REQ_GET_INTERFACE 0x0AU
#define USB_REQ_SET_INTERFACE 0x0BU
#define USB_REQ_SYNCH_FRAME 0x0CU
#define USB_DESC_TYPE_DEVICE 0x01U
#define USB_DESC_TYPE_CONFIGURATION 0x02U
#define USB_DESC_TYPE_STRING 0x03U
#define USB_DESC_TYPE_INTERFACE 0x04U
#define USB_DESC_TYPE_ENDPOINT 0x05U
#define USB_DESC_TYPE_DEVICE_QUALIFIER 0x06U
#define USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION 0x07U
#define USB_DESC_TYPE_IAD 0x0BU
#define USB_DESC_TYPE_BOS 0x0FU
#define USB_CONFIG_REMOTE_WAKEUP 0x02U
#define USB_CONFIG_SELF_POWERED 0x01U
#define USB_FEATURE_EP_HALT 0x00U
#define USB_FEATURE_REMOTE_WAKEUP 0x01U
#define USB_FEATURE_TEST_MODE 0x02U
#define USB_DEVICE_CAPABITY_TYPE 0x10U
#define USB_CONF_DESC_SIZE 0x09U
#define USB_IF_DESC_SIZE 0x09U
#define USB_EP_DESC_SIZE 0x07U
#define USB_IAD_DESC_SIZE 0x08U
#define USB_HS_MAX_PACKET_SIZE 512U
#define USB_FS_MAX_PACKET_SIZE 64U
#define USB_MAX_EP0_SIZE 64U
/* Device Status */
#define USBD_STATE_DEFAULT 0x01U
#define USBD_STATE_ADDRESSED 0x02U
#define USBD_STATE_CONFIGURED 0x03U
#define USBD_STATE_SUSPENDED 0x04U
/* EP0 State */
#define USBD_EP0_IDLE 0x00U
#define USBD_EP0_SETUP 0x01U
#define USBD_EP0_DATA_IN 0x02U
#define USBD_EP0_DATA_OUT 0x03U
#define USBD_EP0_STATUS_IN 0x04U
#define USBD_EP0_STATUS_OUT 0x05U
#define USBD_EP0_STALL 0x06U
#define USBD_EP_TYPE_CTRL 0x00U
#define USBD_EP_TYPE_ISOC 0x01U
#define USBD_EP_TYPE_BULK 0x02U
#define USBD_EP_TYPE_INTR 0x03U
#ifdef USE_USBD_COMPOSITE
#define USBD_EP_IN 0x80U
#define USBD_EP_OUT 0x00U
#define USBD_FUNC_DESCRIPTOR_TYPE 0x24U
#define USBD_DESC_SUBTYPE_ACM 0x0FU
#define USBD_DESC_ECM_BCD_LOW 0x00U
#define USBD_DESC_ECM_BCD_HIGH 0x10U
#endif /* USE_USBD_COMPOSITE */
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_TypesDefinitions
* @{
*/
typedef struct usb_setup_req
{
uint8_t bmRequest;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} USBD_SetupReqTypedef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} __PACKED USBD_ConfigDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumDeviceCaps;
} USBD_BosDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} __PACKED USBD_EpDescTypeDef;
typedef struct
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
} USBD_DescHeaderTypeDef;
struct _USBD_HandleTypeDef;
typedef struct _Device_cb
{
uint8_t (*Init)(struct _USBD_HandleTypeDef *pdev, uint8_t cfgidx);
uint8_t (*DeInit)(struct _USBD_HandleTypeDef *pdev, uint8_t cfgidx);
/* Control Endpoints*/
uint8_t (*Setup)(struct _USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
uint8_t (*EP0_TxSent)(struct _USBD_HandleTypeDef *pdev);
uint8_t (*EP0_RxReady)(struct _USBD_HandleTypeDef *pdev);
/* Class Specific Endpoints*/
uint8_t (*DataIn)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*DataOut)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*SOF)(struct _USBD_HandleTypeDef *pdev);
uint8_t (*IsoINIncomplete)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t (*IsoOUTIncomplete)(struct _USBD_HandleTypeDef *pdev, uint8_t epnum);
uint8_t *(*GetHSConfigDescriptor)(uint16_t *length);
uint8_t *(*GetFSConfigDescriptor)(uint16_t *length);
uint8_t *(*GetOtherSpeedConfigDescriptor)(uint16_t *length);
uint8_t *(*GetDeviceQualifierDescriptor)(uint16_t *length);
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
uint8_t *(*GetUsrStrDescriptor)(struct _USBD_HandleTypeDef *pdev, uint8_t index, uint16_t *length);
#endif /* USBD_SUPPORT_USER_STRING_DESC */
} USBD_ClassTypeDef;
/* Following USB Device Speed */
typedef enum
{
USBD_SPEED_HIGH = 0U,
USBD_SPEED_FULL = 1U,
USBD_SPEED_LOW = 2U,
} USBD_SpeedTypeDef;
/* Following USB Device status */
typedef enum
{
USBD_OK = 0U,
USBD_BUSY,
USBD_EMEM,
USBD_FAIL,
} USBD_StatusTypeDef;
/* USB Device descriptors structure */
typedef struct
{
uint8_t *(*GetDeviceDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetLangIDStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetManufacturerStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetProductStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetSerialStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetConfigurationStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *(*GetInterfaceStrDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
#if (USBD_CLASS_USER_STRING_DESC == 1)
uint8_t *(*GetUserStrDescriptor)(USBD_SpeedTypeDef speed, uint8_t idx, uint16_t *length);
#endif /* USBD_CLASS_USER_STRING_DESC */
#if ((USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1))
uint8_t *(*GetBOSDescriptor)(USBD_SpeedTypeDef speed, uint16_t *length);
#endif /* (USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1) */
} USBD_DescriptorsTypeDef;
/* USB Device handle structure */
typedef struct
{
uint32_t status;
uint32_t total_length;
uint32_t rem_length;
uint32_t maxpacket;
uint16_t is_used;
uint16_t bInterval;
} USBD_EndpointTypeDef;
#ifdef USE_USBD_COMPOSITE
typedef enum
{
CLASS_TYPE_NONE = 0,
CLASS_TYPE_HID = 1,
CLASS_TYPE_CDC = 2,
CLASS_TYPE_MSC = 3,
CLASS_TYPE_DFU = 4,
CLASS_TYPE_CHID = 5,
CLASS_TYPE_AUDIO = 6,
CLASS_TYPE_ECM = 7,
CLASS_TYPE_RNDIS = 8,
CLASS_TYPE_MTP = 9,
CLASS_TYPE_VIDEO = 10,
CLASS_TYPE_PRINTER = 11,
CLASS_TYPE_CCID = 12,
} USBD_CompositeClassTypeDef;
/* USB Device handle structure */
typedef struct
{
uint8_t add;
uint8_t type;
uint8_t size;
uint8_t is_used;
} USBD_EPTypeDef;
/* USB Device handle structure */
typedef struct
{
USBD_CompositeClassTypeDef ClassType;
uint32_t ClassId;
uint32_t Active;
uint32_t NumEps;
USBD_EPTypeDef Eps[USBD_MAX_CLASS_ENDPOINTS];
uint8_t *EpAdd;
uint32_t NumIf;
uint8_t Ifs[USBD_MAX_CLASS_INTERFACES];
uint32_t CurrPcktSze;
} USBD_CompositeElementTypeDef;
#endif /* USE_USBD_COMPOSITE */
/* USB Device handle structure */
typedef struct _USBD_HandleTypeDef
{
uint8_t id;
uint32_t dev_config;
uint32_t dev_default_config;
uint32_t dev_config_status;
USBD_SpeedTypeDef dev_speed;
USBD_EndpointTypeDef ep_in[16];
USBD_EndpointTypeDef ep_out[16];
__IO uint32_t ep0_state;
uint32_t ep0_data_len;
__IO uint8_t dev_state;
__IO uint8_t dev_old_state;
uint8_t dev_address;
uint8_t dev_connection_status;
uint8_t dev_test_mode;
uint32_t dev_remote_wakeup;
uint8_t ConfIdx;
USBD_SetupReqTypedef request;
USBD_DescriptorsTypeDef *pDesc;
USBD_ClassTypeDef *pClass[USBD_MAX_SUPPORTED_CLASS];
void *pClassData;
void *pClassDataCmsit[USBD_MAX_SUPPORTED_CLASS];
void *pUserData[USBD_MAX_SUPPORTED_CLASS];
void *pData;
void *pBosDesc;
void *pConfDesc;
uint32_t classId;
uint32_t NumClasses;
#ifdef USE_USBD_COMPOSITE
USBD_CompositeElementTypeDef tclasslist[USBD_MAX_SUPPORTED_CLASS];
#endif /* USE_USBD_COMPOSITE */
#if (USBD_USER_REGISTER_CALLBACK == 1U)
void (* DevStateCallback)(uint8_t dev_state, uint8_t cfgidx); /*!< User Notification callback */
#endif /* USBD_USER_REGISTER_CALLBACK */
} USBD_HandleTypeDef;
#if (USBD_USER_REGISTER_CALLBACK == 1U)
typedef void (*USBD_DevStateCallbackTypeDef)(uint8_t dev_state, uint8_t cfgidx); /*!< pointer to User callback function */
#endif /* USBD_USER_REGISTER_CALLBACK */
/* USB Device endpoint direction */
typedef enum
{
OUT = 0x00,
IN = 0x80,
} USBD_EPDirectionTypeDef;
typedef enum
{
NETWORK_CONNECTION = 0x00,
RESPONSE_AVAILABLE = 0x01,
CONNECTION_SPEED_CHANGE = 0x2A
} USBD_CDC_NotifCodeTypeDef;
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_Macros
* @{
*/
__STATIC_INLINE uint16_t SWAPBYTE(uint8_t *addr)
{
uint16_t _SwapVal;
uint16_t _Byte1;
uint16_t _Byte2;
uint8_t *_pbuff = addr;
_Byte1 = *(uint8_t *)_pbuff;
_pbuff++;
_Byte2 = *(uint8_t *)_pbuff;
_SwapVal = (_Byte2 << 8) | _Byte1;
return _SwapVal;
}
#ifndef LOBYTE
#define LOBYTE(x) ((uint8_t)((x) & 0x00FFU))
#endif /* LOBYTE */
#ifndef HIBYTE
#define HIBYTE(x) ((uint8_t)(((x) & 0xFF00U) >> 8U))
#endif /* HIBYTE */
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif /* MIN */
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif /* MAX */
#if defined ( __GNUC__ )
#ifndef __weak
#define __weak __attribute__((weak))
#endif /* __weak */
#ifndef __packed
#define __packed __attribute__((__packed__))
#endif /* __packed */
#endif /* __GNUC__ */
/* In HS mode and when the DMA is used, all variables and data structures dealing
with the DMA during the transaction process should be 4-bytes aligned */
#if defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */
#ifndef __ALIGN_END
#define __ALIGN_END __attribute__ ((aligned (4U)))
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#define __ALIGN_BEGIN
#endif /* __ALIGN_BEGIN */
#else
#ifndef __ALIGN_END
#define __ALIGN_END
#endif /* __ALIGN_END */
#ifndef __ALIGN_BEGIN
#if defined (__CC_ARM) /* ARM Compiler */
#define __ALIGN_BEGIN __align(4U)
#elif defined (__ICCARM__) /* IAR Compiler */
#define __ALIGN_BEGIN
#endif /* __CC_ARM */
#endif /* __ALIGN_BEGIN */
#endif /* __GNUC__ */
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_DEF_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_DEF_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_desc_template.h | /**
******************************************************************************
* @file usbd_desc_template.h
* @author MCD Application Team
* @brief Header for usbd_desc_template.c module
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_DESC_TEMPLATE_H
#define __USBD_DESC_TEMPLATE_H
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
#define DEVICE_ID1 (UID_BASE)
#define DEVICE_ID2 (UID_BASE + 0x4U)
#define DEVICE_ID3 (UID_BASE + 0x8U)
/*
* USB Billboard Class USER string desc Defines Template
* index should start form 0x10 to avoid using the reserved device string desc indexes
*/
#if (USBD_CLASS_USER_STRING_DESC == 1)
#define USBD_BB_IF_STRING_INDEX 0x10U
#define USBD_BB_URL_STRING_INDEX 0x11U
#define USBD_BB_ALTMODE0_STRING_INDEX 0x12U
#define USBD_BB_ALTMODE1_STRING_INDEX 0x13U
/* Add Specific USER string Desc */
#define USBD_BB_IF_STR_DESC (uint8_t *)"STM32 BillBoard Interface"
#define USBD_BB_URL_STR_DESC (uint8_t *)"www.st.com"
#define USBD_BB_ALTMODE0_STR_DESC (uint8_t *)"STM32 Alternate0 Mode"
#define USBD_BB_ALTMODE1_STR_DESC (uint8_t *)"STM32 Alternate1 Mode"
#endif /* USBD_CLASS_USER_STRING_DESC */
#define USB_SIZ_STRING_SERIAL 0x1AU
#if (USBD_LPM_ENABLED == 1)
#define USB_SIZ_BOS_DESC 0x0CU
#elif (USBD_CLASS_BOS_ENABLED == 1)
#define USB_SIZ_BOS_DESC 0x5DU
#endif /* USBD_LPM_ENABLED */
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
extern USBD_DescriptorsTypeDef XXX_Desc; /* Replace 'XXX_Desc' with your active USB device class, ex: HID_Desc */
#endif /* __USBD_DESC_TEMPLATE_H*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Inc\usbd_ioreq.h | /**
******************************************************************************
* @file usbd_ioreq.h
* @author MCD Application Team
* @brief Header file for the usbd_ioreq.c file
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 __USBD_IOREQ_H
#define __USBD_IOREQ_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
#include "usbd_core.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_IOREQ
* @brief header file for the usbd_ioreq.c file
* @{
*/
/** @defgroup USBD_IOREQ_Exported_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Exported_FunctionsPrototype
* @{
*/
USBD_StatusTypeDef USBD_CtlSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlContinueSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlPrepareRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlContinueRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len);
USBD_StatusTypeDef USBD_CtlSendStatus(USBD_HandleTypeDef *pdev);
USBD_StatusTypeDef USBD_CtlReceiveStatus(USBD_HandleTypeDef *pdev);
uint32_t USBD_GetRxCount(USBD_HandleTypeDef *pdev, uint8_t ep_addr);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USBD_IOREQ_H */
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Src\usbd_conf_template.c | /**
******************************************************************************
* @file usbd_conf_template.c
* @author MCD Application Team
* @brief USB Device configuration and interface file
* This template should be copied to the user folder,
* renamed and customized following user needs.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_core.h"
#include "usbd_hid.h" /* Include class header file */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the Low Level portion of the Device driver.
* @param pdev: Device handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief De-Initializes the Low Level portion of the Device driver.
* @param pdev: Device handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief Starts the Low Level portion of the Device driver.
* @param pdev: Device handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief Stops the Low Level portion of the Device driver.
* @param pdev: Device handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev)
{
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief Opens an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @param ep_type: Endpoint Type
* @param ep_mps: Endpoint Max Packet Size
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t ep_type, uint16_t ep_mps)
{
UNUSED(pdev);
UNUSED(ep_addr);
UNUSED(ep_type);
UNUSED(ep_mps);
return USBD_OK;
}
/**
* @brief Closes an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return USBD_OK;
}
/**
* @brief Flushes an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return USBD_OK;
}
/**
* @brief Sets a Stall condition on an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return USBD_OK;
}
/**
* @brief Clears a Stall condition on an endpoint of the Low Level Driver.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev,
uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return USBD_OK;
}
/**
* @brief Returns Stall condition.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval Stall (1: Yes, 0: No)
*/
uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return 0U;
}
/**
* @brief Assigns a USB address to the device.
* @param pdev: Device handle
* @param dev_addr: Endpoint Number
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev,
uint8_t dev_addr)
{
UNUSED(pdev);
UNUSED(dev_addr);
return USBD_OK;
}
/**
* @brief Transmits data over an endpoint.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @param pbuf: Pointer to data to be sent
* @param size: Data size
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr,
uint8_t *pbuf, uint32_t size)
{
UNUSED(pdev);
UNUSED(ep_addr);
UNUSED(pbuf);
UNUSED(size);
return USBD_OK;
}
/**
* @brief Prepares an endpoint for reception.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @param pbuf: Pointer to data to be received
* @param size: Data size
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev,
uint8_t ep_addr, uint8_t *pbuf,
uint32_t size)
{
UNUSED(pdev);
UNUSED(ep_addr);
UNUSED(pbuf);
UNUSED(size);
return USBD_OK;
}
/**
* @brief Returns the last transferred packet size.
* @param pdev: Device handle
* @param ep_addr: Endpoint Number
* @retval Received Data Size
*/
uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
UNUSED(pdev);
UNUSED(ep_addr);
return 0U;
}
#ifdef USBD_HS_TESTMODE_ENABLE
/**
* @brief Set High speed Test mode.
* @param pdev: Device handle
* @param testmode: test mode
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_LL_SetTestMode(USBD_HandleTypeDef *pdev, uint8_t testmode)
{
UNUSED(pdev);
UNUSED(testmode);
return USBD_OK;
}
#endif /* USBD_HS_TESTMODE_ENABLE */
/**
* @brief Static single allocation.
* @param size: Size of allocated memory
* @retval None
*/
void *USBD_static_malloc(uint32_t size)
{
UNUSED(size);
static uint32_t mem[(sizeof(USBD_HID_HandleTypeDef) / 4) + 1]; /* On 32-bit boundary */
return mem;
}
/**
* @brief Dummy memory free
* @param p: Pointer to allocated memory address
* @retval None
*/
void USBD_static_free(void *p)
{
UNUSED(p);
}
/**
* @brief Delays routine for the USB Device Library.
* @param Delay: Delay in ms
* @retval None
*/
void USBD_LL_Delay(uint32_t Delay)
{
UNUSED(Delay);
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Src\usbd_core.c | /**
******************************************************************************
* @file usbd_core.c
* @author MCD Application Team
* @brief This file provides all the USBD core functions.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_core.h"
#ifdef USE_USBD_COMPOSITE
#include "usbd_composite_builder.h"
#endif /* USE_USBD_COMPOSITE */
/** @addtogroup STM32_USBD_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CORE
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CORE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Functions
* @{
*/
/**
* @brief USBD_Init
* Initializes the device stack and load the class driver
* @param pdev: device instance
* @param pdesc: Descriptor structure address
* @param id: Low level core index
* @retval None
*/
USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev,
USBD_DescriptorsTypeDef *pdesc, uint8_t id)
{
USBD_StatusTypeDef ret;
/* Check whether the USB Host handle is valid */
if (pdev == NULL)
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Invalid Device handle");
#endif /* (USBD_DEBUG_LEVEL > 1U) */
return USBD_FAIL;
}
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Unlink previous class*/
pdev->pClass[i] = NULL;
pdev->pUserData[i] = NULL;
/* Set class as inactive */
pdev->tclasslist[i].Active = 0;
pdev->NumClasses = 0;
pdev->classId = 0;
}
#else
/* Unlink previous class*/
pdev->pClass[0] = NULL;
pdev->pUserData[0] = NULL;
#endif /* USE_USBD_COMPOSITE */
pdev->pConfDesc = NULL;
/* Assign USBD Descriptors */
if (pdesc != NULL)
{
pdev->pDesc = pdesc;
}
/* Set Device initial State */
pdev->dev_state = USBD_STATE_DEFAULT;
pdev->id = id;
/* Initialize low level driver */
ret = USBD_LL_Init(pdev);
return ret;
}
/**
* @brief USBD_DeInit
* Re-Initialize the device library
* @param pdev: device instance
* @retval status: status
*/
USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev)
{
USBD_StatusTypeDef ret;
/* Disconnect the USB Device */
(void)USBD_LL_Stop(pdev);
/* Set Default State */
pdev->dev_state = USBD_STATE_DEFAULT;
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Free Class Resources */
pdev->pClass[i]->DeInit(pdev, (uint8_t)pdev->dev_config);
}
}
}
#else
/* Free Class Resources */
if (pdev->pClass[0] != NULL)
{
pdev->pClass[0]->DeInit(pdev, (uint8_t)pdev->dev_config);
}
pdev->pUserData[0] = NULL;
#endif /* USE_USBD_COMPOSITE */
/* Free Device descriptors resources */
pdev->pDesc = NULL;
pdev->pConfDesc = NULL;
/* DeInitialize low level driver */
ret = USBD_LL_DeInit(pdev);
return ret;
}
/**
* @brief USBD_RegisterClass
* Link class driver to Device Core.
* @param pDevice : Device Handle
* @param pclass: Class handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass)
{
uint16_t len = 0U;
if (pclass == NULL)
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Invalid Class handle");
#endif /* (USBD_DEBUG_LEVEL > 1U) */
return USBD_FAIL;
}
/* link the class to the USB Device handle */
pdev->pClass[0] = pclass;
/* Get Device Configuration Descriptor */
#ifdef USE_USB_HS
if (pdev->pClass[pdev->classId]->GetHSConfigDescriptor != NULL)
{
pdev->pConfDesc = (void *)pdev->pClass[pdev->classId]->GetHSConfigDescriptor(&len);
}
#else /* Default USE_USB_FS */
if (pdev->pClass[pdev->classId]->GetFSConfigDescriptor != NULL)
{
pdev->pConfDesc = (void *)pdev->pClass[pdev->classId]->GetFSConfigDescriptor(&len);
}
#endif /* USE_USB_FS */
/* Increment the NumClasses */
pdev->NumClasses ++;
return USBD_OK;
}
#ifdef USE_USBD_COMPOSITE
/**
* @brief USBD_RegisterClassComposite
* Link class driver to Device Core.
* @param pdev : Device Handle
* @param pclass: Class handle
* @param classtype: Class type
* @param EpAddr: Endpoint Address handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_RegisterClassComposite(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass,
USBD_CompositeClassTypeDef classtype, uint8_t *EpAddr)
{
USBD_StatusTypeDef ret = USBD_OK;
uint16_t len = 0U;
if ((pdev->classId < USBD_MAX_SUPPORTED_CLASS) && (pdev->NumClasses < USBD_MAX_SUPPORTED_CLASS))
{
if ((uint32_t)pclass != 0U)
{
/* Link the class to the USB Device handle */
pdev->pClass[pdev->classId] = pclass;
ret = USBD_OK;
pdev->tclasslist[pdev->classId].EpAdd = EpAddr;
/* Call the composite class builder */
(void)USBD_CMPSIT_AddClass(pdev, pclass, classtype, 0);
/* Increment the ClassId for the next occurrence */
pdev->classId ++;
pdev->NumClasses ++;
}
else
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Invalid Class handle");
#endif /* (USBD_DEBUG_LEVEL > 1U) */
ret = USBD_FAIL;
}
}
if (ret == USBD_OK)
{
/* Get Device Configuration Descriptor */
#ifdef USE_USB_HS
pdev->pConfDesc = USBD_CMPSIT.GetHSConfigDescriptor(&len);
#else /* Default USE_USB_FS */
pdev->pConfDesc = USBD_CMPSIT.GetFSConfigDescriptor(&len);
#endif /* USE_USB_FS */
}
return ret;
}
/**
* @brief USBD_UnRegisterClassComposite
* UnLink all composite class drivers from Device Core.
* @param pDevice : Device Handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_UnRegisterClassComposite(USBD_HandleTypeDef *pdev)
{
USBD_StatusTypeDef ret = USBD_FAIL;
uint8_t idx1;
uint8_t idx2;
/* Unroll all activated classes */
for (idx1 = 0; idx1 < pdev->NumClasses; idx1++)
{
/* Check if the class correspond to the requested type and if it is active */
if (pdev->tclasslist[idx1].Active == 1U)
{
/* Set the new class ID */
pdev->classId = idx1;
/* Free resources used by the selected class */
if (pdev->pClass[pdev->classId] != NULL)
{
/* Free Class Resources */
if (pdev->pClass[pdev->classId]->DeInit(pdev, (uint8_t)pdev->dev_config) != 0U)
{
#if (USBD_DEBUG_LEVEL > 1U)
USBD_ErrLog("Class DeInit didn't succeed!, can't unregister selected class");
#endif /* (USBD_DEBUG_LEVEL > 1U) */
ret = USBD_FAIL;
}
}
/* Free the class pointer */
pdev->pClass[pdev->classId] = NULL;
/* Free the class location in classes table and reset its parameters to zero */
pdev->tclasslist[pdev->classId].ClassType = CLASS_TYPE_NONE;
pdev->tclasslist[pdev->classId].ClassId = 0U;
pdev->tclasslist[pdev->classId].Active = 0U;
pdev->tclasslist[pdev->classId].NumEps = 0U;
pdev->tclasslist[pdev->classId].NumIf = 0U;
pdev->tclasslist[pdev->classId].CurrPcktSze = 0U;
for (idx2 = 0U; idx2 < USBD_MAX_CLASS_ENDPOINTS; idx2++)
{
pdev->tclasslist[pdev->classId].Eps[idx2].add = 0U;
pdev->tclasslist[pdev->classId].Eps[idx2].type = 0U;
pdev->tclasslist[pdev->classId].Eps[idx2].size = 0U;
pdev->tclasslist[pdev->classId].Eps[idx2].is_used = 0U;
}
for (idx2 = 0U; idx2 < USBD_MAX_CLASS_INTERFACES; idx2++)
{
pdev->tclasslist[pdev->classId].Ifs[idx2] = 0U;
}
}
}
/* Reset the configuration descriptor */
(void)USBD_CMPST_ClearConfDesc(pdev);
/* Reset the class ID and number of classes */
pdev->classId = 0U;
pdev->NumClasses = 0U;
return ret;
}
#endif /* USE_USBD_COMPOSITE */
#if (USBD_USER_REGISTER_CALLBACK == 1U)
/**
* @brief USBD_RegisterDevStateCallback
* @param pdev : Device Handle
* @param pUserCallback: User Callback
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_RegisterDevStateCallback(USBD_HandleTypeDef *pdev, USBD_DevStateCallbackTypeDef pUserCallback)
{
pdev->DevStateCallback = pUserCallback;
return USBD_OK;
}
#endif /* USBD_USER_REGISTER_CALLBACK */
/**
* @brief USBD_Start
* Start the USB Device Core.
* @param pdev: Device Handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_Start(USBD_HandleTypeDef *pdev)
{
#ifdef USE_USBD_COMPOSITE
pdev->classId = 0U;
#endif /* USE_USBD_COMPOSITE */
/* Start the low level driver */
return USBD_LL_Start(pdev);
}
/**
* @brief USBD_Stop
* Stop the USB Device Core.
* @param pdev: Device Handle
* @retval USBD Status
*/
USBD_StatusTypeDef USBD_Stop(USBD_HandleTypeDef *pdev)
{
/* Disconnect USB Device */
(void)USBD_LL_Stop(pdev);
/* Free Class Resources */
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Free Class Resources */
(void)pdev->pClass[i]->DeInit(pdev, (uint8_t)pdev->dev_config);
}
}
}
/* Reset the class ID */
pdev->classId = 0U;
#else
if (pdev->pClass[0] != NULL)
{
(void)pdev->pClass[0]->DeInit(pdev, (uint8_t)pdev->dev_config);
}
#endif /* USE_USBD_COMPOSITE */
return USBD_OK;
}
/**
* @brief USBD_RunTestMode
* Launch test mode process
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_RunTestMode(USBD_HandleTypeDef *pdev)
{
#ifdef USBD_HS_TESTMODE_ENABLE
USBD_StatusTypeDef ret;
/* Run USB HS test mode */
ret = USBD_LL_SetTestMode(pdev, pdev->dev_test_mode);
return ret;
#else
/* Prevent unused argument compilation warning */
UNUSED(pdev);
return USBD_OK;
#endif /* USBD_HS_TESTMODE_ENABLE */
}
/**
* @brief USBD_SetClassConfig
* Configure device and start the interface
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status
*/
USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
USBD_StatusTypeDef ret = USBD_OK;
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Set configuration and Start the Class*/
if (pdev->pClass[i]->Init(pdev, cfgidx) != 0U)
{
ret = USBD_FAIL;
}
}
}
}
#else
if (pdev->pClass[0] != NULL)
{
/* Set configuration and Start the Class */
ret = (USBD_StatusTypeDef)pdev->pClass[0]->Init(pdev, cfgidx);
}
#endif /* USE_USBD_COMPOSITE */
return ret;
}
/**
* @brief USBD_ClrClassConfig
* Clear current configuration
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status: USBD_StatusTypeDef
*/
USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx)
{
USBD_StatusTypeDef ret = USBD_OK;
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Clear configuration and De-initialize the Class process */
if (pdev->pClass[i]->DeInit(pdev, cfgidx) != 0U)
{
ret = USBD_FAIL;
}
}
}
}
#else
/* Clear configuration and De-initialize the Class process */
if (pdev->pClass[0]->DeInit(pdev, cfgidx) != 0U)
{
ret = USBD_FAIL;
}
#endif /* USE_USBD_COMPOSITE */
return ret;
}
/**
* @brief USBD_LL_SetupStage
* Handle the setup stage
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup)
{
USBD_StatusTypeDef ret;
USBD_ParseSetupRequest(&pdev->request, psetup);
pdev->ep0_state = USBD_EP0_SETUP;
pdev->ep0_data_len = pdev->request.wLength;
switch (pdev->request.bmRequest & 0x1FU)
{
case USB_REQ_RECIPIENT_DEVICE:
ret = USBD_StdDevReq(pdev, &pdev->request);
break;
case USB_REQ_RECIPIENT_INTERFACE:
ret = USBD_StdItfReq(pdev, &pdev->request);
break;
case USB_REQ_RECIPIENT_ENDPOINT:
ret = USBD_StdEPReq(pdev, &pdev->request);
break;
default:
ret = USBD_LL_StallEP(pdev, (pdev->request.bmRequest & 0x80U));
break;
}
return ret;
}
/**
* @brief USBD_LL_DataOutStage
* Handle data OUT stage
* @param pdev: device instance
* @param epnum: endpoint index
* @param pdata: data pointer
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev,
uint8_t epnum, uint8_t *pdata)
{
USBD_EndpointTypeDef *pep;
USBD_StatusTypeDef ret = USBD_OK;
uint8_t idx;
if (epnum == 0U)
{
pep = &pdev->ep_out[0];
if (pdev->ep0_state == USBD_EP0_DATA_OUT)
{
if (pep->rem_length > pep->maxpacket)
{
pep->rem_length -= pep->maxpacket;
(void)USBD_CtlContinueRx(pdev, pdata, MIN(pep->rem_length, pep->maxpacket));
}
else
{
/* Find the class ID relative to the current request */
switch (pdev->request.bmRequest & 0x1FU)
{
case USB_REQ_RECIPIENT_DEVICE:
/* Device requests must be managed by the first instantiated class
(or duplicated by all classes for simplicity) */
idx = 0U;
break;
case USB_REQ_RECIPIENT_INTERFACE:
idx = USBD_CoreFindIF(pdev, LOBYTE(pdev->request.wIndex));
break;
case USB_REQ_RECIPIENT_ENDPOINT:
idx = USBD_CoreFindEP(pdev, LOBYTE(pdev->request.wIndex));
break;
default:
/* Back to the first class in case of doubt */
idx = 0U;
break;
}
if (idx < USBD_MAX_SUPPORTED_CLASS)
{
/* Setup the class ID and route the request to the relative class function */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[idx]->EP0_RxReady != NULL)
{
pdev->classId = idx;
pdev->pClass[idx]->EP0_RxReady(pdev);
}
}
}
(void)USBD_CtlSendStatus(pdev);
}
}
}
else
{
/* Get the class index relative to this interface */
idx = USBD_CoreFindEP(pdev, (epnum & 0x7FU));
if (((uint16_t)idx != 0xFFU) && (idx < USBD_MAX_SUPPORTED_CLASS))
{
/* Call the class data out function to manage the request */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[idx]->DataOut != NULL)
{
pdev->classId = idx;
ret = (USBD_StatusTypeDef)pdev->pClass[idx]->DataOut(pdev, epnum);
}
}
if (ret != USBD_OK)
{
return ret;
}
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_DataInStage
* Handle data in stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev,
uint8_t epnum, uint8_t *pdata)
{
USBD_EndpointTypeDef *pep;
USBD_StatusTypeDef ret;
uint8_t idx;
if (epnum == 0U)
{
pep = &pdev->ep_in[0];
if (pdev->ep0_state == USBD_EP0_DATA_IN)
{
if (pep->rem_length > pep->maxpacket)
{
pep->rem_length -= pep->maxpacket;
(void)USBD_CtlContinueSendData(pdev, pdata, pep->rem_length);
/* Prepare endpoint for premature end of transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
}
else
{
/* last packet is MPS multiple, so send ZLP packet */
if ((pep->maxpacket == pep->rem_length) &&
(pep->total_length >= pep->maxpacket) &&
(pep->total_length < pdev->ep0_data_len))
{
(void)USBD_CtlContinueSendData(pdev, NULL, 0U);
pdev->ep0_data_len = 0U;
/* Prepare endpoint for premature end of transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
}
else
{
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[0]->EP0_TxSent != NULL)
{
pdev->classId = 0U;
pdev->pClass[0]->EP0_TxSent(pdev);
}
}
(void)USBD_LL_StallEP(pdev, 0x80U);
(void)USBD_CtlReceiveStatus(pdev);
}
}
}
if (pdev->dev_test_mode != 0U)
{
(void)USBD_RunTestMode(pdev);
pdev->dev_test_mode = 0U;
}
}
else
{
/* Get the class index relative to this interface */
idx = USBD_CoreFindEP(pdev, ((uint8_t)epnum | 0x80U));
if (((uint16_t)idx != 0xFFU) && (idx < USBD_MAX_SUPPORTED_CLASS))
{
/* Call the class data out function to manage the request */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[idx]->DataIn != NULL)
{
pdev->classId = idx;
ret = (USBD_StatusTypeDef)pdev->pClass[idx]->DataIn(pdev, epnum);
if (ret != USBD_OK)
{
return ret;
}
}
}
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_Reset
* Handle Reset event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev)
{
USBD_StatusTypeDef ret = USBD_OK;
/* Upon Reset call user call back */
pdev->dev_state = USBD_STATE_DEFAULT;
pdev->ep0_state = USBD_EP0_IDLE;
pdev->dev_config = 0U;
pdev->dev_remote_wakeup = 0U;
pdev->dev_test_mode = 0U;
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Clear configuration and De-initialize the Class process*/
if (pdev->pClass[i]->DeInit != NULL)
{
if (pdev->pClass[i]->DeInit(pdev, (uint8_t)pdev->dev_config) != USBD_OK)
{
ret = USBD_FAIL;
}
}
}
}
}
#else
if (pdev->pClass[0] != NULL)
{
if (pdev->pClass[0]->DeInit != NULL)
{
if (pdev->pClass[0]->DeInit(pdev, (uint8_t)pdev->dev_config) != USBD_OK)
{
ret = USBD_FAIL;
}
}
}
#endif /* USE_USBD_COMPOSITE */
/* Open EP0 OUT */
(void)USBD_LL_OpenEP(pdev, 0x00U, USBD_EP_TYPE_CTRL, USB_MAX_EP0_SIZE);
pdev->ep_out[0x00U & 0xFU].is_used = 1U;
pdev->ep_out[0].maxpacket = USB_MAX_EP0_SIZE;
/* Open EP0 IN */
(void)USBD_LL_OpenEP(pdev, 0x80U, USBD_EP_TYPE_CTRL, USB_MAX_EP0_SIZE);
pdev->ep_in[0x80U & 0xFU].is_used = 1U;
pdev->ep_in[0].maxpacket = USB_MAX_EP0_SIZE;
return ret;
}
/**
* @brief USBD_LL_SetSpeed
* Handle Reset event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev,
USBD_SpeedTypeDef speed)
{
pdev->dev_speed = speed;
return USBD_OK;
}
/**
* @brief USBD_LL_Suspend
* Handle Suspend event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev)
{
if (pdev->dev_state != USBD_STATE_SUSPENDED)
{
pdev->dev_old_state = pdev->dev_state;
}
pdev->dev_state = USBD_STATE_SUSPENDED;
return USBD_OK;
}
/**
* @brief USBD_LL_Resume
* Handle Resume event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev)
{
if (pdev->dev_state == USBD_STATE_SUSPENDED)
{
pdev->dev_state = pdev->dev_old_state;
}
return USBD_OK;
}
/**
* @brief USBD_LL_SOF
* Handle SOF event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev)
{
/* The SOF event can be distributed for all classes that support it */
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
if (pdev->pClass[i]->SOF != NULL)
{
pdev->classId = i;
(void)pdev->pClass[i]->SOF(pdev);
}
}
}
}
#else
if (pdev->pClass[0] != NULL)
{
if (pdev->pClass[0]->SOF != NULL)
{
(void)pdev->pClass[0]->SOF(pdev);
}
}
#endif /* USE_USBD_COMPOSITE */
}
return USBD_OK;
}
/**
* @brief USBD_LL_IsoINIncomplete
* Handle iso in incomplete event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev,
uint8_t epnum)
{
if (pdev->pClass[pdev->classId] == NULL)
{
return USBD_FAIL;
}
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[pdev->classId]->IsoINIncomplete != NULL)
{
(void)pdev->pClass[pdev->classId]->IsoINIncomplete(pdev, epnum);
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_IsoOUTIncomplete
* Handle iso out incomplete event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev,
uint8_t epnum)
{
if (pdev->pClass[pdev->classId] == NULL)
{
return USBD_FAIL;
}
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
if (pdev->pClass[pdev->classId]->IsoOUTIncomplete != NULL)
{
(void)pdev->pClass[pdev->classId]->IsoOUTIncomplete(pdev, epnum);
}
}
return USBD_OK;
}
/**
* @brief USBD_LL_DevConnected
* Handle device connection event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev)
{
/* Prevent unused argument compilation warning */
UNUSED(pdev);
return USBD_OK;
}
/**
* @brief USBD_LL_DevDisconnected
* Handle device disconnection event
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev)
{
USBD_StatusTypeDef ret = USBD_OK;
/* Free Class Resources */
pdev->dev_state = USBD_STATE_DEFAULT;
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
if (pdev->pClass[i] != NULL)
{
pdev->classId = i;
/* Clear configuration and De-initialize the Class process*/
if (pdev->pClass[i]->DeInit(pdev, (uint8_t)pdev->dev_config) != 0U)
{
ret = USBD_FAIL;
}
}
}
}
#else
if (pdev->pClass[0] != NULL)
{
if (pdev->pClass[0]->DeInit(pdev, (uint8_t)pdev->dev_config) != 0U)
{
ret = USBD_FAIL;
}
}
#endif /* USE_USBD_COMPOSITE */
return ret;
}
/**
* @brief USBD_CoreFindIF
* return the class index relative to the selected interface
* @param pdev: device instance
* @param index : selected interface number
* @retval index of the class using the selected interface number. OxFF if no class found.
*/
uint8_t USBD_CoreFindIF(USBD_HandleTypeDef *pdev, uint8_t index)
{
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
/* Parse all interfaces listed in the current class */
for (uint32_t j = 0U; j < pdev->tclasslist[i].NumIf; j++)
{
/* Check if requested Interface matches the current class interface */
if (pdev->tclasslist[i].Ifs[j] == index)
{
if (pdev->pClass[i]->Setup != NULL)
{
return (uint8_t)i;
}
}
}
}
}
return 0xFFU;
#else
UNUSED(pdev);
UNUSED(index);
return 0x00U;
#endif /* USE_USBD_COMPOSITE */
}
/**
* @brief USBD_CoreFindEP
* return the class index relative to the selected endpoint
* @param pdev: device instance
* @param index : selected endpoint number
* @retval index of the class using the selected endpoint number. 0xFF if no class found.
*/
uint8_t USBD_CoreFindEP(USBD_HandleTypeDef *pdev, uint8_t index)
{
#ifdef USE_USBD_COMPOSITE
/* Parse the table of classes in use */
for (uint32_t i = 0U; i < USBD_MAX_SUPPORTED_CLASS; i++)
{
/* Check if current class is in use */
if ((pdev->tclasslist[i].Active) == 1U)
{
/* Parse all endpoints listed in the current class */
for (uint32_t j = 0U; j < pdev->tclasslist[i].NumEps; j++)
{
/* Check if requested endpoint matches the current class endpoint */
if (pdev->tclasslist[i].Eps[j].add == index)
{
if (pdev->pClass[i]->Setup != NULL)
{
return (uint8_t)i;
}
}
}
}
}
return 0xFFU;
#else
UNUSED(pdev);
UNUSED(index);
return 0x00U;
#endif /* USE_USBD_COMPOSITE */
}
#ifdef USE_USBD_COMPOSITE
/**
* @brief USBD_CoreGetEPAdd
* Get the endpoint address relative to a selected class
* @param pdev: device instance
* @param ep_dir: USBD_EP_IN or USBD_EP_OUT
* @param ep_type: USBD_EP_TYPE_CTRL, USBD_EP_TYPE_ISOC, USBD_EP_TYPE_BULK or USBD_EP_TYPE_INTR
* @param ClassId: The Class ID
* @retval Address of the selected endpoint or 0xFFU if no endpoint found.
*/
uint8_t USBD_CoreGetEPAdd(USBD_HandleTypeDef *pdev, uint8_t ep_dir, uint8_t ep_type, uint8_t ClassId)
{
uint8_t idx;
/* Find the EP address in the selected class table */
for (idx = 0; idx < pdev->tclasslist[ClassId].NumEps; idx++)
{
if (((pdev->tclasslist[ClassId].Eps[idx].add & USBD_EP_IN) == ep_dir) && \
(pdev->tclasslist[ClassId].Eps[idx].type == ep_type) && \
(pdev->tclasslist[ClassId].Eps[idx].is_used != 0U))
{
return (pdev->tclasslist[ClassId].Eps[idx].add);
}
}
/* If reaching this point, then no endpoint was found */
return 0xFFU;
}
#endif /* USE_USBD_COMPOSITE */
/**
* @brief USBD_GetEpDesc
* This function return the Endpoint descriptor
* @param pdev: device instance
* @param pConfDesc: pointer to Bos descriptor
* @param EpAddr: endpoint address
* @retval pointer to video endpoint descriptor
*/
void *USBD_GetEpDesc(uint8_t *pConfDesc, uint8_t EpAddr)
{
USBD_DescHeaderTypeDef *pdesc = (USBD_DescHeaderTypeDef *)(void *)pConfDesc;
USBD_ConfigDescTypeDef *desc = (USBD_ConfigDescTypeDef *)(void *)pConfDesc;
USBD_EpDescTypeDef *pEpDesc = NULL;
uint16_t ptr;
if (desc->wTotalLength > desc->bLength)
{
ptr = desc->bLength;
while (ptr < desc->wTotalLength)
{
pdesc = USBD_GetNextDesc((uint8_t *)pdesc, &ptr);
if (pdesc->bDescriptorType == USB_DESC_TYPE_ENDPOINT)
{
pEpDesc = (USBD_EpDescTypeDef *)(void *)pdesc;
if (pEpDesc->bEndpointAddress == EpAddr)
{
break;
}
else
{
pEpDesc = NULL;
}
}
}
}
return (void *)pEpDesc;
}
/**
* @brief USBD_GetNextDesc
* This function return the next descriptor header
* @param buf: Buffer where the descriptor is available
* @param ptr: data pointer inside the descriptor
* @retval next header
*/
USBD_DescHeaderTypeDef *USBD_GetNextDesc(uint8_t *pbuf, uint16_t *ptr)
{
USBD_DescHeaderTypeDef *pnext = (USBD_DescHeaderTypeDef *)(void *)pbuf;
*ptr += pnext->bLength;
pnext = (USBD_DescHeaderTypeDef *)(void *)(pbuf + pnext->bLength);
return (pnext);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Src\usbd_ctlreq.c | /**
******************************************************************************
* @file usbd_req.c
* @author MCD Application Team
* @brief This file provides the standard USB requests following chapter 9.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_ctlreq.h"
#include "usbd_ioreq.h"
#ifdef USE_USBD_COMPOSITE
#include "usbd_composite_builder.h"
#endif /* USE_USBD_COMPOSITE */
/** @addtogroup STM32_USBD_STATE_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_REQ
* @brief USB standard requests module
* @{
*/
/** @defgroup USBD_REQ_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_REQ_Private_FunctionPrototypes
* @{
*/
static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_SetAddress(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static USBD_StatusTypeDef USBD_SetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_GetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_GetStatus(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_SetFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static void USBD_ClrFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req);
static uint8_t USBD_GetLen(uint8_t *buf);
/**
* @}
*/
/** @defgroup USBD_REQ_Private_Functions
* @{
*/
/**
* @brief USBD_StdDevReq
* Handle standard usb device requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdDevReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
ret = (USBD_StatusTypeDef)pdev->pClass[pdev->classId]->Setup(pdev, req);
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_GET_DESCRIPTOR:
USBD_GetDescriptor(pdev, req);
break;
case USB_REQ_SET_ADDRESS:
USBD_SetAddress(pdev, req);
break;
case USB_REQ_SET_CONFIGURATION:
ret = USBD_SetConfig(pdev, req);
break;
case USB_REQ_GET_CONFIGURATION:
USBD_GetConfig(pdev, req);
break;
case USB_REQ_GET_STATUS:
USBD_GetStatus(pdev, req);
break;
case USB_REQ_SET_FEATURE:
USBD_SetFeature(pdev, req);
break;
case USB_REQ_CLEAR_FEATURE:
USBD_ClrFeature(pdev, req);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_StdItfReq
* Handle standard usb interface requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdItfReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
uint8_t idx;
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
case USB_REQ_TYPE_STANDARD:
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (LOBYTE(req->wIndex) <= USBD_MAX_NUM_INTERFACES)
{
/* Get the class index relative to this interface */
idx = USBD_CoreFindIF(pdev, LOBYTE(req->wIndex));
if (((uint8_t)idx != 0xFFU) && (idx < USBD_MAX_SUPPORTED_CLASS))
{
/* Call the class data out function to manage the request */
if (pdev->pClass[idx]->Setup != NULL)
{
pdev->classId = idx;
ret = (USBD_StatusTypeDef)(pdev->pClass[idx]->Setup(pdev, req));
}
else
{
/* should never reach this condition */
ret = USBD_FAIL;
}
}
else
{
/* No relative interface found */
ret = USBD_FAIL;
}
if ((req->wLength == 0U) && (ret == USBD_OK))
{
(void)USBD_CtlSendStatus(pdev);
}
}
else
{
USBD_CtlError(pdev, req);
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_StdEPReq
* Handle standard usb endpoint requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
USBD_StatusTypeDef USBD_StdEPReq(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_EndpointTypeDef *pep;
uint8_t ep_addr;
uint8_t idx;
USBD_StatusTypeDef ret = USBD_OK;
ep_addr = LOBYTE(req->wIndex);
switch (req->bmRequest & USB_REQ_TYPE_MASK)
{
case USB_REQ_TYPE_CLASS:
case USB_REQ_TYPE_VENDOR:
/* Get the class index relative to this endpoint */
idx = USBD_CoreFindEP(pdev, ep_addr);
if (((uint8_t)idx != 0xFFU) && (idx < USBD_MAX_SUPPORTED_CLASS))
{
pdev->classId = idx;
/* Call the class data out function to manage the request */
if (pdev->pClass[idx]->Setup != NULL)
{
ret = (USBD_StatusTypeDef)pdev->pClass[idx]->Setup(pdev, req);
}
}
break;
case USB_REQ_TYPE_STANDARD:
switch (req->bRequest)
{
case USB_REQ_SET_FEATURE:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
(void)USBD_LL_StallEP(pdev, 0x80U);
}
else
{
USBD_CtlError(pdev, req);
}
break;
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_EP_HALT)
{
if ((ep_addr != 0x00U) && (ep_addr != 0x80U) && (req->wLength == 0x00U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
}
}
(void)USBD_CtlSendStatus(pdev);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
case USB_REQ_CLEAR_FEATURE:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
(void)USBD_LL_StallEP(pdev, ep_addr);
(void)USBD_LL_StallEP(pdev, 0x80U);
}
else
{
USBD_CtlError(pdev, req);
}
break;
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_EP_HALT)
{
if ((ep_addr & 0x7FU) != 0x00U)
{
(void)USBD_LL_ClearStallEP(pdev, ep_addr);
}
(void)USBD_CtlSendStatus(pdev);
/* Get the class index relative to this interface */
idx = USBD_CoreFindEP(pdev, ep_addr);
if (((uint8_t)idx != 0xFFU) && (idx < USBD_MAX_SUPPORTED_CLASS))
{
pdev->classId = idx;
/* Call the class data out function to manage the request */
if (pdev->pClass[idx]->Setup != NULL)
{
ret = (USBD_StatusTypeDef)(pdev->pClass[idx]->Setup(pdev, req));
}
}
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
case USB_REQ_GET_STATUS:
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if ((ep_addr != 0x00U) && (ep_addr != 0x80U))
{
USBD_CtlError(pdev, req);
break;
}
pep = ((ep_addr & 0x80U) == 0x80U) ? &pdev->ep_in[ep_addr & 0x7FU] : \
&pdev->ep_out[ep_addr & 0x7FU];
pep->status = 0x0000U;
(void)USBD_CtlSendData(pdev, (uint8_t *)&pep->status, 2U);
break;
case USBD_STATE_CONFIGURED:
if ((ep_addr & 0x80U) == 0x80U)
{
if (pdev->ep_in[ep_addr & 0xFU].is_used == 0U)
{
USBD_CtlError(pdev, req);
break;
}
}
else
{
if (pdev->ep_out[ep_addr & 0xFU].is_used == 0U)
{
USBD_CtlError(pdev, req);
break;
}
}
pep = ((ep_addr & 0x80U) == 0x80U) ? &pdev->ep_in[ep_addr & 0x7FU] : \
&pdev->ep_out[ep_addr & 0x7FU];
if ((ep_addr == 0x00U) || (ep_addr == 0x80U))
{
pep->status = 0x0000U;
}
else if (USBD_LL_IsStallEP(pdev, ep_addr) != 0U)
{
pep->status = 0x0001U;
}
else
{
pep->status = 0x0000U;
}
(void)USBD_CtlSendData(pdev, (uint8_t *)&pep->status, 2U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
return ret;
}
/**
* @brief USBD_GetDescriptor
* Handle Get Descriptor requests
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
uint16_t len = 0U;
uint8_t *pbuf = NULL;
uint8_t err = 0U;
switch (req->wValue >> 8)
{
#if ((USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1U))
case USB_DESC_TYPE_BOS:
if (pdev->pDesc->GetBOSDescriptor != NULL)
{
pbuf = pdev->pDesc->GetBOSDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
#endif /* (USBD_LPM_ENABLED == 1U) || (USBD_CLASS_BOS_ENABLED == 1U) */
case USB_DESC_TYPE_DEVICE:
pbuf = pdev->pDesc->GetDeviceDescriptor(pdev->dev_speed, &len);
break;
case USB_DESC_TYPE_CONFIGURATION:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
#ifdef USE_USBD_COMPOSITE
if ((uint8_t)(pdev->NumClasses) > 0U)
{
pbuf = (uint8_t *)USBD_CMPSIT.GetHSConfigDescriptor(&len);
}
else
#endif /* USE_USBD_COMPOSITE */
{
pbuf = (uint8_t *)pdev->pClass[0]->GetHSConfigDescriptor(&len);
}
pbuf[1] = USB_DESC_TYPE_CONFIGURATION;
}
else
{
#ifdef USE_USBD_COMPOSITE
if ((uint8_t)(pdev->NumClasses) > 0U)
{
pbuf = (uint8_t *)USBD_CMPSIT.GetFSConfigDescriptor(&len);
}
else
#endif /* USE_USBD_COMPOSITE */
{
pbuf = (uint8_t *)pdev->pClass[0]->GetFSConfigDescriptor(&len);
}
pbuf[1] = USB_DESC_TYPE_CONFIGURATION;
}
break;
case USB_DESC_TYPE_STRING:
switch ((uint8_t)(req->wValue))
{
case USBD_IDX_LANGID_STR:
if (pdev->pDesc->GetLangIDStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetLangIDStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_MFC_STR:
if (pdev->pDesc->GetManufacturerStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetManufacturerStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_PRODUCT_STR:
if (pdev->pDesc->GetProductStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetProductStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_SERIAL_STR:
if (pdev->pDesc->GetSerialStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetSerialStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_CONFIG_STR:
if (pdev->pDesc->GetConfigurationStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetConfigurationStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USBD_IDX_INTERFACE_STR:
if (pdev->pDesc->GetInterfaceStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetInterfaceStrDescriptor(pdev->dev_speed, &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
default:
#if (USBD_SUPPORT_USER_STRING_DESC == 1U)
pbuf = NULL;
for (uint32_t idx = 0U; (idx < pdev->NumClasses); idx++)
{
if (pdev->pClass[idx]->GetUsrStrDescriptor != NULL)
{
pdev->classId = idx;
pbuf = pdev->pClass[idx]->GetUsrStrDescriptor(pdev, LOBYTE(req->wValue), &len);
if (pbuf == NULL) /* This means that no class recognized the string index */
{
continue;
}
else
{
break;
}
}
}
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#if (USBD_CLASS_USER_STRING_DESC == 1U)
if (pdev->pDesc->GetUserStrDescriptor != NULL)
{
pbuf = pdev->pDesc->GetUserStrDescriptor(pdev->dev_speed, LOBYTE(req->wValue), &len);
}
else
{
USBD_CtlError(pdev, req);
err++;
}
#endif /* USBD_SUPPORT_USER_STRING_DESC */
#if ((USBD_CLASS_USER_STRING_DESC == 0U) && (USBD_SUPPORT_USER_STRING_DESC == 0U))
USBD_CtlError(pdev, req);
err++;
#endif /* (USBD_CLASS_USER_STRING_DESC == 0U) && (USBD_SUPPORT_USER_STRING_DESC == 0U) */
break;
}
break;
case USB_DESC_TYPE_DEVICE_QUALIFIER:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
#ifdef USE_USBD_COMPOSITE
if ((uint8_t)(pdev->NumClasses) > 0U)
{
pbuf = (uint8_t *)USBD_CMPSIT.GetDeviceQualifierDescriptor(&len);
}
else
#endif /* USE_USBD_COMPOSITE */
{
pbuf = (uint8_t *)pdev->pClass[0]->GetDeviceQualifierDescriptor(&len);
}
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
case USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION:
if (pdev->dev_speed == USBD_SPEED_HIGH)
{
#ifdef USE_USBD_COMPOSITE
if ((uint8_t)(pdev->NumClasses) > 0U)
{
pbuf = (uint8_t *)USBD_CMPSIT.GetOtherSpeedConfigDescriptor(&len);
}
else
#endif /* USE_USBD_COMPOSITE */
{
pbuf = (uint8_t *)pdev->pClass[0]->GetOtherSpeedConfigDescriptor(&len);
}
pbuf[1] = USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION;
}
else
{
USBD_CtlError(pdev, req);
err++;
}
break;
default:
USBD_CtlError(pdev, req);
err++;
break;
}
if (err != 0U)
{
return;
}
if (req->wLength != 0U)
{
if (len != 0U)
{
len = MIN(len, req->wLength);
(void)USBD_CtlSendData(pdev, pbuf, len);
}
else
{
USBD_CtlError(pdev, req);
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
}
/**
* @brief USBD_SetAddress
* Set device address
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_SetAddress(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
uint8_t dev_addr;
if ((req->wIndex == 0U) && (req->wLength == 0U) && (req->wValue < 128U))
{
dev_addr = (uint8_t)(req->wValue) & 0x7FU;
if (pdev->dev_state == USBD_STATE_CONFIGURED)
{
USBD_CtlError(pdev, req);
}
else
{
pdev->dev_address = dev_addr;
(void)USBD_LL_SetUSBAddress(pdev, dev_addr);
(void)USBD_CtlSendStatus(pdev);
if (dev_addr != 0U)
{
pdev->dev_state = USBD_STATE_ADDRESSED;
}
else
{
pdev->dev_state = USBD_STATE_DEFAULT;
}
}
}
else
{
USBD_CtlError(pdev, req);
}
}
/**
* @brief USBD_SetConfig
* Handle Set device configuration request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static USBD_StatusTypeDef USBD_SetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
USBD_StatusTypeDef ret = USBD_OK;
static uint8_t cfgidx;
cfgidx = (uint8_t)(req->wValue);
if (cfgidx > USBD_MAX_NUM_CONFIGURATION)
{
USBD_CtlError(pdev, req);
return USBD_FAIL;
}
switch (pdev->dev_state)
{
case USBD_STATE_ADDRESSED:
if (cfgidx != 0U)
{
pdev->dev_config = cfgidx;
ret = USBD_SetClassConfig(pdev, cfgidx);
if (ret != USBD_OK)
{
USBD_CtlError(pdev, req);
pdev->dev_state = USBD_STATE_ADDRESSED;
}
else
{
(void)USBD_CtlSendStatus(pdev);
pdev->dev_state = USBD_STATE_CONFIGURED;
#if (USBD_USER_REGISTER_CALLBACK == 1U)
if (pdev->DevStateCallback != NULL)
{
pdev->DevStateCallback(USBD_STATE_CONFIGURED, cfgidx);
}
#endif /* USBD_USER_REGISTER_CALLBACK */
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
break;
case USBD_STATE_CONFIGURED:
if (cfgidx == 0U)
{
pdev->dev_state = USBD_STATE_ADDRESSED;
pdev->dev_config = cfgidx;
(void)USBD_ClrClassConfig(pdev, cfgidx);
(void)USBD_CtlSendStatus(pdev);
}
else if (cfgidx != pdev->dev_config)
{
/* Clear old configuration */
(void)USBD_ClrClassConfig(pdev, (uint8_t)pdev->dev_config);
/* set new configuration */
pdev->dev_config = cfgidx;
ret = USBD_SetClassConfig(pdev, cfgidx);
if (ret != USBD_OK)
{
USBD_CtlError(pdev, req);
(void)USBD_ClrClassConfig(pdev, (uint8_t)pdev->dev_config);
pdev->dev_state = USBD_STATE_ADDRESSED;
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
}
else
{
(void)USBD_CtlSendStatus(pdev);
}
break;
default:
USBD_CtlError(pdev, req);
(void)USBD_ClrClassConfig(pdev, cfgidx);
ret = USBD_FAIL;
break;
}
return ret;
}
/**
* @brief USBD_GetConfig
* Handle Get device configuration request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetConfig(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
if (req->wLength != 1U)
{
USBD_CtlError(pdev, req);
}
else
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
pdev->dev_default_config = 0U;
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_default_config, 1U);
break;
case USBD_STATE_CONFIGURED:
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_config, 1U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
}
/**
* @brief USBD_GetStatus
* Handle Get Status request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_GetStatus(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (req->wLength != 0x2U)
{
USBD_CtlError(pdev, req);
break;
}
#if (USBD_SELF_POWERED == 1U)
pdev->dev_config_status = USB_CONFIG_SELF_POWERED;
#else
pdev->dev_config_status = 0U;
#endif /* USBD_SELF_POWERED */
if (pdev->dev_remote_wakeup != 0U)
{
pdev->dev_config_status |= USB_CONFIG_REMOTE_WAKEUP;
}
(void)USBD_CtlSendData(pdev, (uint8_t *)&pdev->dev_config_status, 2U);
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
/**
* @brief USBD_SetFeature
* Handle Set device feature request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_SetFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
if (req->wValue == USB_FEATURE_REMOTE_WAKEUP)
{
pdev->dev_remote_wakeup = 1U;
(void)USBD_CtlSendStatus(pdev);
}
else if (req->wValue == USB_FEATURE_TEST_MODE)
{
pdev->dev_test_mode = (uint8_t)(req->wIndex >> 8);
(void)USBD_CtlSendStatus(pdev);
}
else
{
USBD_CtlError(pdev, req);
}
}
/**
* @brief USBD_ClrFeature
* Handle clear device feature request
* @param pdev: device instance
* @param req: usb request
* @retval status
*/
static void USBD_ClrFeature(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
switch (pdev->dev_state)
{
case USBD_STATE_DEFAULT:
case USBD_STATE_ADDRESSED:
case USBD_STATE_CONFIGURED:
if (req->wValue == USB_FEATURE_REMOTE_WAKEUP)
{
pdev->dev_remote_wakeup = 0U;
(void)USBD_CtlSendStatus(pdev);
}
break;
default:
USBD_CtlError(pdev, req);
break;
}
}
/**
* @brief USBD_ParseSetupRequest
* Copy buffer into setup structure
* @param pdev: device instance
* @param req: usb request
* @retval None
*/
void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata)
{
uint8_t *pbuff = pdata;
req->bmRequest = *(uint8_t *)(pbuff);
pbuff++;
req->bRequest = *(uint8_t *)(pbuff);
pbuff++;
req->wValue = SWAPBYTE(pbuff);
pbuff++;
pbuff++;
req->wIndex = SWAPBYTE(pbuff);
pbuff++;
pbuff++;
req->wLength = SWAPBYTE(pbuff);
}
/**
* @brief USBD_CtlError
* Handle USB low level Error
* @param pdev: device instance
* @param req: usb request
* @retval None
*/
void USBD_CtlError(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req)
{
UNUSED(req);
(void)USBD_LL_StallEP(pdev, 0x80U);
(void)USBD_LL_StallEP(pdev, 0U);
}
/**
* @brief USBD_GetString
* Convert Ascii string into unicode one
* @param desc : descriptor buffer
* @param unicode : Formatted string buffer (unicode)
* @param len : descriptor length
* @retval None
*/
void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len)
{
uint8_t idx = 0U;
uint8_t *pdesc;
if (desc == NULL)
{
return;
}
pdesc = desc;
*len = ((uint16_t)USBD_GetLen(pdesc) * 2U) + 2U;
unicode[idx] = *(uint8_t *)len;
idx++;
unicode[idx] = USB_DESC_TYPE_STRING;
idx++;
while (*pdesc != (uint8_t)'\0')
{
unicode[idx] = *pdesc;
pdesc++;
idx++;
unicode[idx] = 0U;
idx++;
}
}
/**
* @brief USBD_GetLen
* return the string length
* @param buf : pointer to the ascii string buffer
* @retval string length
*/
static uint8_t USBD_GetLen(uint8_t *buf)
{
uint8_t len = 0U;
uint8_t *pbuff = buf;
while (*pbuff != (uint8_t)'\0')
{
len++;
pbuff++;
}
return len;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Src\usbd_desc_template.c | /**
******************************************************************************
* @file usbd_desc_template.c
* @author MCD Application Team
* @brief This file provides the USBD descriptors and string formatting method.
* This template should be copied to the user folder,
* renamed and customized following user needs.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_core.h"
#include "usbd_desc.h"
#include "usbd_conf.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define USBD_VID 0x0483
#define USBD_PID 0xaaaa /* Replace '0xaaaa' with your device product ID */
#define USBD_LANGID_STRING 0xbbb /* Replace '0xbbb' with your device language ID */
#define USBD_MANUFACTURER_STRING "xxxxx" /* Add your manufacturer string */
#define USBD_PRODUCT_HS_STRING "xxxxx" /* Add your product High Speed string */
#define USBD_PRODUCT_FS_STRING "xxxxx" /* Add your product Full Speed string */
#define USBD_CONFIGURATION_HS_STRING "xxxxx" /* Add your configuration High Speed string */
#define USBD_INTERFACE_HS_STRING "xxxxx" /* Add your Interface High Speed string */
#define USBD_CONFIGURATION_FS_STRING "xxxxx" /* Add your configuration Full Speed string */
#define USBD_INTERFACE_FS_STRING "xxxxx" /* Add your Interface Full Speed string */
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
uint8_t *USBD_Class_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
uint8_t *USBD_Class_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
#if (USBD_CLASS_USER_STRING_DESC == 1)
uint8_t *USBD_Class_UserStrDescriptor(USBD_SpeedTypeDef speed, uint8_t idx, uint16_t *length);
#endif /* USB_CLASS_USER_STRING_DESC */
#if ((USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1))
uint8_t *USBD_USR_BOSDescriptor(USBD_SpeedTypeDef speed, uint16_t *length);
#endif /* (USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1) */
/* Private variables ---------------------------------------------------------*/
USBD_DescriptorsTypeDef Class_Desc =
{
USBD_Class_DeviceDescriptor,
USBD_Class_LangIDStrDescriptor,
USBD_Class_ManufacturerStrDescriptor,
USBD_Class_ProductStrDescriptor,
USBD_Class_SerialStrDescriptor,
USBD_Class_ConfigStrDescriptor,
USBD_Class_InterfaceStrDescriptor,
#if (USBD_CLASS_USER_STRING_DESC == 1)
USBD_CLASS_UserStrDescriptor,
#endif /* USB_CLASS_USER_STRING_DESC */
#if ((USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1))
USBD_USR_BOSDescriptor,
#endif /* (USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1) */
};
/* USB Standard Device Descriptor */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END =
{
0x12, /* bLength */
USB_DESC_TYPE_DEVICE, /* bDescriptorType */
#if ((USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1))
0x01, /*bcdUSB */ /* changed to USB version 2.01
in order to support BOS Desc */
#else
0x00, /* bcdUSB */
#endif /* (USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1) */
0x02,
0x00, /* bDeviceClass */
0x00, /* bDeviceSubClass */
0x00, /* bDeviceProtocol */
USB_MAX_EP0_SIZE, /* bMaxPacketSize */
LOBYTE(USBD_VID), /* idVendor */
HIBYTE(USBD_VID), /* idVendor */
LOBYTE(USBD_PID), /* idVendor */
HIBYTE(USBD_PID), /* idVendor */
0x00, /* bcdDevice rel. 2.00 */
0x02,
USBD_IDX_MFC_STR, /* Index of manufacturer string */
USBD_IDX_PRODUCT_STR, /* Index of product string */
USBD_IDX_SERIAL_STR, /* Index of serial number string */
USBD_MAX_NUM_CONFIGURATION /* bNumConfigurations */
}; /* USB_DeviceDescriptor */
/* USB Device LPM BOS descriptor */
#if (USBD_LPM_ENABLED == 1)
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_BOSDesc[USB_SIZ_BOS_DESC] __ALIGN_END =
{
0x5,
USB_DESC_TYPE_BOS,
0xC,
0x0,
0x1, /* 1 device capability */
/* device capability */
0x7,
USB_DEVICE_CAPABITY_TYPE,
0x2,
0x6, /*LPM capability bit set */
0x0,
0x0,
0x0
};
#endif /* USBD_LPM_ENABLED */
/* USB Device Billboard BOS descriptor Template */
#if (USBD_CLASS_BOS_ENABLED == 1)
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_BOSDesc[USB_SIZ_BOS_DESC] __ALIGN_END =
{
0x05, /* bLength */
USB_DESC_TYPE_BOS, /* Device Descriptor Type */
USB_SIZ_BOS_DESC, /* Total length of BOS descriptor and all of its sub descs */
0x00,
0x04, /* The number of separate device capability descriptors in the BOS */
/* ----------- Device Capability Descriptor: CONTAINER_ID ---------- */
0x14, /* bLength */
0x10, /* bDescriptorType: DEVICE CAPABILITY Type */
0x04, /* bDevCapabilityType: CONTAINER_ID */
0x00, /* bReserved */
0xa7, 0xd6, 0x1b, 0xfa, /* ContainerID: This is a Unique 128-bit number GUID */
0x91, 0xa6, 0xa8, 0x4e,
0xa8, 0x21, 0x9f, 0x2b,
0xaf, 0xf7, 0x94, 0xd4,
/* ----------- Device Capability Descriptor: BillBoard ---------- */
0x34, /* bLength */
0x10, /* bDescriptorType: DEVICE CAPABILITY Type */
0x0D, /* bDevCapabilityType: BILLBOARD_CAPABILITY */
USBD_BB_URL_STRING_INDEX, /* iAddtionalInfoURL: Index of string descriptor providing a URL where the user
can go to get more detailed information about the product and the various
Alternate Modes it supports */
0x02, /* bNumberOfAlternateModes: Number of Alternate modes supported. The
maximum value that this field can be set to is MAX_NUM_ALT_MODE. */
0x00, /* bPreferredAlternateMode: Index of the preferred Alternate Mode. System
software may use this information to provide the user with a better
user experience. */
0x00, 0x00, /* VCONN Power needed by the adapter for full functionality 000b = 1W */
0x01, 0x00, 0x00, 0x00, /* bmConfigured. 01b: Alternate Mode configuration not attempted or exited */
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x21, 0x01, /* bcdVersion = 0x0121 */
0x00, /* bAdditionalFailureInfo */
0x00, /* bReserved */
LOBYTE(USBD_VID),
HIBYTE(USBD_VID), /* wSVID[0]: Standard or Vendor ID. This shall match one of the SVIDs
returned in response to a USB PD Discover SVIDs command */
0x00, /* bAlternateMode[0] Index of the Alternate Mode within the SVID as
returned in response to a Discover Modes command. Example:
0 first Mode entry
1 second mode entry */
USBD_BB_ALTMODE0_STRING_INDEX, /* iAlternateModeString[0]: Index of string descriptor describing protocol.
It is optional to support this string. */
LOBYTE(USBD_VID),
HIBYTE(USBD_VID), /* wSVID[1]: Standard or Vendor ID. This shall match one of the SVIDs
returned in response to a USB PD Discover SVIDs command */
0x01, /* bAlternateMode[1] Index of the Alternate Mode within the SVID as
returned in response to a Discover Modes command. Example:
0 first Mode entry
1 second Mode entry */
USBD_BB_ALTMODE1_STRING_INDEX, /* iAlternateModeString[1]: Index of string descriptor describing protocol.
It is optional to support this string. */
/* Alternate Mode Desc */
/* ----------- Device Capability Descriptor: BillBoard Alternate Mode Desc ---------- */
0x08, /* bLength */
0x10, /* bDescriptorType: Device Descriptor Type */
0x0F, /* bDevCapabilityType: BILLBOARD ALTERNATE MODE CAPABILITY */
0x00, /* bIndex: Index of Alternate Mode described in the Billboard Capability Desc */
0x10, 0x00, 0x00, 0x00, /* dwAlternateModeVdo: contents of the Mode VDO for the alternate mode
identified by bIndex */
0x08, /* bLength */
0x10, /* bDescriptorType: Device Descriptor Type */
0x0F, /* bDevCapabilityType: BILLBOARD ALTERNATE MODE CAPABILITY */
0x01, /* bIndex: Index of Alternate Mode described in the Billboard Capability Desc */
0x20, 0x00, 0x00, 0x00, /* dwAlternateModeVdo: contents of the Mode VDO for the alternate mode
identified by bIndex */
};
#endif /* USBD_CLASS_BOS_ENABLED */
/* USB Standard Device Descriptor */
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END =
{
USB_LEN_LANGID_STR_DESC,
USB_DESC_TYPE_STRING,
LOBYTE(USBD_LANGID_STRING),
HIBYTE(USBD_LANGID_STRING),
};
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_StringSerial[USB_SIZ_STRING_SERIAL] =
{
USB_SIZ_STRING_SERIAL,
USB_DESC_TYPE_STRING,
};
#if defined ( __ICCARM__ ) /*!< IAR Compiler */
#pragma data_alignment=4
#endif /* __ICCARM__ */
__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END;
/* Private functions ---------------------------------------------------------*/
static void IntToUnicode(uint32_t value, uint8_t *pbuf, uint8_t len);
static void Get_SerialNum(void);
/**
* @brief Returns the device descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = sizeof(USBD_DeviceDesc);
return (uint8_t *)USBD_DeviceDesc;
}
/**
* @brief Returns the LangID string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = sizeof(USBD_LangIDDesc);
return (uint8_t *)USBD_LangIDDesc;
}
/**
* @brief Returns the product string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if (speed == USBD_SPEED_HIGH)
{
USBD_GetString((uint8_t *)USBD_PRODUCT_HS_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_PRODUCT_FS_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Returns the manufacturer string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
USBD_GetString((uint8_t *)USBD_MANUFACTURER_STRING, USBD_StrDesc, length);
return USBD_StrDesc;
}
/**
* @brief Returns the serial number string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
UNUSED(speed);
*length = USB_SIZ_STRING_SERIAL;
/* Update the serial number string descriptor with the data from the unique ID*/
Get_SerialNum();
return (uint8_t *)USBD_StringSerial;
}
/**
* @brief Returns the configuration string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if (speed == USBD_SPEED_HIGH)
{
USBD_GetString((uint8_t *)USBD_CONFIGURATION_HS_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_CONFIGURATION_FS_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Returns the interface string descriptor.
* @param speed: Current device speed
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
if (speed == USBD_SPEED_HIGH)
{
USBD_GetString((uint8_t *)USBD_INTERFACE_HS_STRING, USBD_StrDesc, length);
}
else
{
USBD_GetString((uint8_t *)USBD_INTERFACE_FS_STRING, USBD_StrDesc, length);
}
return USBD_StrDesc;
}
/**
* @brief Create the serial number string descriptor
* @param None
* @retval None
*/
static void Get_SerialNum(void)
{
uint32_t deviceserial0;
uint32_t deviceserial1;
uint32_t deviceserial2;
deviceserial0 = *(uint32_t *)DEVICE_ID1;
deviceserial1 = *(uint32_t *)DEVICE_ID2;
deviceserial2 = *(uint32_t *)DEVICE_ID3;
deviceserial0 += deviceserial2;
if (deviceserial0 != 0U)
{
IntToUnicode(deviceserial0, &USBD_StringSerial[2], 8U);
IntToUnicode(deviceserial1, &USBD_StringSerial[18], 4U);
}
}
#if ((USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1))
/**
* @brief USBD_USR_BOSDescriptor
* return the BOS descriptor
* @param speed : current device speed
* @param length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *USBD_USR_BOSDescriptor(USBD_SpeedTypeDef speed, uint16_t *length)
{
*length = sizeof(USBD_BOSDesc);
return (uint8_t *)USBD_BOSDesc;
}
#endif /* (USBD_LPM_ENABLED == 1) || (USBD_CLASS_BOS_ENABLED == 1) */
#if (USBD_CLASS_USER_STRING_DESC == 1)
/**
* @brief Returns the Class User string descriptor.
* @param speed: Current device speed
* @param idx: index of string descriptor
* @param length: Pointer to data length variable
* @retval Pointer to descriptor buffer
*/
uint8_t *USBD_Class_UserStrDescriptor(USBD_SpeedTypeDef speed, uint8_t idx, uint16_t *length)
{
static uint8_t USBD_StrDesc[255];
return USBD_StrDesc;
}
#endif /* USBD_CLASS_USER_STRING_DESC */
/**
* @brief Convert Hex 32Bits value into char
* @param value: value to convert
* @param pbuf: pointer to the buffer
* @param len: buffer length
* @retval None
*/
static void IntToUnicode(uint32_t value, uint8_t *pbuf, uint8_t len)
{
uint8_t idx = 0U;
for (idx = 0U ; idx < len ; idx ++)
{
if (((value >> 28)) < 0xAU)
{
pbuf[ 2U * idx] = (value >> 28) + '0';
}
else
{
pbuf[2U * idx] = (value >> 28) + 'A' - 10U;
}
value = value << 4;
pbuf[2U * idx + 1] = 0U;
}
}
| 0 |
D://workCode//uploadProject\stm32_mw_usb_device\Core | D://workCode//uploadProject\stm32_mw_usb_device\Core\Src\usbd_ioreq.c | /**
******************************************************************************
* @file usbd_ioreq.c
* @author MCD Application Team
* @brief This file provides the IO requests APIs for control endpoints.
******************************************************************************
* @attention
*
* Copyright (c) 2015 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in 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 "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_IOREQ
* @brief control I/O requests module
* @{
*/
/** @defgroup USBD_IOREQ_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup USBD_IOREQ_Private_Functions
* @{
*/
/**
* @brief USBD_CtlSendData
* send data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be sent
* @retval status
*/
USBD_StatusTypeDef USBD_CtlSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_DATA_IN;
pdev->ep_in[0].total_length = len;
#ifdef USBD_AVOID_PACKET_SPLIT_MPS
pdev->ep_in[0].rem_length = 0U;
#else
pdev->ep_in[0].rem_length = len;
#endif /* USBD_AVOID_PACKET_SPLIT_MPS */
/* Start the transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlContinueSendData
* continue sending data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be sent
* @retval status
*/
USBD_StatusTypeDef USBD_CtlContinueSendData(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Start the next transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlPrepareRx
* receive data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be received
* @retval status
*/
USBD_StatusTypeDef USBD_CtlPrepareRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_DATA_OUT;
pdev->ep_out[0].total_length = len;
#ifdef USBD_AVOID_PACKET_SPLIT_MPS
pdev->ep_out[0].rem_length = 0U;
#else
pdev->ep_out[0].rem_length = len;
#endif /* USBD_AVOID_PACKET_SPLIT_MPS */
/* Start the transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlContinueRx
* continue receive data on the ctl pipe
* @param pdev: device instance
* @param buff: pointer to data buffer
* @param len: length of data to be received
* @retval status
*/
USBD_StatusTypeDef USBD_CtlContinueRx(USBD_HandleTypeDef *pdev,
uint8_t *pbuf, uint32_t len)
{
(void)USBD_LL_PrepareReceive(pdev, 0U, pbuf, len);
return USBD_OK;
}
/**
* @brief USBD_CtlSendStatus
* send zero lzngth packet on the ctl pipe
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_CtlSendStatus(USBD_HandleTypeDef *pdev)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_STATUS_IN;
/* Start the transfer */
(void)USBD_LL_Transmit(pdev, 0x00U, NULL, 0U);
return USBD_OK;
}
/**
* @brief USBD_CtlReceiveStatus
* receive zero lzngth packet on the ctl pipe
* @param pdev: device instance
* @retval status
*/
USBD_StatusTypeDef USBD_CtlReceiveStatus(USBD_HandleTypeDef *pdev)
{
/* Set EP0 State */
pdev->ep0_state = USBD_EP0_STATUS_OUT;
/* Start the transfer */
(void)USBD_LL_PrepareReceive(pdev, 0U, NULL, 0U);
return USBD_OK;
}
/**
* @brief USBD_GetRxCount
* returns the received data length
* @param pdev: device instance
* @param ep_addr: endpoint address
* @retval Rx Data blength
*/
uint32_t USBD_GetRxCount(USBD_HandleTypeDef *pdev, uint8_t ep_addr)
{
return USBD_LL_GetRxDataSize(pdev, ep_addr);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
| 0 |
D://workCode//uploadProject\stm32_oled | D://workCode//uploadProject\stm32_oled\example\physical.h | #ifndef PHYSICAL
#define PHYSICAL
#endif
| 0 |
D://workCode//uploadProject\stm32_oled | D://workCode//uploadProject\stm32_oled\example\test.h | #ifndef TEST_H
#define TEST_H
void demo(void);
#endif
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\CMSIS\core_cm3.c | /**************************************************************************//**
* @file core_cm3.c
* @brief CMSIS Cortex-M3 Core Peripheral Access Layer Source File
* @version V1.30
* @date 30. October 2009
*
* @note
* Copyright (C) 2009 ARM Limited. All rights reserved.
*
* @par
* ARM Limited (ARM) is supplying this software for use with Cortex-M
* processor based microcontrollers. This file can be freely distributed
* within development tools that are supporting such ARM based processors.
*
* @par
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
******************************************************************************/
#include <stdint.h>
/* define compiler specific symbols */
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#endif
/* ################### Compiler specific Intrinsics ########################### */
#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
/* ARM armcc specific functions */
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
__ASM uint32_t __get_PSP(void)
{
mrs r0, psp
bx lr
}
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
__ASM void __set_PSP(uint32_t topOfProcStack)
{
msr psp, r0
bx lr
}
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
__ASM uint32_t __get_MSP(void)
{
mrs r0, msp
bx lr
}
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
__ASM void __set_MSP(uint32_t mainStackPointer)
{
msr msp, r0
bx lr
}
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
__ASM uint32_t __REV16(uint16_t value)
{
rev16 r0, r0
bx lr
}
/**
* @brief Reverse byte order in signed short value with sign extension to integer
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in signed short value with sign extension to integer
*/
__ASM int32_t __REVSH(int16_t value)
{
revsh r0, r0
bx lr
}
#if (__ARMCC_VERSION < 400000)
/**
* @brief Remove the exclusive lock created by ldrex
*
* Removes the exclusive lock which is created by ldrex.
*/
__ASM void __CLREX(void)
{
clrex
}
/**
* @brief Return the Base Priority value
*
* @return BasePriority
*
* Return the content of the base priority register
*/
__ASM uint32_t __get_BASEPRI(void)
{
mrs r0, basepri
bx lr
}
/**
* @brief Set the Base Priority value
*
* @param basePri BasePriority
*
* Set the base priority register
*/
__ASM void __set_BASEPRI(uint32_t basePri)
{
msr basepri, r0
bx lr
}
/**
* @brief Return the Priority Mask value
*
* @return PriMask
*
* Return state of the priority mask bit from the priority mask register
*/
__ASM uint32_t __get_PRIMASK(void)
{
mrs r0, primask
bx lr
}
/**
* @brief Set the Priority Mask value
*
* @param priMask PriMask
*
* Set the priority mask bit in the priority mask register
*/
__ASM void __set_PRIMASK(uint32_t priMask)
{
msr primask, r0
bx lr
}
/**
* @brief Return the Fault Mask value
*
* @return FaultMask
*
* Return the content of the fault mask register
*/
__ASM uint32_t __get_FAULTMASK(void)
{
mrs r0, faultmask
bx lr
}
/**
* @brief Set the Fault Mask value
*
* @param faultMask faultMask value
*
* Set the fault mask register
*/
__ASM void __set_FAULTMASK(uint32_t faultMask)
{
msr faultmask, r0
bx lr
}
/**
* @brief Return the Control Register value
*
* @return Control value
*
* Return the content of the control register
*/
__ASM uint32_t __get_CONTROL(void)
{
mrs r0, control
bx lr
}
/**
* @brief Set the Control Register value
*
* @param control Control value
*
* Set the control register
*/
__ASM void __set_CONTROL(uint32_t control)
{
msr control, r0
bx lr
}
#endif /* __ARMCC_VERSION */
#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/
/* IAR iccarm specific functions */
#pragma diag_suppress=Pe940
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
uint32_t __get_PSP(void)
{
__ASM("mrs r0, psp");
__ASM("bx lr");
}
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
void __set_PSP(uint32_t topOfProcStack)
{
__ASM("msr psp, r0");
__ASM("bx lr");
}
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
uint32_t __get_MSP(void)
{
__ASM("mrs r0, msp");
__ASM("bx lr");
}
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
void __set_MSP(uint32_t topOfMainStack)
{
__ASM("msr msp, r0");
__ASM("bx lr");
}
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
uint32_t __REV16(uint16_t value)
{
__ASM("rev16 r0, r0");
__ASM("bx lr");
}
/**
* @brief Reverse bit order of value
*
* @param value value to reverse
* @return reversed value
*
* Reverse bit order of value
*/
uint32_t __RBIT(uint32_t value)
{
__ASM("rbit r0, r0");
__ASM("bx lr");
}
/**
* @brief LDR Exclusive (8 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 8 bit values)
*/
uint8_t __LDREXB(uint8_t *addr)
{
__ASM("ldrexb r0, [r0]");
__ASM("bx lr");
}
/**
* @brief LDR Exclusive (16 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 16 bit values
*/
uint16_t __LDREXH(uint16_t *addr)
{
__ASM("ldrexh r0, [r0]");
__ASM("bx lr");
}
/**
* @brief LDR Exclusive (32 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 32 bit values
*/
uint32_t __LDREXW(uint32_t *addr)
{
__ASM("ldrex r0, [r0]");
__ASM("bx lr");
}
/**
* @brief STR Exclusive (8 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 8 bit values
*/
uint32_t __STREXB(uint8_t value, uint8_t *addr)
{
__ASM("strexb r0, r0, [r1]");
__ASM("bx lr");
}
/**
* @brief STR Exclusive (16 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 16 bit values
*/
uint32_t __STREXH(uint16_t value, uint16_t *addr)
{
__ASM("strexh r0, r0, [r1]");
__ASM("bx lr");
}
/**
* @brief STR Exclusive (32 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 32 bit values
*/
uint32_t __STREXW(uint32_t value, uint32_t *addr)
{
__ASM("strex r0, r0, [r1]");
__ASM("bx lr");
}
#pragma diag_default=Pe940
#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/
/* GNU gcc specific functions */
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
uint32_t __get_PSP(void) __attribute__( ( naked ) );
uint32_t __get_PSP(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, psp\n\t"
"MOV r0, %0 \n\t"
"BX lr \n\t" : "=r" (result) );
return(result);
}
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
void __set_PSP(uint32_t topOfProcStack) __attribute__( ( naked ) );
void __set_PSP(uint32_t topOfProcStack)
{
__ASM volatile ("MSR psp, %0\n\t"
"BX lr \n\t" : : "r" (topOfProcStack) );
}
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
uint32_t __get_MSP(void) __attribute__( ( naked ) );
uint32_t __get_MSP(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, msp\n\t"
"MOV r0, %0 \n\t"
"BX lr \n\t" : "=r" (result) );
return(result);
}
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
void __set_MSP(uint32_t topOfMainStack) __attribute__( ( naked ) );
void __set_MSP(uint32_t topOfMainStack)
{
__ASM volatile ("MSR msp, %0\n\t"
"BX lr \n\t" : : "r" (topOfMainStack) );
}
/**
* @brief Return the Base Priority value
*
* @return BasePriority
*
* Return the content of the base priority register
*/
uint32_t __get_BASEPRI(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, basepri_max" : "=r" (result) );
return(result);
}
/**
* @brief Set the Base Priority value
*
* @param basePri BasePriority
*
* Set the base priority register
*/
void __set_BASEPRI(uint32_t value)
{
__ASM volatile ("MSR basepri, %0" : : "r" (value) );
}
/**
* @brief Return the Priority Mask value
*
* @return PriMask
*
* Return state of the priority mask bit from the priority mask register
*/
uint32_t __get_PRIMASK(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, primask" : "=r" (result) );
return(result);
}
/**
* @brief Set the Priority Mask value
*
* @param priMask PriMask
*
* Set the priority mask bit in the priority mask register
*/
void __set_PRIMASK(uint32_t priMask)
{
__ASM volatile ("MSR primask, %0" : : "r" (priMask) );
}
/**
* @brief Return the Fault Mask value
*
* @return FaultMask
*
* Return the content of the fault mask register
*/
uint32_t __get_FAULTMASK(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, faultmask" : "=r" (result) );
return(result);
}
/**
* @brief Set the Fault Mask value
*
* @param faultMask faultMask value
*
* Set the fault mask register
*/
void __set_FAULTMASK(uint32_t faultMask)
{
__ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) );
}
/**
* @brief Return the Control Register value
*
* @return Control value
*
* Return the content of the control register
*/
uint32_t __get_CONTROL(void)
{
uint32_t result=0;
__ASM volatile ("MRS %0, control" : "=r" (result) );
return(result);
}
/**
* @brief Set the Control Register value
*
* @param control Control value
*
* Set the control register
*/
void __set_CONTROL(uint32_t control)
{
__ASM volatile ("MSR control, %0" : : "r" (control) );
}
/**
* @brief Reverse byte order in integer value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in integer value
*/
uint32_t __REV(uint32_t value)
{
uint32_t result=0;
__ASM volatile ("rev %0, %1" : "=r" (result) : "r" (value) );
return(result);
}
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
uint32_t __REV16(uint16_t value)
{
uint32_t result=0;
__ASM volatile ("rev16 %0, %1" : "=r" (result) : "r" (value) );
return(result);
}
/**
* @brief Reverse byte order in signed short value with sign extension to integer
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in signed short value with sign extension to integer
*/
int32_t __REVSH(int16_t value)
{
uint32_t result=0;
__ASM volatile ("revsh %0, %1" : "=r" (result) : "r" (value) );
return(result);
}
/**
* @brief Reverse bit order of value
*
* @param value value to reverse
* @return reversed value
*
* Reverse bit order of value
*/
uint32_t __RBIT(uint32_t value)
{
uint32_t result=0;
__ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) );
return(result);
}
/**
* @brief LDR Exclusive (8 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 8 bit value
*/
uint8_t __LDREXB(uint8_t *addr)
{
uint8_t result=0;
__ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) );
return(result);
}
/**
* @brief LDR Exclusive (16 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 16 bit values
*/
uint16_t __LDREXH(uint16_t *addr)
{
uint16_t result=0;
__ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) );
return(result);
}
/**
* @brief LDR Exclusive (32 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 32 bit values
*/
uint32_t __LDREXW(uint32_t *addr)
{
uint32_t result=0;
__ASM volatile ("ldrex %0, [%1]" : "=r" (result) : "r" (addr) );
return(result);
}
/**
* @brief STR Exclusive (8 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 8 bit values
*/
uint32_t __STREXB(uint8_t value, uint8_t *addr)
{
uint32_t result=0;
__ASM volatile ("strexb %0, %2, [%1]" : "=r" (result) : "r" (addr), "r" (value) );
return(result);
}
/**
* @brief STR Exclusive (16 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 16 bit values
*/
uint32_t __STREXH(uint16_t value, uint16_t *addr)
{
uint32_t result=0;
__ASM volatile ("strexh %0, %2, [%1]" : "=r" (result) : "r" (addr), "r" (value) );
return(result);
}
/**
* @brief STR Exclusive (32 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 32 bit values
*/
uint32_t __STREXW(uint32_t value, uint32_t *addr)
{
uint32_t result=0;
__ASM volatile ("strex %0, %2, [%1]" : "=r" (result) : "r" (addr), "r" (value) );
return(result);
}
#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/
/* TASKING carm specific functions */
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all instrinsics,
* Including the CMSIS ones.
*/
#endif
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\CMSIS\core_cm3.h | /**************************************************************************//**
* @file core_cm3.h
* @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File
* @version V1.30
* @date 30. October 2009
*
* @note
* Copyright (C) 2009 ARM Limited. All rights reserved.
*
* @par
* ARM Limited (ARM) is supplying this software for use with Cortex-M
* processor based microcontrollers. This file can be freely distributed
* within development tools that are supporting such ARM based processors.
*
* @par
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
******************************************************************************/
#ifndef __CM3_CORE_H__
#define __CM3_CORE_H__
/** @addtogroup CMSIS_CM3_core_LintCinfiguration CMSIS CM3 Core Lint Configuration
*
* List of Lint messages which will be suppressed and not shown:
* - Error 10: \n
* register uint32_t __regBasePri __asm("basepri"); \n
* Error 10: Expecting ';'
* .
* - Error 530: \n
* return(__regBasePri); \n
* Warning 530: Symbol '__regBasePri' (line 264) not initialized
* .
* - Error 550: \n
* __regBasePri = (basePri & 0x1ff); \n
* Warning 550: Symbol '__regBasePri' (line 271) not accessed
* .
* - Error 754: \n
* uint32_t RESERVED0[24]; \n
* Info 754: local structure member '<some, not used in the HAL>' (line 109, file ./cm3_core.h) not referenced
* .
* - Error 750: \n
* #define __CM3_CORE_H__ \n
* Info 750: local macro '__CM3_CORE_H__' (line 43, file./cm3_core.h) not referenced
* .
* - Error 528: \n
* static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) \n
* Warning 528: Symbol 'NVIC_DisableIRQ(unsigned int)' (line 419, file ./cm3_core.h) not referenced
* .
* - Error 751: \n
* } InterruptType_Type; \n
* Info 751: local typedef 'InterruptType_Type' (line 170, file ./cm3_core.h) not referenced
* .
* Note: To re-enable a Message, insert a space before 'lint' *
*
*/
/*lint -save */
/*lint -e10 */
/*lint -e530 */
/*lint -e550 */
/*lint -e754 */
/*lint -e750 */
/*lint -e528 */
/*lint -e751 */
/** @addtogroup CMSIS_CM3_core_definitions CM3 Core Definitions
This file defines all structures and symbols for CMSIS core:
- CMSIS version number
- Cortex-M core registers and bitfields
- Cortex-M core peripheral base address
@{
*/
#ifdef __cplusplus
extern "C" {
#endif
#define __CM3_CMSIS_VERSION_MAIN (0x01) /*!< [31:16] CMSIS HAL main version */
#define __CM3_CMSIS_VERSION_SUB (0x30) /*!< [15:0] CMSIS HAL sub version */
#define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | __CM3_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */
#define __CORTEX_M (0x03) /*!< Cortex core */
#include <stdint.h> /* Include standard types */
#if defined (__ICCARM__)
#include <intrinsics.h> /* IAR Intrinsics */
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 4 /*!< standard definition for NVIC Priority Bits */
#endif
/**
* IO definitions
*
* define access restrictions to peripheral registers
*/
#ifdef __cplusplus
#define __I volatile /*!< defines 'read only' permissions */
#else
#define __I volatile const /*!< defines 'read only' permissions */
#endif
#define __O volatile /*!< defines 'write only' permissions */
#define __IO volatile /*!< defines 'read / write' permissions */
/*******************************************************************************
* Register Abstraction
******************************************************************************/
/** @addtogroup CMSIS_CM3_core_register CMSIS CM3 Core Register
@{
*/
/** @addtogroup CMSIS_CM3_NVIC CMSIS CM3 NVIC
memory mapped structure for Nested Vectored Interrupt Controller (NVIC)
@{
*/
typedef struct
{
__IO uint32_t ISER[8]; /*!< Offset: 0x000 Interrupt Set Enable Register */
uint32_t RESERVED0[24];
__IO uint32_t ICER[8]; /*!< Offset: 0x080 Interrupt Clear Enable Register */
uint32_t RSERVED1[24];
__IO uint32_t ISPR[8]; /*!< Offset: 0x100 Interrupt Set Pending Register */
uint32_t RESERVED2[24];
__IO uint32_t ICPR[8]; /*!< Offset: 0x180 Interrupt Clear Pending Register */
uint32_t RESERVED3[24];
__IO uint32_t IABR[8]; /*!< Offset: 0x200 Interrupt Active bit Register */
uint32_t RESERVED4[56];
__IO uint8_t IP[240]; /*!< Offset: 0x300 Interrupt Priority Register (8Bit wide) */
uint32_t RESERVED5[644];
__O uint32_t STIR; /*!< Offset: 0xE00 Software Trigger Interrupt Register */
} NVIC_Type;
/*@}*/ /* end of group CMSIS_CM3_NVIC */
/** @addtogroup CMSIS_CM3_SCB CMSIS CM3 SCB
memory mapped structure for System Control Block (SCB)
@{
*/
typedef struct
{
__I uint32_t CPUID; /*!< Offset: 0x00 CPU ID Base Register */
__IO uint32_t ICSR; /*!< Offset: 0x04 Interrupt Control State Register */
__IO uint32_t VTOR; /*!< Offset: 0x08 Vector Table Offset Register */
__IO uint32_t AIRCR; /*!< Offset: 0x0C Application Interrupt / Reset Control Register */
__IO uint32_t SCR; /*!< Offset: 0x10 System Control Register */
__IO uint32_t CCR; /*!< Offset: 0x14 Configuration Control Register */
__IO uint8_t SHP[12]; /*!< Offset: 0x18 System Handlers Priority Registers (4-7, 8-11, 12-15) */
__IO uint32_t SHCSR; /*!< Offset: 0x24 System Handler Control and State Register */
__IO uint32_t CFSR; /*!< Offset: 0x28 Configurable Fault Status Register */
__IO uint32_t HFSR; /*!< Offset: 0x2C Hard Fault Status Register */
__IO uint32_t DFSR; /*!< Offset: 0x30 Debug Fault Status Register */
__IO uint32_t MMFAR; /*!< Offset: 0x34 Mem Manage Address Register */
__IO uint32_t BFAR; /*!< Offset: 0x38 Bus Fault Address Register */
__IO uint32_t AFSR; /*!< Offset: 0x3C Auxiliary Fault Status Register */
__I uint32_t PFR[2]; /*!< Offset: 0x40 Processor Feature Register */
__I uint32_t DFR; /*!< Offset: 0x48 Debug Feature Register */
__I uint32_t ADR; /*!< Offset: 0x4C Auxiliary Feature Register */
__I uint32_t MMFR[4]; /*!< Offset: 0x50 Memory Model Feature Register */
__I uint32_t ISAR[5]; /*!< Offset: 0x60 ISA Feature Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFul << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFul << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFul << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFul << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1ul << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1ul << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1ul << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1ul << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1ul << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1ul << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1ul << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFul << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */
#define SCB_ICSR_RETTOBASE_Msk (1ul << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFul << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */
#define SCB_VTOR_TBLBASE_Msk (0x1FFul << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */
#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */
#define SCB_VTOR_TBLOFF_Msk (0x3FFFFFul << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFul << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFul << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1ul << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */
#define SCB_AIRCR_PRIGROUP_Msk (7ul << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1ul << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1ul << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
#define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */
#define SCB_AIRCR_VECTRESET_Msk (1ul << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1ul << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1ul << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1ul << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1ul << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */
#define SCB_CCR_BFHFNMIGN_Msk (1ul << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */
#define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */
#define SCB_CCR_DIV_0_TRP_Msk (1ul << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1ul << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
#define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */
#define SCB_CCR_USERSETMPEND_Msk (1ul << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */
#define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */
#define SCB_CCR_NONBASETHRDENA_Msk (1ul << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */
#define SCB_SHCSR_USGFAULTENA_Msk (1ul << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */
#define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */
#define SCB_SHCSR_BUSFAULTENA_Msk (1ul << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */
#define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */
#define SCB_SHCSR_MEMFAULTENA_Msk (1ul << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */
#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1ul << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
#define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */
#define SCB_SHCSR_BUSFAULTPENDED_Msk (1ul << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */
#define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */
#define SCB_SHCSR_MEMFAULTPENDED_Msk (1ul << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */
#define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */
#define SCB_SHCSR_USGFAULTPENDED_Msk (1ul << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */
#define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */
#define SCB_SHCSR_SYSTICKACT_Msk (1ul << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */
#define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */
#define SCB_SHCSR_PENDSVACT_Msk (1ul << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */
#define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */
#define SCB_SHCSR_MONITORACT_Msk (1ul << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */
#define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */
#define SCB_SHCSR_SVCALLACT_Msk (1ul << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */
#define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */
#define SCB_SHCSR_USGFAULTACT_Msk (1ul << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */
#define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */
#define SCB_SHCSR_BUSFAULTACT_Msk (1ul << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */
#define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */
#define SCB_SHCSR_MEMFAULTACT_Msk (1ul << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */
/* SCB Configurable Fault Status Registers Definitions */
#define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */
#define SCB_CFSR_USGFAULTSR_Msk (0xFFFFul << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */
#define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */
#define SCB_CFSR_BUSFAULTSR_Msk (0xFFul << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */
#define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */
#define SCB_CFSR_MEMFAULTSR_Msk (0xFFul << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
/* SCB Hard Fault Status Registers Definitions */
#define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */
#define SCB_HFSR_DEBUGEVT_Msk (1ul << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */
#define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */
#define SCB_HFSR_FORCED_Msk (1ul << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */
#define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */
#define SCB_HFSR_VECTTBL_Msk (1ul << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */
/* SCB Debug Fault Status Register Definitions */
#define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */
#define SCB_DFSR_EXTERNAL_Msk (1ul << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */
#define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */
#define SCB_DFSR_VCATCH_Msk (1ul << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */
#define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */
#define SCB_DFSR_DWTTRAP_Msk (1ul << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */
#define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */
#define SCB_DFSR_BKPT_Msk (1ul << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */
#define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */
#define SCB_DFSR_HALTED_Msk (1ul << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */
/*@}*/ /* end of group CMSIS_CM3_SCB */
/** @addtogroup CMSIS_CM3_SysTick CMSIS CM3 SysTick
memory mapped structure for SysTick
@{
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x00 SysTick Control and Status Register */
__IO uint32_t LOAD; /*!< Offset: 0x04 SysTick Reload Value Register */
__IO uint32_t VAL; /*!< Offset: 0x08 SysTick Current Value Register */
__I uint32_t CALIB; /*!< Offset: 0x0C SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1ul << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1ul << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1ul << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1ul << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFul << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFul << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1ul << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1ul << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFul << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */
/*@}*/ /* end of group CMSIS_CM3_SysTick */
/** @addtogroup CMSIS_CM3_ITM CMSIS CM3 ITM
memory mapped structure for Instrumentation Trace Macrocell (ITM)
@{
*/
typedef struct
{
__O union
{
__O uint8_t u8; /*!< Offset: ITM Stimulus Port 8-bit */
__O uint16_t u16; /*!< Offset: ITM Stimulus Port 16-bit */
__O uint32_t u32; /*!< Offset: ITM Stimulus Port 32-bit */
} PORT [32]; /*!< Offset: 0x00 ITM Stimulus Port Registers */
uint32_t RESERVED0[864];
__IO uint32_t TER; /*!< Offset: ITM Trace Enable Register */
uint32_t RESERVED1[15];
__IO uint32_t TPR; /*!< Offset: ITM Trace Privilege Register */
uint32_t RESERVED2[15];
__IO uint32_t TCR; /*!< Offset: ITM Trace Control Register */
uint32_t RESERVED3[29];
__IO uint32_t IWR; /*!< Offset: ITM Integration Write Register */
__IO uint32_t IRR; /*!< Offset: ITM Integration Read Register */
__IO uint32_t IMCR; /*!< Offset: ITM Integration Mode Control Register */
uint32_t RESERVED4[43];
__IO uint32_t LAR; /*!< Offset: ITM Lock Access Register */
__IO uint32_t LSR; /*!< Offset: ITM Lock Status Register */
uint32_t RESERVED5[6];
__I uint32_t PID4; /*!< Offset: ITM Peripheral Identification Register #4 */
__I uint32_t PID5; /*!< Offset: ITM Peripheral Identification Register #5 */
__I uint32_t PID6; /*!< Offset: ITM Peripheral Identification Register #6 */
__I uint32_t PID7; /*!< Offset: ITM Peripheral Identification Register #7 */
__I uint32_t PID0; /*!< Offset: ITM Peripheral Identification Register #0 */
__I uint32_t PID1; /*!< Offset: ITM Peripheral Identification Register #1 */
__I uint32_t PID2; /*!< Offset: ITM Peripheral Identification Register #2 */
__I uint32_t PID3; /*!< Offset: ITM Peripheral Identification Register #3 */
__I uint32_t CID0; /*!< Offset: ITM Component Identification Register #0 */
__I uint32_t CID1; /*!< Offset: ITM Component Identification Register #1 */
__I uint32_t CID2; /*!< Offset: ITM Component Identification Register #2 */
__I uint32_t CID3; /*!< Offset: ITM Component Identification Register #3 */
} ITM_Type;
/* ITM Trace Privilege Register Definitions */
#define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */
#define ITM_TPR_PRIVMASK_Msk (0xFul << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */
/* ITM Trace Control Register Definitions */
#define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */
#define ITM_TCR_BUSY_Msk (1ul << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */
#define ITM_TCR_ATBID_Pos 16 /*!< ITM TCR: ATBID Position */
#define ITM_TCR_ATBID_Msk (0x7Ful << ITM_TCR_ATBID_Pos) /*!< ITM TCR: ATBID Mask */
#define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */
#define ITM_TCR_TSPrescale_Msk (3ul << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */
#define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */
#define ITM_TCR_SWOENA_Msk (1ul << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */
#define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */
#define ITM_TCR_DWTENA_Msk (1ul << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */
#define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */
#define ITM_TCR_SYNCENA_Msk (1ul << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */
#define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */
#define ITM_TCR_TSENA_Msk (1ul << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */
#define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */
#define ITM_TCR_ITMENA_Msk (1ul << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */
/* ITM Integration Write Register Definitions */
#define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */
#define ITM_IWR_ATVALIDM_Msk (1ul << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */
/* ITM Integration Read Register Definitions */
#define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */
#define ITM_IRR_ATREADYM_Msk (1ul << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */
/* ITM Integration Mode Control Register Definitions */
#define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */
#define ITM_IMCR_INTEGRATION_Msk (1ul << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */
/* ITM Lock Status Register Definitions */
#define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */
#define ITM_LSR_ByteAcc_Msk (1ul << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */
#define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */
#define ITM_LSR_Access_Msk (1ul << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */
#define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */
#define ITM_LSR_Present_Msk (1ul << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */
/*@}*/ /* end of group CMSIS_CM3_ITM */
/** @addtogroup CMSIS_CM3_InterruptType CMSIS CM3 Interrupt Type
memory mapped structure for Interrupt Type
@{
*/
typedef struct
{
uint32_t RESERVED0;
__I uint32_t ICTR; /*!< Offset: 0x04 Interrupt Control Type Register */
#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
__IO uint32_t ACTLR; /*!< Offset: 0x08 Auxiliary Control Register */
#else
uint32_t RESERVED1;
#endif
} InterruptType_Type;
/* Interrupt Controller Type Register Definitions */
#define InterruptType_ICTR_INTLINESNUM_Pos 0 /*!< InterruptType ICTR: INTLINESNUM Position */
#define InterruptType_ICTR_INTLINESNUM_Msk (0x1Ful << InterruptType_ICTR_INTLINESNUM_Pos) /*!< InterruptType ICTR: INTLINESNUM Mask */
/* Auxiliary Control Register Definitions */
#define InterruptType_ACTLR_DISFOLD_Pos 2 /*!< InterruptType ACTLR: DISFOLD Position */
#define InterruptType_ACTLR_DISFOLD_Msk (1ul << InterruptType_ACTLR_DISFOLD_Pos) /*!< InterruptType ACTLR: DISFOLD Mask */
#define InterruptType_ACTLR_DISDEFWBUF_Pos 1 /*!< InterruptType ACTLR: DISDEFWBUF Position */
#define InterruptType_ACTLR_DISDEFWBUF_Msk (1ul << InterruptType_ACTLR_DISDEFWBUF_Pos) /*!< InterruptType ACTLR: DISDEFWBUF Mask */
#define InterruptType_ACTLR_DISMCYCINT_Pos 0 /*!< InterruptType ACTLR: DISMCYCINT Position */
#define InterruptType_ACTLR_DISMCYCINT_Msk (1ul << InterruptType_ACTLR_DISMCYCINT_Pos) /*!< InterruptType ACTLR: DISMCYCINT Mask */
/*@}*/ /* end of group CMSIS_CM3_InterruptType */
#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)
/** @addtogroup CMSIS_CM3_MPU CMSIS CM3 MPU
memory mapped structure for Memory Protection Unit (MPU)
@{
*/
typedef struct
{
__I uint32_t TYPE; /*!< Offset: 0x00 MPU Type Register */
__IO uint32_t CTRL; /*!< Offset: 0x04 MPU Control Register */
__IO uint32_t RNR; /*!< Offset: 0x08 MPU Region RNRber Register */
__IO uint32_t RBAR; /*!< Offset: 0x0C MPU Region Base Address Register */
__IO uint32_t RASR; /*!< Offset: 0x10 MPU Region Attribute and Size Register */
__IO uint32_t RBAR_A1; /*!< Offset: 0x14 MPU Alias 1 Region Base Address Register */
__IO uint32_t RASR_A1; /*!< Offset: 0x18 MPU Alias 1 Region Attribute and Size Register */
__IO uint32_t RBAR_A2; /*!< Offset: 0x1C MPU Alias 2 Region Base Address Register */
__IO uint32_t RASR_A2; /*!< Offset: 0x20 MPU Alias 2 Region Attribute and Size Register */
__IO uint32_t RBAR_A3; /*!< Offset: 0x24 MPU Alias 3 Region Base Address Register */
__IO uint32_t RASR_A3; /*!< Offset: 0x28 MPU Alias 3 Region Attribute and Size Register */
} MPU_Type;
/* MPU Type Register */
#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */
#define MPU_TYPE_IREGION_Msk (0xFFul << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */
#define MPU_TYPE_DREGION_Msk (0xFFul << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */
#define MPU_TYPE_SEPARATE_Msk (1ul << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */
/* MPU Control Register */
#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */
#define MPU_CTRL_PRIVDEFENA_Msk (1ul << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */
#define MPU_CTRL_HFNMIENA_Msk (1ul << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */
#define MPU_CTRL_ENABLE_Msk (1ul << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */
/* MPU Region Number Register */
#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */
#define MPU_RNR_REGION_Msk (0xFFul << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */
/* MPU Region Base Address Register */
#define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */
#define MPU_RBAR_ADDR_Msk (0x7FFFFFFul << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */
#define MPU_RBAR_VALID_Msk (1ul << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */
#define MPU_RBAR_REGION_Msk (0xFul << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */
/* MPU Region Attribute and Size Register */
#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: XN Position */
#define MPU_RASR_XN_Msk (1ul << MPU_RASR_XN_Pos) /*!< MPU RASR: XN Mask */
#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: AP Position */
#define MPU_RASR_AP_Msk (7ul << MPU_RASR_AP_Pos) /*!< MPU RASR: AP Mask */
#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: TEX Position */
#define MPU_RASR_TEX_Msk (7ul << MPU_RASR_TEX_Pos) /*!< MPU RASR: TEX Mask */
#define MPU_RASR_S_Pos 18 /*!< MPU RASR: Shareable bit Position */
#define MPU_RASR_S_Msk (1ul << MPU_RASR_S_Pos) /*!< MPU RASR: Shareable bit Mask */
#define MPU_RASR_C_Pos 17 /*!< MPU RASR: Cacheable bit Position */
#define MPU_RASR_C_Msk (1ul << MPU_RASR_C_Pos) /*!< MPU RASR: Cacheable bit Mask */
#define MPU_RASR_B_Pos 16 /*!< MPU RASR: Bufferable bit Position */
#define MPU_RASR_B_Msk (1ul << MPU_RASR_B_Pos) /*!< MPU RASR: Bufferable bit Mask */
#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */
#define MPU_RASR_SRD_Msk (0xFFul << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */
#define MPU_RASR_SIZE_Msk (0x1Ful << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
#define MPU_RASR_ENA_Pos 0 /*!< MPU RASR: Region enable bit Position */
#define MPU_RASR_ENA_Msk (0x1Ful << MPU_RASR_ENA_Pos) /*!< MPU RASR: Region enable bit Disable Mask */
/*@}*/ /* end of group CMSIS_CM3_MPU */
#endif
/** @addtogroup CMSIS_CM3_CoreDebug CMSIS CM3 Core Debug
memory mapped structure for Core Debug Register
@{
*/
typedef struct
{
__IO uint32_t DHCSR; /*!< Offset: 0x00 Debug Halting Control and Status Register */
__O uint32_t DCRSR; /*!< Offset: 0x04 Debug Core Register Selector Register */
__IO uint32_t DCRDR; /*!< Offset: 0x08 Debug Core Register Data Register */
__IO uint32_t DEMCR; /*!< Offset: 0x0C Debug Exception and Monitor Control Register */
} CoreDebug_Type;
/* Debug Halting Control and Status Register */
#define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */
#define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFul << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */
#define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */
#define CoreDebug_DHCSR_S_RESET_ST_Msk (1ul << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */
#define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
#define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1ul << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
#define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */
#define CoreDebug_DHCSR_S_LOCKUP_Msk (1ul << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */
#define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */
#define CoreDebug_DHCSR_S_SLEEP_Msk (1ul << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */
#define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */
#define CoreDebug_DHCSR_S_HALT_Msk (1ul << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */
#define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */
#define CoreDebug_DHCSR_S_REGRDY_Msk (1ul << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */
#define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
#define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1ul << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
#define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */
#define CoreDebug_DHCSR_C_MASKINTS_Msk (1ul << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */
#define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */
#define CoreDebug_DHCSR_C_STEP_Msk (1ul << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */
#define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */
#define CoreDebug_DHCSR_C_HALT_Msk (1ul << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */
#define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */
#define CoreDebug_DHCSR_C_DEBUGEN_Msk (1ul << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
/* Debug Core Register Selector Register */
#define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */
#define CoreDebug_DCRSR_REGWnR_Msk (1ul << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */
#define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */
#define CoreDebug_DCRSR_REGSEL_Msk (0x1Ful << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */
/* Debug Exception and Monitor Control Register */
#define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */
#define CoreDebug_DEMCR_TRCENA_Msk (1ul << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */
#define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */
#define CoreDebug_DEMCR_MON_REQ_Msk (1ul << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */
#define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */
#define CoreDebug_DEMCR_MON_STEP_Msk (1ul << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */
#define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */
#define CoreDebug_DEMCR_MON_PEND_Msk (1ul << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */
#define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */
#define CoreDebug_DEMCR_MON_EN_Msk (1ul << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */
#define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */
#define CoreDebug_DEMCR_VC_HARDERR_Msk (1ul << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */
#define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */
#define CoreDebug_DEMCR_VC_INTERR_Msk (1ul << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */
#define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */
#define CoreDebug_DEMCR_VC_BUSERR_Msk (1ul << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */
#define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */
#define CoreDebug_DEMCR_VC_STATERR_Msk (1ul << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */
#define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */
#define CoreDebug_DEMCR_VC_CHKERR_Msk (1ul << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */
#define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */
#define CoreDebug_DEMCR_VC_NOCPERR_Msk (1ul << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
#define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */
#define CoreDebug_DEMCR_VC_MMERR_Msk (1ul << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */
#define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */
#define CoreDebug_DEMCR_VC_CORERESET_Msk (1ul << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */
/*@}*/ /* end of group CMSIS_CM3_CoreDebug */
/* Memory mapping of Cortex-M3 Hardware */
#define SCS_BASE (0xE000E000) /*!< System Control Space Base Address */
#define ITM_BASE (0xE0000000) /*!< ITM Base Address */
#define CoreDebug_BASE (0xE000EDF0) /*!< Core Debug Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00) /*!< System Control Block Base Address */
#define InterruptType ((InterruptType_Type *) SCS_BASE) /*!< Interrupt Type Register */
#define SCB ((SCB_Type *) SCB_BASE) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE) /*!< NVIC configuration struct */
#define ITM ((ITM_Type *) ITM_BASE) /*!< ITM configuration struct */
#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */
#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)
#define MPU_BASE (SCS_BASE + 0x0D90) /*!< Memory Protection Unit */
#define MPU ((MPU_Type*) MPU_BASE) /*!< Memory Protection Unit */
#endif
/*@}*/ /* end of group CMSIS_CM3_core_register */
/*******************************************************************************
* Hardware Abstraction Layer
******************************************************************************/
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#endif
/* ################### Compiler specific Intrinsics ########################### */
#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
/* ARM armcc specific functions */
#define __enable_fault_irq __enable_fiq
#define __disable_fault_irq __disable_fiq
#define __NOP __nop
#define __WFI __wfi
#define __WFE __wfe
#define __SEV __sev
#define __ISB() __isb(0)
#define __DSB() __dsb(0)
#define __DMB() __dmb(0)
#define __REV __rev
#define __RBIT __rbit
#define __LDREXB(ptr) ((unsigned char ) __ldrex(ptr))
#define __LDREXH(ptr) ((unsigned short) __ldrex(ptr))
#define __LDREXW(ptr) ((unsigned int ) __ldrex(ptr))
#define __STREXB(value, ptr) __strex(value, ptr)
#define __STREXH(value, ptr) __strex(value, ptr)
#define __STREXW(value, ptr) __strex(value, ptr)
/* intrinsic unsigned long long __ldrexd(volatile void *ptr) */
/* intrinsic int __strexd(unsigned long long val, volatile void *ptr) */
/* intrinsic void __enable_irq(); */
/* intrinsic void __disable_irq(); */
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
extern uint32_t __get_PSP(void);
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
extern void __set_PSP(uint32_t topOfProcStack);
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
extern uint32_t __get_MSP(void);
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
extern void __set_MSP(uint32_t topOfMainStack);
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
extern uint32_t __REV16(uint16_t value);
/**
* @brief Reverse byte order in signed short value with sign extension to integer
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in signed short value with sign extension to integer
*/
extern int32_t __REVSH(int16_t value);
#if (__ARMCC_VERSION < 400000)
/**
* @brief Remove the exclusive lock created by ldrex
*
* Removes the exclusive lock which is created by ldrex.
*/
extern void __CLREX(void);
/**
* @brief Return the Base Priority value
*
* @return BasePriority
*
* Return the content of the base priority register
*/
extern uint32_t __get_BASEPRI(void);
/**
* @brief Set the Base Priority value
*
* @param basePri BasePriority
*
* Set the base priority register
*/
extern void __set_BASEPRI(uint32_t basePri);
/**
* @brief Return the Priority Mask value
*
* @return PriMask
*
* Return state of the priority mask bit from the priority mask register
*/
extern uint32_t __get_PRIMASK(void);
/**
* @brief Set the Priority Mask value
*
* @param priMask PriMask
*
* Set the priority mask bit in the priority mask register
*/
extern void __set_PRIMASK(uint32_t priMask);
/**
* @brief Return the Fault Mask value
*
* @return FaultMask
*
* Return the content of the fault mask register
*/
extern uint32_t __get_FAULTMASK(void);
/**
* @brief Set the Fault Mask value
*
* @param faultMask faultMask value
*
* Set the fault mask register
*/
extern void __set_FAULTMASK(uint32_t faultMask);
/**
* @brief Return the Control Register value
*
* @return Control value
*
* Return the content of the control register
*/
extern uint32_t __get_CONTROL(void);
/**
* @brief Set the Control Register value
*
* @param control Control value
*
* Set the control register
*/
extern void __set_CONTROL(uint32_t control);
#else /* (__ARMCC_VERSION >= 400000) */
/**
* @brief Remove the exclusive lock created by ldrex
*
* Removes the exclusive lock which is created by ldrex.
*/
#define __CLREX __clrex
/**
* @brief Return the Base Priority value
*
* @return BasePriority
*
* Return the content of the base priority register
*/
static __INLINE uint32_t __get_BASEPRI(void)
{
register uint32_t __regBasePri __ASM("basepri");
return(__regBasePri);
}
/**
* @brief Set the Base Priority value
*
* @param basePri BasePriority
*
* Set the base priority register
*/
static __INLINE void __set_BASEPRI(uint32_t basePri)
{
register uint32_t __regBasePri __ASM("basepri");
__regBasePri = (basePri & 0xff);
}
/**
* @brief Return the Priority Mask value
*
* @return PriMask
*
* Return state of the priority mask bit from the priority mask register
*/
static __INLINE uint32_t __get_PRIMASK(void)
{
register uint32_t __regPriMask __ASM("primask");
return(__regPriMask);
}
/**
* @brief Set the Priority Mask value
*
* @param priMask PriMask
*
* Set the priority mask bit in the priority mask register
*/
static __INLINE void __set_PRIMASK(uint32_t priMask)
{
register uint32_t __regPriMask __ASM("primask");
__regPriMask = (priMask);
}
/**
* @brief Return the Fault Mask value
*
* @return FaultMask
*
* Return the content of the fault mask register
*/
static __INLINE uint32_t __get_FAULTMASK(void)
{
register uint32_t __regFaultMask __ASM("faultmask");
return(__regFaultMask);
}
/**
* @brief Set the Fault Mask value
*
* @param faultMask faultMask value
*
* Set the fault mask register
*/
static __INLINE void __set_FAULTMASK(uint32_t faultMask)
{
register uint32_t __regFaultMask __ASM("faultmask");
__regFaultMask = (faultMask & 1);
}
/**
* @brief Return the Control Register value
*
* @return Control value
*
* Return the content of the control register
*/
static __INLINE uint32_t __get_CONTROL(void)
{
register uint32_t __regControl __ASM("control");
return(__regControl);
}
/**
* @brief Set the Control Register value
*
* @param control Control value
*
* Set the control register
*/
static __INLINE void __set_CONTROL(uint32_t control)
{
register uint32_t __regControl __ASM("control");
__regControl = control;
}
#endif /* __ARMCC_VERSION */
#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/
/* IAR iccarm specific functions */
#define __enable_irq __enable_interrupt /*!< global Interrupt enable */
#define __disable_irq __disable_interrupt /*!< global Interrupt disable */
static __INLINE void __enable_fault_irq() { __ASM ("cpsie f"); }
static __INLINE void __disable_fault_irq() { __ASM ("cpsid f"); }
#define __NOP __no_operation /*!< no operation intrinsic in IAR Compiler */
static __INLINE void __WFI() { __ASM ("wfi"); }
static __INLINE void __WFE() { __ASM ("wfe"); }
static __INLINE void __SEV() { __ASM ("sev"); }
static __INLINE void __CLREX() { __ASM ("clrex"); }
/* intrinsic void __ISB(void) */
/* intrinsic void __DSB(void) */
/* intrinsic void __DMB(void) */
/* intrinsic void __set_PRIMASK(); */
/* intrinsic void __get_PRIMASK(); */
/* intrinsic void __set_FAULTMASK(); */
/* intrinsic void __get_FAULTMASK(); */
/* intrinsic uint32_t __REV(uint32_t value); */
/* intrinsic uint32_t __REVSH(uint32_t value); */
/* intrinsic unsigned long __STREX(unsigned long, unsigned long); */
/* intrinsic unsigned long __LDREX(unsigned long *); */
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
extern uint32_t __get_PSP(void);
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
extern void __set_PSP(uint32_t topOfProcStack);
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
extern uint32_t __get_MSP(void);
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
extern void __set_MSP(uint32_t topOfMainStack);
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
extern uint32_t __REV16(uint16_t value);
/**
* @brief Reverse bit order of value
*
* @param value value to reverse
* @return reversed value
*
* Reverse bit order of value
*/
extern uint32_t __RBIT(uint32_t value);
/**
* @brief LDR Exclusive (8 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 8 bit values)
*/
extern uint8_t __LDREXB(uint8_t *addr);
/**
* @brief LDR Exclusive (16 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 16 bit values
*/
extern uint16_t __LDREXH(uint16_t *addr);
/**
* @brief LDR Exclusive (32 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 32 bit values
*/
extern uint32_t __LDREXW(uint32_t *addr);
/**
* @brief STR Exclusive (8 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 8 bit values
*/
extern uint32_t __STREXB(uint8_t value, uint8_t *addr);
/**
* @brief STR Exclusive (16 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 16 bit values
*/
extern uint32_t __STREXH(uint16_t value, uint16_t *addr);
/**
* @brief STR Exclusive (32 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 32 bit values
*/
extern uint32_t __STREXW(uint32_t value, uint32_t *addr);
#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/
/* GNU gcc specific functions */
static __INLINE void __enable_irq() { __ASM volatile ("cpsie i"); }
static __INLINE void __disable_irq() { __ASM volatile ("cpsid i"); }
static __INLINE void __enable_fault_irq() { __ASM volatile ("cpsie f"); }
static __INLINE void __disable_fault_irq() { __ASM volatile ("cpsid f"); }
static __INLINE void __NOP() { __ASM volatile ("nop"); }
static __INLINE void __WFI() { __ASM volatile ("wfi"); }
static __INLINE void __WFE() { __ASM volatile ("wfe"); }
static __INLINE void __SEV() { __ASM volatile ("sev"); }
static __INLINE void __ISB() { __ASM volatile ("isb"); }
static __INLINE void __DSB() { __ASM volatile ("dsb"); }
static __INLINE void __DMB() { __ASM volatile ("dmb"); }
static __INLINE void __CLREX() { __ASM volatile ("clrex"); }
/**
* @brief Return the Process Stack Pointer
*
* @return ProcessStackPointer
*
* Return the actual process stack pointer
*/
extern uint32_t __get_PSP(void);
/**
* @brief Set the Process Stack Pointer
*
* @param topOfProcStack Process Stack Pointer
*
* Assign the value ProcessStackPointer to the MSP
* (process stack pointer) Cortex processor register
*/
extern void __set_PSP(uint32_t topOfProcStack);
/**
* @brief Return the Main Stack Pointer
*
* @return Main Stack Pointer
*
* Return the current value of the MSP (main stack pointer)
* Cortex processor register
*/
extern uint32_t __get_MSP(void);
/**
* @brief Set the Main Stack Pointer
*
* @param topOfMainStack Main Stack Pointer
*
* Assign the value mainStackPointer to the MSP
* (main stack pointer) Cortex processor register
*/
extern void __set_MSP(uint32_t topOfMainStack);
/**
* @brief Return the Base Priority value
*
* @return BasePriority
*
* Return the content of the base priority register
*/
extern uint32_t __get_BASEPRI(void);
/**
* @brief Set the Base Priority value
*
* @param basePri BasePriority
*
* Set the base priority register
*/
extern void __set_BASEPRI(uint32_t basePri);
/**
* @brief Return the Priority Mask value
*
* @return PriMask
*
* Return state of the priority mask bit from the priority mask register
*/
extern uint32_t __get_PRIMASK(void);
/**
* @brief Set the Priority Mask value
*
* @param priMask PriMask
*
* Set the priority mask bit in the priority mask register
*/
extern void __set_PRIMASK(uint32_t priMask);
/**
* @brief Return the Fault Mask value
*
* @return FaultMask
*
* Return the content of the fault mask register
*/
extern uint32_t __get_FAULTMASK(void);
/**
* @brief Set the Fault Mask value
*
* @param faultMask faultMask value
*
* Set the fault mask register
*/
extern void __set_FAULTMASK(uint32_t faultMask);
/**
* @brief Return the Control Register value
*
* @return Control value
*
* Return the content of the control register
*/
extern uint32_t __get_CONTROL(void);
/**
* @brief Set the Control Register value
*
* @param control Control value
*
* Set the control register
*/
extern void __set_CONTROL(uint32_t control);
/**
* @brief Reverse byte order in integer value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in integer value
*/
extern uint32_t __REV(uint32_t value);
/**
* @brief Reverse byte order in unsigned short value
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in unsigned short value
*/
extern uint32_t __REV16(uint16_t value);
/**
* @brief Reverse byte order in signed short value with sign extension to integer
*
* @param value value to reverse
* @return reversed value
*
* Reverse byte order in signed short value with sign extension to integer
*/
extern int32_t __REVSH(int16_t value);
/**
* @brief Reverse bit order of value
*
* @param value value to reverse
* @return reversed value
*
* Reverse bit order of value
*/
extern uint32_t __RBIT(uint32_t value);
/**
* @brief LDR Exclusive (8 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 8 bit value
*/
extern uint8_t __LDREXB(uint8_t *addr);
/**
* @brief LDR Exclusive (16 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 16 bit values
*/
extern uint16_t __LDREXH(uint16_t *addr);
/**
* @brief LDR Exclusive (32 bit)
*
* @param *addr address pointer
* @return value of (*address)
*
* Exclusive LDR command for 32 bit values
*/
extern uint32_t __LDREXW(uint32_t *addr);
/**
* @brief STR Exclusive (8 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 8 bit values
*/
extern uint32_t __STREXB(uint8_t value, uint8_t *addr);
/**
* @brief STR Exclusive (16 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 16 bit values
*/
extern uint32_t __STREXH(uint16_t value, uint16_t *addr);
/**
* @brief STR Exclusive (32 bit)
*
* @param value value to store
* @param *addr address pointer
* @return successful / failed
*
* Exclusive STR command for 32 bit values
*/
extern uint32_t __STREXW(uint32_t value, uint32_t *addr);
#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/
/* TASKING carm specific functions */
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all instrinsics,
* Including the CMSIS ones.
*/
#endif
/** @addtogroup CMSIS_CM3_Core_FunctionInterface CMSIS CM3 Core Function Interface
Core Function Interface containing:
- Core NVIC Functions
- Core SysTick Functions
- Core Reset Functions
*/
/*@{*/
/* ########################## NVIC functions #################################### */
/**
* @brief Set the Priority Grouping in NVIC Interrupt Controller
*
* @param PriorityGroup is priority grouping field
*
* Set the priority grouping field using the required unlock sequence.
* The parameter priority_grouping is assigned to the field
* SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used.
* In case of a conflict between priority grouping and available
* priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.
*/
static __INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
{
uint32_t reg_value;
uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
reg_value = SCB->AIRCR; /* read old register configuration */
reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */
reg_value = (reg_value |
(0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(PriorityGroupTmp << 8)); /* Insert write key and priorty group */
SCB->AIRCR = reg_value;
}
/**
* @brief Get the Priority Grouping from NVIC Interrupt Controller
*
* @return priority grouping field
*
* Get the priority grouping from NVIC Interrupt Controller.
* priority grouping is SCB->AIRCR [10:8] PRIGROUP field.
*/
static __INLINE uint32_t NVIC_GetPriorityGrouping(void)
{
return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */
}
/**
* @brief Enable Interrupt in NVIC Interrupt Controller
*
* @param IRQn The positive number of the external interrupt to enable
*
* Enable a device specific interupt in the NVIC interrupt controller.
* The interrupt number cannot be a negative value.
*/
static __INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
}
/**
* @brief Disable the interrupt line for external interrupt specified
*
* @param IRQn The positive number of the external interrupt to disable
*
* Disable a device specific interupt in the NVIC interrupt controller.
* The interrupt number cannot be a negative value.
*/
static __INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
{
NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
}
/**
* @brief Read the interrupt pending bit for a device specific interrupt source
*
* @param IRQn The number of the device specifc interrupt
* @return 1 = interrupt pending, 0 = interrupt not pending
*
* Read the pending register in NVIC and return 1 if its status is pending,
* otherwise it returns 0
*/
static __INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */
}
/**
* @brief Set the pending bit for an external interrupt
*
* @param IRQn The number of the interrupt for set pending
*
* Set the pending bit for the specified interrupt.
* The interrupt number cannot be a negative value.
*/
static __INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */
}
/**
* @brief Clear the pending bit for an external interrupt
*
* @param IRQn The number of the interrupt for clear pending
*
* Clear the pending bit for the specified interrupt.
* The interrupt number cannot be a negative value.
*/
static __INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
}
/**
* @brief Read the active bit for an external interrupt
*
* @param IRQn The number of the interrupt for read active bit
* @return 1 = interrupt active, 0 = interrupt not active
*
* Read the active register in NVIC and returns 1 if its status is active,
* otherwise it returns 0.
*/
static __INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)
{
return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */
}
/**
* @brief Set the priority for an interrupt
*
* @param IRQn The number of the interrupt for set priority
* @param priority The priority to set
*
* Set the priority for the specified interrupt. The interrupt
* number can be positive to specify an external (device specific)
* interrupt, or negative to specify an internal (core) interrupt.
*
* Note: The priority cannot be set for every core interrupt.
*/
static __INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if(IRQn < 0) {
SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M3 System Interrupts */
else {
NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */
}
/**
* @brief Read the priority for an interrupt
*
* @param IRQn The number of the interrupt for get priority
* @return The priority for the interrupt
*
* Read the priority for the specified interrupt. The interrupt
* number can be positive to specify an external (device specific)
* interrupt, or negative to specify an internal (core) interrupt.
*
* The returned priority value is automatically aligned to the implemented
* priority bits of the microcontroller.
*
* Note: The priority cannot be set for every core interrupt.
*/
static __INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
{
if(IRQn < 0) {
return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M3 system interrupts */
else {
return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */
}
/**
* @brief Encode the priority for an interrupt
*
* @param PriorityGroup The used priority group
* @param PreemptPriority The preemptive priority value (starting from 0)
* @param SubPriority The sub priority value (starting from 0)
* @return The encoded priority for the interrupt
*
* Encode the priority for an interrupt with the given priority group,
* preemptive priority value and sub priority value.
* In case of a conflict between priority grouping and available
* priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
*
* The returned priority value can be used for NVIC_SetPriority(...) function
*/
static __INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
return (
((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) |
((SubPriority & ((1 << (SubPriorityBits )) - 1)))
);
}
/**
* @brief Decode the priority of an interrupt
*
* @param Priority The priority for the interrupt
* @param PriorityGroup The used priority group
* @param pPreemptPriority The preemptive priority value (starting from 0)
* @param pSubPriority The sub priority value (starting from 0)
*
* Decode an interrupt priority value with the given priority group to
* preemptive priority value and sub priority value.
* In case of a conflict between priority grouping and available
* priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
*
* The priority value can be retrieved with NVIC_GetPriority(...) function
*/
static __INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
*pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1);
*pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1);
}
/* ################################## SysTick function ############################################ */
#if (!defined (__Vendor_SysTickConfig)) || (__Vendor_SysTickConfig == 0)
/**
* @brief Initialize and start the SysTick counter and its interrupt.
*
* @param ticks number of ticks between two interrupts
* @return 1 = failed, 0 = successful
*
* Initialise the system tick timer and its interrupt and start the
* system tick timer / counter in free running mode to generate
* periodical interrupts.
*/
static __INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if (ticks > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */
SysTick->LOAD = (ticks & SysTick_LOAD_RELOAD_Msk) - 1; /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Cortex-M0 System Interrupts */
SysTick->VAL = 0; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0); /* Function successful */
}
#endif
/* ################################## Reset function ############################################ */
/**
* @brief Initiate a system reset request.
*
* Initiate a system reset request to reset the MCU
*/
static __INLINE void NVIC_SystemReset(void)
{
SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */
__DSB(); /* Ensure completion of memory access */
while(1); /* wait until reset */
}
/*@}*/ /* end of group CMSIS_CM3_Core_FunctionInterface */
/* ##################################### Debug In/Output function ########################################### */
/** @addtogroup CMSIS_CM3_CoreDebugInterface CMSIS CM3 Core Debug Interface
Core Debug Interface containing:
- Core Debug Receive / Transmit Functions
- Core Debug Defines
- Core Debug Variables
*/
/*@{*/
extern volatile int ITM_RxBuffer; /*!< variable to receive characters */
#define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< value identifying ITM_RxBuffer is ready for next character */
/**
* @brief Outputs a character via the ITM channel 0
*
* @param ch character to output
* @return character to output
*
* The function outputs a character via the ITM channel 0.
* The function returns when no debugger is connected that has booked the output.
* It is blocking when a debugger is connected, but the previous character send is not transmitted.
*/
static __INLINE uint32_t ITM_SendChar (uint32_t ch)
{
if ((CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && /* Trace enabled */
(ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */
(ITM->TER & (1ul << 0) ) ) /* ITM Port #0 enabled */
{
while (ITM->PORT[0].u32 == 0);
ITM->PORT[0].u8 = (uint8_t) ch;
}
return (ch);
}
/**
* @brief Inputs a character via variable ITM_RxBuffer
*
* @return received character, -1 = no character received
*
* The function inputs a character via variable ITM_RxBuffer.
* The function returns when no debugger is connected that has booked the output.
* It is blocking when a debugger is connected, but the previous character send is not transmitted.
*/
static __INLINE int ITM_ReceiveChar (void) {
int ch = -1; /* no character available */
if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) {
ch = ITM_RxBuffer;
ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */
}
return (ch);
}
/**
* @brief Check if a character via variable ITM_RxBuffer is available
*
* @return 1 = character available, 0 = no character available
*
* The function checks variable ITM_RxBuffer whether a character is available or not.
* The function returns '1' if a character is available and '0' if no character is available.
*/
static __INLINE int ITM_CheckChar (void) {
if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) {
return (0); /* no character available */
} else {
return (1); /* character available */
}
}
/*@}*/ /* end of group CMSIS_CM3_core_DebugInterface */
#ifdef __cplusplus
}
#endif
/*@}*/ /* end of group CMSIS_CM3_core_definitions */
#endif /* __CM3_CORE_H__ */
/*lint -restore */
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\CMSIS\system_stm32f10x.c | /**
******************************************************************************
* @file system_stm32f10x.c
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
*
* 1. This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
* factors, AHB/APBx prescalers and Flash settings).
* This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f10x_xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* 2. After each device reset the HSI (8 MHz) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32f10x_xx.s" file, to
* configure the system clock before to branch to main program.
*
* 3. If the system clock source selected by user fails to startup, the SystemInit()
* function will do nothing and HSI still used as system clock source. User can
* add some code to deal with this issue inside the SetSysClock() function.
*
* 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depedning on
* the product used), refer to "HSE_VALUE" define in "stm32f10x.h" file.
* When HSE is used as system clock source, directly or through PLL, and you
* are using different crystal you have to adapt the HSE value to your own
* configuration.
*
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f10x_system
* @{
*/
/** @addtogroup STM32F10x_System_Private_Includes
* @{
*/
#include "stm32f10x.h"
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Defines
* @{
*/
/*!< Uncomment the line corresponding to the desired System clock (SYSCLK)
frequency (after reset the HSI is used as SYSCLK source)
IMPORTANT NOTE:
==============
1. After each device reset the HSI is used as System clock source.
2. Please make sure that the selected System clock doesn't exceed your device's
maximum frequency.
3. If none of the define below is enabled, the HSI is used as System clock
source.
4. The System clock configuration functions provided within this file assume that:
- For Low, Medium and High density Value line devices an external 8MHz
crystal is used to drive the System clock.
- For Low, Medium and High density devices an external 8MHz crystal is
used to drive the System clock.
- For Connectivity line devices an external 25MHz crystal is used to drive
the System clock.
If you are using different crystal you have to adapt those functions accordingly.
*/
#if defined (STM32F10X_LD_VL) || (defined STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
/* #define SYSCLK_FREQ_HSE HSE_VALUE */
#define SYSCLK_FREQ_24MHz 24000000
#else
/* #define SYSCLK_FREQ_HSE HSE_VALUE */
/* #define SYSCLK_FREQ_24MHz 24000000 */
/* #define SYSCLK_FREQ_36MHz 36000000 */
/* #define SYSCLK_FREQ_48MHz 48000000 */
/* #define SYSCLK_FREQ_56MHz 56000000 */
#define SYSCLK_FREQ_72MHz 72000000
#endif
/*!< Uncomment the following line if you need to use external SRAM mounted
on STM3210E-EVAL board (STM32 High density and XL-density devices) or on
STM32100E-EVAL board (STM32 High-density value line devices) as data memory */
#if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL)
/* #define DATA_IN_ExtSRAM */
#endif
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Variables
* @{
*/
/*******************************************************************************
* Clock Definitions
*******************************************************************************/
#ifdef SYSCLK_FREQ_HSE
uint32_t SystemCoreClock = SYSCLK_FREQ_HSE; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_24MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_24MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_36MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_36MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_48MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_48MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_56MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_56MHz; /*!< System Clock Frequency (Core Clock) */
#elif defined SYSCLK_FREQ_72MHz
uint32_t SystemCoreClock = SYSCLK_FREQ_72MHz; /*!< System Clock Frequency (Core Clock) */
#else /*!< HSI Selected as System Clock source */
uint32_t SystemCoreClock = HSI_VALUE; /*!< System Clock Frequency (Core Clock) */
#endif
__I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_FunctionPrototypes
* @{
*/
static void SetSysClock(void);
#ifdef SYSCLK_FREQ_HSE
static void SetSysClockToHSE(void);
#elif defined SYSCLK_FREQ_24MHz
static void SetSysClockTo24(void);
#elif defined SYSCLK_FREQ_36MHz
static void SetSysClockTo36(void);
#elif defined SYSCLK_FREQ_48MHz
static void SetSysClockTo48(void);
#elif defined SYSCLK_FREQ_56MHz
static void SetSysClockTo56(void);
#elif defined SYSCLK_FREQ_72MHz
static void SetSysClockTo72(void);
#endif
#ifdef DATA_IN_ExtSRAM
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */
/**
* @}
*/
/** @addtogroup STM32F10x_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the Embedded Flash Interface, the PLL and update the
* SystemCoreClock variable.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
void SystemInit (void)
{
/* Reset the RCC clock configuration to the default reset state(for debug purpose) */
/* Set HSION bit */
RCC->CR |= (uint32_t)0x00000001;
/* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
#ifndef STM32F10X_CL
RCC->CFGR &= (uint32_t)0xF8FF0000;
#else
RCC->CFGR &= (uint32_t)0xF0FF0000;
#endif /* STM32F10X_CL */
/* Reset HSEON, CSSON and PLLON bits */
RCC->CR &= (uint32_t)0xFEF6FFFF;
/* Reset HSEBYP bit */
RCC->CR &= (uint32_t)0xFFFBFFFF;
/* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
RCC->CFGR &= (uint32_t)0xFF80FFFF;
#ifdef STM32F10X_CL
/* Reset PLL2ON and PLL3ON bits */
RCC->CR &= (uint32_t)0xEBFFFFFF;
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x00FF0000;
/* Reset CFGR2 register */
RCC->CFGR2 = 0x00000000;
#elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x009F0000;
/* Reset CFGR2 register */
RCC->CFGR2 = 0x00000000;
#else
/* Disable all interrupts and clear pending bits */
RCC->CIR = 0x009F0000;
#endif /* STM32F10X_CL */
#if defined (STM32F10X_HD) || (defined STM32F10X_XL) || (defined STM32F10X_HD_VL)
#ifdef DATA_IN_ExtSRAM
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
#endif
/* Configure the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers */
/* Configure the Flash Latency cycles and enable prefetch buffer */
SetSysClock();
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
#endif
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz or 25 MHz, depedning on the product used), user has to ensure
* that HSE_VALUE is same as the real frequency of the crystal used.
* Otherwise, this function may have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
* @param None
* @retval None
*/
void SystemCoreClockUpdate (void)
{
uint32_t tmp = 0, pllmull = 0, pllsource = 0;
#ifdef STM32F10X_CL
uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0;
#endif /* STM32F10X_CL */
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
uint32_t prediv1factor = 0;
#endif /* STM32F10X_LD_VL or STM32F10X_MD_VL or STM32F10X_HD_VL */
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00: /* HSI used as system clock */
SystemCoreClock = HSI_VALUE;
break;
case 0x04: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case 0x08: /* PLL used as system clock */
/* Get PLL clock source and multiplication factor ----------------------*/
pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
#ifndef STM32F10X_CL
pllmull = ( pllmull >> 18) + 2;
if (pllsource == 0x00)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1) * pllmull;
}
else
{
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1;
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
#else
/* HSE selected as PLL clock entry */
if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET)
{/* HSE oscillator clock divided by 2 */
SystemCoreClock = (HSE_VALUE >> 1) * pllmull;
}
else
{
SystemCoreClock = HSE_VALUE * pllmull;
}
#endif
}
#else
pllmull = pllmull >> 18;
if (pllmull != 0x0D)
{
pllmull += 2;
}
else
{ /* PLL multiplication factor = PLL input clock * 6.5 */
pllmull = 13 / 2;
}
if (pllsource == 0x00)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1) * pllmull;
}
else
{/* PREDIV1 selected as PLL clock entry */
/* Get PREDIV1 clock source and division factor */
prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1;
if (prediv1source == 0)
{
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
}
else
{/* PLL2 clock selected as PREDIV1 clock entry */
/* Get PREDIV2 division factor and PLL2 multiplication factor */
prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1;
pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2;
SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
}
}
#endif /* STM32F10X_CL */
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK clock frequency ----------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
/**
* @brief Configures the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers.
* @param None
* @retval None
*/
static void SetSysClock(void)
{
#ifdef SYSCLK_FREQ_HSE
SetSysClockToHSE();
#elif defined SYSCLK_FREQ_24MHz
SetSysClockTo24();
#elif defined SYSCLK_FREQ_36MHz
SetSysClockTo36();
#elif defined SYSCLK_FREQ_48MHz
SetSysClockTo48();
#elif defined SYSCLK_FREQ_56MHz
SetSysClockTo56();
#elif defined SYSCLK_FREQ_72MHz
SetSysClockTo72();
#endif
/* If none of the define above is enabled, the HSI is used as System clock
source (default after reset) */
}
/**
* @brief Setup the external memory controller. Called in startup_stm32f10x.s
* before jump to __main
* @param None
* @retval None
*/
#ifdef DATA_IN_ExtSRAM
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f10x_xx.s/.c before jump to main.
* This function configures the external SRAM mounted on STM3210E-EVAL
* board (STM32 High density devices). This SRAM will be used as program
* data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
/*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
required, then adjust the Register Addresses */
/* Enable FSMC clock */
RCC->AHBENR = 0x00000114;
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
RCC->APB2ENR = 0x000001E0;
/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
/*---------------- SRAM Address lines configuration -------------------------*/
/*---------------- NOE and NWE configuration --------------------------------*/
/*---------------- NE3 configuration ----------------------------------------*/
/*---------------- NBL0, NBL1 configuration ---------------------------------*/
GPIOD->CRL = 0x44BB44BB;
GPIOD->CRH = 0xBBBBBBBB;
GPIOE->CRL = 0xB44444BB;
GPIOE->CRH = 0xBBBBBBBB;
GPIOF->CRL = 0x44BBBBBB;
GPIOF->CRH = 0xBBBB4444;
GPIOG->CRL = 0x44BBBBBB;
GPIOG->CRH = 0x44444B44;
/*---------------- FSMC Configuration ---------------------------------------*/
/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
FSMC_Bank1->BTCR[4] = 0x00001011;
FSMC_Bank1->BTCR[5] = 0x00000200;
}
#endif /* DATA_IN_ExtSRAM */
#ifdef SYSCLK_FREQ_HSE
/**
* @brief Selects HSE as System clock source and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockToHSE(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
#if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 0 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
#ifndef STM32F10X_CL
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
#else
if (HSE_VALUE <= 24000000)
{
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
}
else
{
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
}
#endif /* STM32F10X_CL */
#endif
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
/* Select HSE as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_HSE;
/* Wait till HSE is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x04)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_24MHz
/**
* @brief Sets System clock frequency to 24MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo24(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
#if !defined STM32F10X_LD_VL && !defined STM32F10X_MD_VL && !defined STM32F10X_HD_VL
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 0 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_0;
#endif
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL configuration: PLLCLK = PREDIV1 * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL6);
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
#elif defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)
/* PLL configuration: = (HSE / 2) * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLXTPRE_PREDIV1_Div2 | RCC_CFGR_PLLMULL6);
#else
/* PLL configuration: = (HSE / 2) * 6 = 24 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL6);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_36MHz
/**
* @brief Sets System clock frequency to 36MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo36(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 1 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL configuration: PLLCLK = PREDIV1 * 9 = 36 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL9);
/*!< PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 10 = 4 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV10);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
#else
/* PLL configuration: PLLCLK = (HSE / 2) * 9 = 36 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLXTPRE_HSE_Div2 | RCC_CFGR_PLLMULL9);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_48MHz
/**
* @brief Sets System clock frequency to 48MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo48(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 1 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_1;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 6 = 48 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL6);
#else
/* PLL configuration: PLLCLK = HSE * 6 = 48 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL6);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_56MHz
/**
* @brief Sets System clock frequency to 56MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo56(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 2 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 7 = 56 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL7);
#else
/* PLL configuration: PLLCLK = HSE * 7 = 56 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL7);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#elif defined SYSCLK_FREQ_72MHz
/**
* @brief Sets System clock frequency to 72MHz and configure HCLK, PCLK2
* and PCLK1 prescalers.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
static void SetSysClockTo72(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTBE;
/* Flash 2 wait state */
FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;
/* HCLK = SYSCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK */
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
#ifdef STM32F10X_CL
/* Configure PLLs ------------------------------------------------------*/
/* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */
/* PREDIV1 configuration: PREDIV1CLK = PLL2 / 5 = 8 MHz */
RCC->CFGR2 &= (uint32_t)~(RCC_CFGR2_PREDIV2 | RCC_CFGR2_PLL2MUL |
RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC);
RCC->CFGR2 |= (uint32_t)(RCC_CFGR2_PREDIV2_DIV5 | RCC_CFGR2_PLL2MUL8 |
RCC_CFGR2_PREDIV1SRC_PLL2 | RCC_CFGR2_PREDIV1_DIV5);
/* Enable PLL2 */
RCC->CR |= RCC_CR_PLL2ON;
/* Wait till PLL2 is ready */
while((RCC->CR & RCC_CR_PLL2RDY) == 0)
{
}
/* PLL configuration: PLLCLK = PREDIV1 * 9 = 72 MHz */
RCC->CFGR &= (uint32_t)~(RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL);
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLSRC_PREDIV1 |
RCC_CFGR_PLLMULL9);
#else
/* PLL configuration: PLLCLK = HSE * 9 = 72 MHz */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE |
RCC_CFGR_PLLMULL));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL9);
#endif /* STM32F10X_CL */
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
{
}
}
else
{ /* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\CMSIS\system_stm32f10x.h | /**
******************************************************************************
* @file system_stm32f10x.h
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Header File.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f10x_system
* @{
*/
/**
* @brief Define to prevent recursive inclusion
*/
#ifndef __SYSTEM_STM32F10X_H
#define __SYSTEM_STM32F10X_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup STM32F10x_System_Includes
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Exported_types
* @{
*/
extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
/**
* @}
*/
/** @addtogroup STM32F10x_System_Exported_Constants
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Exported_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F10x_System_Exported_Functions
* @{
*/
extern void SystemInit(void);
extern void SystemCoreClockUpdate(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /*__SYSTEM_STM32F10X_H */
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\inc\misc.h | /**
******************************************************************************
* @file misc.h
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief This file contains all the functions prototypes for the miscellaneous
* firmware library functions (add-on to CMSIS functions).
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MISC_H
#define __MISC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup STM32F10x_StdPeriph_Driver
* @{
*/
/** @addtogroup MISC
* @{
*/
/** @defgroup MISC_Exported_Types
* @{
*/
/**
* @brief NVIC Init Structure definition
*/
typedef struct
{
uint8_t NVIC_IRQChannel; /*!< Specifies the IRQ channel to be enabled or disabled.
This parameter can be a value of @ref IRQn_Type
(For the complete STM32 Devices IRQ Channels list, please
refer to stm32f10x.h file) */
uint8_t NVIC_IRQChannelPreemptionPriority; /*!< Specifies the pre-emption priority for the IRQ channel
specified in NVIC_IRQChannel. This parameter can be a value
between 0 and 15 as described in the table @ref NVIC_Priority_Table */
uint8_t NVIC_IRQChannelSubPriority; /*!< Specifies the subpriority level for the IRQ channel specified
in NVIC_IRQChannel. This parameter can be a value
between 0 and 15 as described in the table @ref NVIC_Priority_Table */
FunctionalState NVIC_IRQChannelCmd; /*!< Specifies whether the IRQ channel defined in NVIC_IRQChannel
will be enabled or disabled.
This parameter can be set either to ENABLE or DISABLE */
} NVIC_InitTypeDef;
/**
* @}
*/
/** @defgroup NVIC_Priority_Table
* @{
*/
/**
@code
The table below gives the allowed values of the pre-emption priority and subpriority according
to the Priority Grouping configuration performed by NVIC_PriorityGroupConfig function
============================================================================================================================
NVIC_PriorityGroup | NVIC_IRQChannelPreemptionPriority | NVIC_IRQChannelSubPriority | Description
============================================================================================================================
NVIC_PriorityGroup_0 | 0 | 0-15 | 0 bits for pre-emption priority
| | | 4 bits for subpriority
----------------------------------------------------------------------------------------------------------------------------
NVIC_PriorityGroup_1 | 0-1 | 0-7 | 1 bits for pre-emption priority
| | | 3 bits for subpriority
----------------------------------------------------------------------------------------------------------------------------
NVIC_PriorityGroup_2 | 0-3 | 0-3 | 2 bits for pre-emption priority
| | | 2 bits for subpriority
----------------------------------------------------------------------------------------------------------------------------
NVIC_PriorityGroup_3 | 0-7 | 0-1 | 3 bits for pre-emption priority
| | | 1 bits for subpriority
----------------------------------------------------------------------------------------------------------------------------
NVIC_PriorityGroup_4 | 0-15 | 0 | 4 bits for pre-emption priority
| | | 0 bits for subpriority
============================================================================================================================
@endcode
*/
/**
* @}
*/
/** @defgroup MISC_Exported_Constants
* @{
*/
/** @defgroup Vector_Table_Base
* @{
*/
#define NVIC_VectTab_RAM ((uint32_t)0x20000000)
#define NVIC_VectTab_FLASH ((uint32_t)0x08000000)
#define IS_NVIC_VECTTAB(VECTTAB) (((VECTTAB) == NVIC_VectTab_RAM) || \
((VECTTAB) == NVIC_VectTab_FLASH))
/**
* @}
*/
/** @defgroup System_Low_Power
* @{
*/
#define NVIC_LP_SEVONPEND ((uint8_t)0x10)
#define NVIC_LP_SLEEPDEEP ((uint8_t)0x04)
#define NVIC_LP_SLEEPONEXIT ((uint8_t)0x02)
#define IS_NVIC_LP(LP) (((LP) == NVIC_LP_SEVONPEND) || \
((LP) == NVIC_LP_SLEEPDEEP) || \
((LP) == NVIC_LP_SLEEPONEXIT))
/**
* @}
*/
/** @defgroup Preemption_Priority_Group
* @{
*/
#define NVIC_PriorityGroup_0 ((uint32_t)0x700) /*!< 0 bits for pre-emption priority
4 bits for subpriority */
#define NVIC_PriorityGroup_1 ((uint32_t)0x600) /*!< 1 bits for pre-emption priority
3 bits for subpriority */
#define NVIC_PriorityGroup_2 ((uint32_t)0x500) /*!< 2 bits for pre-emption priority
2 bits for subpriority */
#define NVIC_PriorityGroup_3 ((uint32_t)0x400) /*!< 3 bits for pre-emption priority
1 bits for subpriority */
#define NVIC_PriorityGroup_4 ((uint32_t)0x300) /*!< 4 bits for pre-emption priority
0 bits for subpriority */
#define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PriorityGroup_0) || \
((GROUP) == NVIC_PriorityGroup_1) || \
((GROUP) == NVIC_PriorityGroup_2) || \
((GROUP) == NVIC_PriorityGroup_3) || \
((GROUP) == NVIC_PriorityGroup_4))
#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10)
#define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10)
#define IS_NVIC_OFFSET(OFFSET) ((OFFSET) < 0x000FFFFF)
/**
* @}
*/
/** @defgroup SysTick_clock_source
* @{
*/
#define SysTick_CLKSource_HCLK_Div8 ((uint32_t)0xFFFFFFFB)
#define SysTick_CLKSource_HCLK ((uint32_t)0x00000004)
#define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SysTick_CLKSource_HCLK) || \
((SOURCE) == SysTick_CLKSource_HCLK_Div8))
/**
* @}
*/
/**
* @}
*/
/** @defgroup MISC_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup MISC_Exported_Functions
* @{
*/
void NVIC_PriorityGroupConfig(uint32_t NVIC_PriorityGroup);
void NVIC_Init(NVIC_InitTypeDef* NVIC_InitStruct);
void NVIC_SetVectorTable(uint32_t NVIC_VectTab, uint32_t Offset);
void NVIC_SystemLPConfig(uint8_t LowPowerMode, FunctionalState NewState);
void SysTick_CLKSourceConfig(uint32_t SysTick_CLKSource);
#ifdef __cplusplus
}
#endif
#endif /* __MISC_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| 0 |
D://workCode//uploadProject\stm32_oled\Libraries | D://workCode//uploadProject\stm32_oled\Libraries\inc\stm32f10x_adc.h | /**
******************************************************************************
* @file stm32f10x_adc.h
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief This file contains all the functions prototypes for the ADC firmware
* library.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F10x_ADC_H
#define __STM32F10x_ADC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup STM32F10x_StdPeriph_Driver
* @{
*/
/** @addtogroup ADC
* @{
*/
/** @defgroup ADC_Exported_Types
* @{
*/
/**
* @brief ADC Init structure definition
*/
typedef struct
{
uint32_t ADC_Mode; /*!< Configures the ADC to operate in independent or
dual mode.
This parameter can be a value of @ref ADC_mode */
FunctionalState ADC_ScanConvMode; /*!< Specifies whether the conversion is performed in
Scan (multichannels) or Single (one channel) mode.
This parameter can be set to ENABLE or DISABLE */
FunctionalState ADC_ContinuousConvMode; /*!< Specifies whether the conversion is performed in
Continuous or Single mode.
This parameter can be set to ENABLE or DISABLE. */
uint32_t ADC_ExternalTrigConv; /*!< Defines the external trigger used to start the analog
to digital conversion of regular channels. This parameter
can be a value of @ref ADC_external_trigger_sources_for_regular_channels_conversion */
uint32_t ADC_DataAlign; /*!< Specifies whether the ADC data alignment is left or right.
This parameter can be a value of @ref ADC_data_align */
uint8_t ADC_NbrOfChannel; /*!< Specifies the number of ADC channels that will be converted
using the sequencer for regular channel group.
This parameter must range from 1 to 16. */
}ADC_InitTypeDef;
/**
* @}
*/
/** @defgroup ADC_Exported_Constants
* @{
*/
#define IS_ADC_ALL_PERIPH(PERIPH) (((PERIPH) == ADC1) || \
((PERIPH) == ADC2) || \
((PERIPH) == ADC3))
#define IS_ADC_DMA_PERIPH(PERIPH) (((PERIPH) == ADC1) || \
((PERIPH) == ADC3))
/** @defgroup ADC_mode
* @{
*/
#define ADC_Mode_Independent ((uint32_t)0x00000000)
#define ADC_Mode_RegInjecSimult ((uint32_t)0x00010000)
#define ADC_Mode_RegSimult_AlterTrig ((uint32_t)0x00020000)
#define ADC_Mode_InjecSimult_FastInterl ((uint32_t)0x00030000)
#define ADC_Mode_InjecSimult_SlowInterl ((uint32_t)0x00040000)
#define ADC_Mode_InjecSimult ((uint32_t)0x00050000)
#define ADC_Mode_RegSimult ((uint32_t)0x00060000)
#define ADC_Mode_FastInterl ((uint32_t)0x00070000)
#define ADC_Mode_SlowInterl ((uint32_t)0x00080000)
#define ADC_Mode_AlterTrig ((uint32_t)0x00090000)
#define IS_ADC_MODE(MODE) (((MODE) == ADC_Mode_Independent) || \
((MODE) == ADC_Mode_RegInjecSimult) || \
((MODE) == ADC_Mode_RegSimult_AlterTrig) || \
((MODE) == ADC_Mode_InjecSimult_FastInterl) || \
((MODE) == ADC_Mode_InjecSimult_SlowInterl) || \
((MODE) == ADC_Mode_InjecSimult) || \
((MODE) == ADC_Mode_RegSimult) || \
((MODE) == ADC_Mode_FastInterl) || \
((MODE) == ADC_Mode_SlowInterl) || \
((MODE) == ADC_Mode_AlterTrig))
/**
* @}
*/
/** @defgroup ADC_external_trigger_sources_for_regular_channels_conversion
* @{
*/
#define ADC_ExternalTrigConv_T1_CC1 ((uint32_t)0x00000000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T1_CC2 ((uint32_t)0x00020000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T2_CC2 ((uint32_t)0x00060000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T3_TRGO ((uint32_t)0x00080000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T4_CC4 ((uint32_t)0x000A0000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO ((uint32_t)0x000C0000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T1_CC3 ((uint32_t)0x00040000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigConv_None ((uint32_t)0x000E0000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigConv_T3_CC1 ((uint32_t)0x00000000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T2_CC3 ((uint32_t)0x00020000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T8_CC1 ((uint32_t)0x00060000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T8_TRGO ((uint32_t)0x00080000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T5_CC1 ((uint32_t)0x000A0000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T5_CC3 ((uint32_t)0x000C0000) /*!< For ADC3 only */
#define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_ExternalTrigConv_T1_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T1_CC2) || \
((REGTRIG) == ADC_ExternalTrigConv_T1_CC3) || \
((REGTRIG) == ADC_ExternalTrigConv_T2_CC2) || \
((REGTRIG) == ADC_ExternalTrigConv_T3_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_T4_CC4) || \
((REGTRIG) == ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_None) || \
((REGTRIG) == ADC_ExternalTrigConv_T3_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T2_CC3) || \
((REGTRIG) == ADC_ExternalTrigConv_T8_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T8_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_T5_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T5_CC3))
/**
* @}
*/
/** @defgroup ADC_data_align
* @{
*/
#define ADC_DataAlign_Right ((uint32_t)0x00000000)
#define ADC_DataAlign_Left ((uint32_t)0x00000800)
#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DataAlign_Right) || \
((ALIGN) == ADC_DataAlign_Left))
/**
* @}
*/
/** @defgroup ADC_channels
* @{
*/
#define ADC_Channel_0 ((uint8_t)0x00)
#define ADC_Channel_1 ((uint8_t)0x01)
#define ADC_Channel_2 ((uint8_t)0x02)
#define ADC_Channel_3 ((uint8_t)0x03)
#define ADC_Channel_4 ((uint8_t)0x04)
#define ADC_Channel_5 ((uint8_t)0x05)
#define ADC_Channel_6 ((uint8_t)0x06)
#define ADC_Channel_7 ((uint8_t)0x07)
#define ADC_Channel_8 ((uint8_t)0x08)
#define ADC_Channel_9 ((uint8_t)0x09)
#define ADC_Channel_10 ((uint8_t)0x0A)
#define ADC_Channel_11 ((uint8_t)0x0B)
#define ADC_Channel_12 ((uint8_t)0x0C)
#define ADC_Channel_13 ((uint8_t)0x0D)
#define ADC_Channel_14 ((uint8_t)0x0E)
#define ADC_Channel_15 ((uint8_t)0x0F)
#define ADC_Channel_16 ((uint8_t)0x10)
#define ADC_Channel_17 ((uint8_t)0x11)
#define ADC_Channel_TempSensor ((uint8_t)ADC_Channel_16)
#define ADC_Channel_Vrefint ((uint8_t)ADC_Channel_17)
#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_Channel_0) || ((CHANNEL) == ADC_Channel_1) || \
((CHANNEL) == ADC_Channel_2) || ((CHANNEL) == ADC_Channel_3) || \
((CHANNEL) == ADC_Channel_4) || ((CHANNEL) == ADC_Channel_5) || \
((CHANNEL) == ADC_Channel_6) || ((CHANNEL) == ADC_Channel_7) || \
((CHANNEL) == ADC_Channel_8) || ((CHANNEL) == ADC_Channel_9) || \
((CHANNEL) == ADC_Channel_10) || ((CHANNEL) == ADC_Channel_11) || \
((CHANNEL) == ADC_Channel_12) || ((CHANNEL) == ADC_Channel_13) || \
((CHANNEL) == ADC_Channel_14) || ((CHANNEL) == ADC_Channel_15) || \
((CHANNEL) == ADC_Channel_16) || ((CHANNEL) == ADC_Channel_17))
/**
* @}
*/
/** @defgroup ADC_sampling_time
* @{
*/
#define ADC_SampleTime_1Cycles5 ((uint8_t)0x00)
#define ADC_SampleTime_7Cycles5 ((uint8_t)0x01)
#define ADC_SampleTime_13Cycles5 ((uint8_t)0x02)
#define ADC_SampleTime_28Cycles5 ((uint8_t)0x03)
#define ADC_SampleTime_41Cycles5 ((uint8_t)0x04)
#define ADC_SampleTime_55Cycles5 ((uint8_t)0x05)
#define ADC_SampleTime_71Cycles5 ((uint8_t)0x06)
#define ADC_SampleTime_239Cycles5 ((uint8_t)0x07)
#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SampleTime_1Cycles5) || \
((TIME) == ADC_SampleTime_7Cycles5) || \
((TIME) == ADC_SampleTime_13Cycles5) || \
((TIME) == ADC_SampleTime_28Cycles5) || \
((TIME) == ADC_SampleTime_41Cycles5) || \
((TIME) == ADC_SampleTime_55Cycles5) || \
((TIME) == ADC_SampleTime_71Cycles5) || \
((TIME) == ADC_SampleTime_239Cycles5))
/**
* @}
*/
/** @defgroup ADC_external_trigger_sources_for_injected_channels_conversion
* @{
*/
#define ADC_ExternalTrigInjecConv_T2_TRGO ((uint32_t)0x00002000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T2_CC1 ((uint32_t)0x00003000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T3_CC4 ((uint32_t)0x00004000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T4_TRGO ((uint32_t)0x00005000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4 ((uint32_t)0x00006000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T1_TRGO ((uint32_t)0x00000000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_T1_CC4 ((uint32_t)0x00001000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_None ((uint32_t)0x00007000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_T4_CC3 ((uint32_t)0x00002000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T8_CC2 ((uint32_t)0x00003000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T8_CC4 ((uint32_t)0x00004000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T5_TRGO ((uint32_t)0x00005000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T5_CC4 ((uint32_t)0x00006000) /*!< For ADC3 only */
#define IS_ADC_EXT_INJEC_TRIG(INJTRIG) (((INJTRIG) == ADC_ExternalTrigInjecConv_T1_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T1_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T2_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T2_CC1) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T3_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T4_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_None) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T4_CC3) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T8_CC2) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T8_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T5_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T5_CC4))
/**
* @}
*/
/** @defgroup ADC_injected_channel_selection
* @{
*/
#define ADC_InjectedChannel_1 ((uint8_t)0x14)
#define ADC_InjectedChannel_2 ((uint8_t)0x18)
#define ADC_InjectedChannel_3 ((uint8_t)0x1C)
#define ADC_InjectedChannel_4 ((uint8_t)0x20)
#define IS_ADC_INJECTED_CHANNEL(CHANNEL) (((CHANNEL) == ADC_InjectedChannel_1) || \
((CHANNEL) == ADC_InjectedChannel_2) || \
((CHANNEL) == ADC_InjectedChannel_3) || \
((CHANNEL) == ADC_InjectedChannel_4))
/**
* @}
*/
/** @defgroup ADC_analog_watchdog_selection
* @{
*/
#define ADC_AnalogWatchdog_SingleRegEnable ((uint32_t)0x00800200)
#define ADC_AnalogWatchdog_SingleInjecEnable ((uint32_t)0x00400200)
#define ADC_AnalogWatchdog_SingleRegOrInjecEnable ((uint32_t)0x00C00200)
#define ADC_AnalogWatchdog_AllRegEnable ((uint32_t)0x00800000)
#define ADC_AnalogWatchdog_AllInjecEnable ((uint32_t)0x00400000)
#define ADC_AnalogWatchdog_AllRegAllInjecEnable ((uint32_t)0x00C00000)
#define ADC_AnalogWatchdog_None ((uint32_t)0x00000000)
#define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_AnalogWatchdog_SingleRegEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_SingleInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_SingleRegOrInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllRegEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllRegAllInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_None))
/**
* @}
*/
/** @defgroup ADC_interrupts_definition
* @{
*/
#define ADC_IT_EOC ((uint16_t)0x0220)
#define ADC_IT_AWD ((uint16_t)0x0140)
#define ADC_IT_JEOC ((uint16_t)0x0480)
#define IS_ADC_IT(IT) ((((IT) & (uint16_t)0xF81F) == 0x00) && ((IT) != 0x00))
#define IS_ADC_GET_IT(IT) (((IT) == ADC_IT_EOC) || ((IT) == ADC_IT_AWD) || \
((IT) == ADC_IT_JEOC))
/**
* @}
*/
/** @defgroup ADC_flags_definition
* @{
*/
#define ADC_FLAG_AWD ((uint8_t)0x01)
#define ADC_FLAG_EOC ((uint8_t)0x02)
#define ADC_FLAG_JEOC ((uint8_t)0x04)
#define ADC_FLAG_JSTRT ((uint8_t)0x08)
#define ADC_FLAG_STRT ((uint8_t)0x10)
#define IS_ADC_CLEAR_FLAG(FLAG) ((((FLAG) & (uint8_t)0xE0) == 0x00) && ((FLAG) != 0x00))
#define IS_ADC_GET_FLAG(FLAG) (((FLAG) == ADC_FLAG_AWD) || ((FLAG) == ADC_FLAG_EOC) || \
((FLAG) == ADC_FLAG_JEOC) || ((FLAG)== ADC_FLAG_JSTRT) || \
((FLAG) == ADC_FLAG_STRT))
/**
* @}
*/
/** @defgroup ADC_thresholds
* @{
*/
#define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= 0xFFF)
/**
* @}
*/
/** @defgroup ADC_injected_offset
* @{
*/
#define IS_ADC_OFFSET(OFFSET) ((OFFSET) <= 0xFFF)
/**
* @}
*/
/** @defgroup ADC_injected_length
* @{
*/
#define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x4))
/**
* @}
*/
/** @defgroup ADC_injected_rank
* @{
*/
#define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x4))
/**
* @}
*/
/** @defgroup ADC_regular_length
* @{
*/
#define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x10))
/**
* @}
*/
/** @defgroup ADC_regular_rank
* @{
*/
#define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x10))
/**
* @}
*/
/** @defgroup ADC_regular_discontinuous_mode_number
* @{
*/
#define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= 0x1) && ((NUMBER) <= 0x8))
/**
* @}
*/
/**
* @}
*/
/** @defgroup ADC_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup ADC_Exported_Functions
* @{
*/
void ADC_DeInit(ADC_TypeDef* ADCx);
void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct);
void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct);
void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_ITConfig(ADC_TypeDef* ADCx, uint16_t ADC_IT, FunctionalState NewState);
void ADC_ResetCalibration(ADC_TypeDef* ADCx);
FlagStatus ADC_GetResetCalibrationStatus(ADC_TypeDef* ADCx);
void ADC_StartCalibration(ADC_TypeDef* ADCx);
FlagStatus ADC_GetCalibrationStatus(ADC_TypeDef* ADCx);
void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
FlagStatus ADC_GetSoftwareStartConvStatus(ADC_TypeDef* ADCx);
void ADC_DiscModeChannelCountConfig(ADC_TypeDef* ADCx, uint8_t Number);
void ADC_DiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
void ADC_ExternalTrigConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx);
uint32_t ADC_GetDualModeConversionValue(void);
void ADC_AutoInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_InjectedDiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv);
void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
FlagStatus ADC_GetSoftwareStartInjectedConvCmdStatus(ADC_TypeDef* ADCx);
void ADC_InjectedChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
void ADC_InjectedSequencerLengthConfig(ADC_TypeDef* ADCx, uint8_t Length);
void ADC_SetInjectedOffset(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel, uint16_t Offset);
uint16_t ADC_GetInjectedConversionValue(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel);
void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog);
void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold, uint16_t LowThreshold);
void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel);
void ADC_TempSensorVrefintCmd(FunctionalState NewState);
FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
void ADC_ClearFlag(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint16_t ADC_IT);
void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint16_t ADC_IT);
#ifdef __cplusplus
}
#endif
#endif /*__STM32F10x_ADC_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| 0 |