diff --git a/boards/DJI_Board_TypeC/Core/Inc/FreeRTOSConfig.h b/boards/DJI_Board_TypeC/Core/Inc/FreeRTOSConfig.h index 5f4a049c..2d21e3d7 100644 --- a/boards/DJI_Board_TypeC/Core/Inc/FreeRTOSConfig.h +++ b/boards/DJI_Board_TypeC/Core/Inc/FreeRTOSConfig.h @@ -97,7 +97,7 @@ #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY ( 2 ) #define configTIMER_QUEUE_LENGTH 10 -#define configTIMER_TASK_STACK_DEPTH 256 +#define configTIMER_TASK_STACK_DEPTH 1024 /* CMSIS-RTOS V2 flags */ #define configUSE_OS2_THREAD_SUSPEND_RESUME 1 diff --git a/boards/DJI_Board_TypeC/Core/Src/main.c b/boards/DJI_Board_TypeC/Core/Src/main.c index 090e3e80..9c2e5af3 100644 --- a/boards/DJI_Board_TypeC/Core/Src/main.c +++ b/boards/DJI_Board_TypeC/Core/Src/main.c @@ -112,7 +112,9 @@ int main(void) /* USER CODE END 2 */ /* Init scheduler */ - osKernelInitialize(); /* Call init function for freertos objects (in freertos.c) */ + osKernelInitialize(); + + /* Call init function for freertos objects (in freertos.c) */ MX_FREERTOS_Init(); /* Start scheduler */ diff --git a/boards/DJI_Board_TypeC/DJI_Board_TypeC.ioc b/boards/DJI_Board_TypeC/DJI_Board_TypeC.ioc index 138c58d3..1eefdfec 100644 --- a/boards/DJI_Board_TypeC/DJI_Board_TypeC.ioc +++ b/boards/DJI_Board_TypeC/DJI_Board_TypeC.ioc @@ -99,11 +99,12 @@ Dma.USART6_TX.4.PeriphInc=DMA_PINC_DISABLE Dma.USART6_TX.4.Priority=DMA_PRIORITY_MEDIUM Dma.USART6_TX.4.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode FREERTOS.FootprintOK=true -FREERTOS.IPParameters=Tasks01,configENABLE_FPU,configTOTAL_HEAP_SIZE,configCHECK_FOR_STACK_OVERFLOW,configGENERATE_RUN_TIME_STATS,FootprintOK +FREERTOS.IPParameters=Tasks01,configENABLE_FPU,configTOTAL_HEAP_SIZE,configCHECK_FOR_STACK_OVERFLOW,configGENERATE_RUN_TIME_STATS,FootprintOK,configTIMER_TASK_STACK_DEPTH FREERTOS.Tasks01=defaultTask,24,1024,StartDefaultTask,Default,NULL,Dynamic,NULL,NULL FREERTOS.configCHECK_FOR_STACK_OVERFLOW=2 FREERTOS.configENABLE_FPU=1 FREERTOS.configGENERATE_RUN_TIME_STATS=1 +FREERTOS.configTIMER_TASK_STACK_DEPTH=1024 FREERTOS.configTOTAL_HEAP_SIZE=65536 File.Version=6 GPIO.groupedBy=Group By Peripherals @@ -195,8 +196,8 @@ Mcu.PinsNb=54 Mcu.ThirdPartyNb=0 Mcu.UserConstants= Mcu.UserName=STM32F407IGHx -MxCube.Version=6.9.0 -MxDb.Version=DB.6.0.90 +MxCube.Version=6.10.0 +MxDb.Version=DB.6.0.100 NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false NVIC.CAN1_RX0_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true NVIC.CAN1_TX_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true @@ -460,7 +461,7 @@ ProjectManager.FreePins=false ProjectManager.HalAssertFull=false ProjectManager.HeapSize=0x2000 ProjectManager.KeepUserCode=true -ProjectManager.LastFirmware=false +ProjectManager.LastFirmware=true ProjectManager.LibraryCopy=1 ProjectManager.MainLocation=Core/Src ProjectManager.NoMain=false diff --git a/boards/DJI_Board_TypeC/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_spi.h b/boards/DJI_Board_TypeC/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_spi.h new file mode 100644 index 00000000..4f3b0306 --- /dev/null +++ b/boards/DJI_Board_TypeC/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_ll_spi.h @@ -0,0 +1,2027 @@ +/** + ****************************************************************************** + * @file stm32f4xx_ll_spi.h + * @author MCD Application Team + * @brief Header file of SPI LL module. + ****************************************************************************** + * @attention + * + * Copyright (c) 2016 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32F4xx_LL_SPI_H +#define STM32F4xx_LL_SPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx.h" + +/** @addtogroup STM32F4xx_LL_Driver + * @{ + */ + +#if defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) + +/** @defgroup SPI_LL SPI + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_LL_DRIVER) +/** @defgroup SPI_LL_ES_INIT SPI Exported Init structure + * @{ + */ + +/** + * @brief SPI Init structures definition + */ +typedef struct +{ + uint32_t TransferDirection; /*!< Specifies the SPI unidirectional or bidirectional data mode. + This parameter can be a value of @ref SPI_LL_EC_TRANSFER_MODE. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferDirection().*/ + + uint32_t Mode; /*!< Specifies the SPI mode (Master/Slave). + This parameter can be a value of @ref SPI_LL_EC_MODE. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetMode().*/ + + uint32_t DataWidth; /*!< Specifies the SPI data width. + This parameter can be a value of @ref SPI_LL_EC_DATAWIDTH. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetDataWidth().*/ + + uint32_t ClockPolarity; /*!< Specifies the serial clock steady state. + This parameter can be a value of @ref SPI_LL_EC_POLARITY. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPolarity().*/ + + uint32_t ClockPhase; /*!< Specifies the clock active edge for the bit capture. + This parameter can be a value of @ref SPI_LL_EC_PHASE. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPhase().*/ + + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. + This parameter can be a value of @ref SPI_LL_EC_NSS_MODE. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetNSSMode().*/ + + uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used to configure the transmit and receive SCK clock. + This parameter can be a value of @ref SPI_LL_EC_BAUDRATEPRESCALER. + @note The communication clock is derived from the master clock. The slave clock does not need to be set. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetBaudRatePrescaler().*/ + + uint32_t BitOrder; /*!< Specifies whether data transfers start from MSB or LSB bit. + This parameter can be a value of @ref SPI_LL_EC_BIT_ORDER. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferBitOrder().*/ + + uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. + This parameter can be a value of @ref SPI_LL_EC_CRC_CALCULATION. + + This feature can be modified afterwards using unitary functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ + + uint32_t CRCPoly; /*!< Specifies the polynomial used for the CRC calculation. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF. + + This feature can be modified afterwards using unitary function @ref LL_SPI_SetCRCPolynomial().*/ + +} LL_SPI_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SPI_LL_Exported_Constants SPI Exported Constants + * @{ + */ + +/** @defgroup SPI_LL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with LL_SPI_ReadReg function + * @{ + */ +#define LL_SPI_SR_RXNE SPI_SR_RXNE /*!< Rx buffer not empty flag */ +#define LL_SPI_SR_TXE SPI_SR_TXE /*!< Tx buffer empty flag */ +#define LL_SPI_SR_BSY SPI_SR_BSY /*!< Busy flag */ +#define LL_SPI_SR_CRCERR SPI_SR_CRCERR /*!< CRC error flag */ +#define LL_SPI_SR_MODF SPI_SR_MODF /*!< Mode fault flag */ +#define LL_SPI_SR_OVR SPI_SR_OVR /*!< Overrun flag */ +#define LL_SPI_SR_FRE SPI_SR_FRE /*!< TI mode frame format error flag */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_IT IT Defines + * @brief IT defines which can be used with LL_SPI_ReadReg and LL_SPI_WriteReg functions + * @{ + */ +#define LL_SPI_CR2_RXNEIE SPI_CR2_RXNEIE /*!< Rx buffer not empty interrupt enable */ +#define LL_SPI_CR2_TXEIE SPI_CR2_TXEIE /*!< Tx buffer empty interrupt enable */ +#define LL_SPI_CR2_ERRIE SPI_CR2_ERRIE /*!< Error interrupt enable */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_MODE Operation Mode + * @{ + */ +#define LL_SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) /*!< Master configuration */ +#define LL_SPI_MODE_SLAVE 0x00000000U /*!< Slave configuration */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_PROTOCOL Serial Protocol + * @{ + */ +#define LL_SPI_PROTOCOL_MOTOROLA 0x00000000U /*!< Motorola mode. Used as default value */ +#define LL_SPI_PROTOCOL_TI (SPI_CR2_FRF) /*!< TI mode */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_PHASE Clock Phase + * @{ + */ +#define LL_SPI_PHASE_1EDGE 0x00000000U /*!< First clock transition is the first data capture edge */ +#define LL_SPI_PHASE_2EDGE (SPI_CR1_CPHA) /*!< Second clock transition is the first data capture edge */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_POLARITY Clock Polarity + * @{ + */ +#define LL_SPI_POLARITY_LOW 0x00000000U /*!< Clock to 0 when idle */ +#define LL_SPI_POLARITY_HIGH (SPI_CR1_CPOL) /*!< Clock to 1 when idle */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_BAUDRATEPRESCALER Baud Rate Prescaler + * @{ + */ +#define LL_SPI_BAUDRATEPRESCALER_DIV2 0x00000000U /*!< BaudRate control equal to fPCLK/2 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV4 (SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/4 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV8 (SPI_CR1_BR_1) /*!< BaudRate control equal to fPCLK/8 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV16 (SPI_CR1_BR_1 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/16 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV32 (SPI_CR1_BR_2) /*!< BaudRate control equal to fPCLK/32 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV64 (SPI_CR1_BR_2 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/64 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV128 (SPI_CR1_BR_2 | SPI_CR1_BR_1) /*!< BaudRate control equal to fPCLK/128 */ +#define LL_SPI_BAUDRATEPRESCALER_DIV256 (SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/256 */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_BIT_ORDER Transmission Bit Order + * @{ + */ +#define LL_SPI_LSB_FIRST (SPI_CR1_LSBFIRST) /*!< Data is transmitted/received with the LSB first */ +#define LL_SPI_MSB_FIRST 0x00000000U /*!< Data is transmitted/received with the MSB first */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_TRANSFER_MODE Transfer Mode + * @{ + */ +#define LL_SPI_FULL_DUPLEX 0x00000000U /*!< Full-Duplex mode. Rx and Tx transfer on 2 lines */ +#define LL_SPI_SIMPLEX_RX (SPI_CR1_RXONLY) /*!< Simplex Rx mode. Rx transfer only on 1 line */ +#define LL_SPI_HALF_DUPLEX_RX (SPI_CR1_BIDIMODE) /*!< Half-Duplex Rx mode. Rx transfer on 1 line */ +#define LL_SPI_HALF_DUPLEX_TX (SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE) /*!< Half-Duplex Tx mode. Tx transfer on 1 line */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_NSS_MODE Slave Select Pin Mode + * @{ + */ +#define LL_SPI_NSS_SOFT (SPI_CR1_SSM) /*!< NSS managed internally. NSS pin not used and free */ +#define LL_SPI_NSS_HARD_INPUT 0x00000000U /*!< NSS pin used in Input. Only used in Master mode */ +#define LL_SPI_NSS_HARD_OUTPUT (((uint32_t)SPI_CR2_SSOE << 16U)) /*!< NSS pin used in Output. Only used in Slave mode as chip select */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_DATAWIDTH Datawidth + * @{ + */ +#define LL_SPI_DATAWIDTH_8BIT 0x00000000U /*!< Data length for SPI transfer: 8 bits */ +#define LL_SPI_DATAWIDTH_16BIT (SPI_CR1_DFF) /*!< Data length for SPI transfer: 16 bits */ +/** + * @} + */ +#if defined(USE_FULL_LL_DRIVER) + +/** @defgroup SPI_LL_EC_CRC_CALCULATION CRC Calculation + * @{ + */ +#define LL_SPI_CRCCALCULATION_DISABLE 0x00000000U /*!< CRC calculation disabled */ +#define LL_SPI_CRCCALCULATION_ENABLE (SPI_CR1_CRCEN) /*!< CRC calculation enabled */ +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SPI_LL_Exported_Macros SPI Exported Macros + * @{ + */ + +/** @defgroup SPI_LL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in SPI register + * @param __INSTANCE__ SPI Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define LL_SPI_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in SPI register + * @param __INSTANCE__ SPI Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define LL_SPI_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SPI_LL_Exported_Functions SPI Exported Functions + * @{ + */ + +/** @defgroup SPI_LL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Enable SPI peripheral + * @rmtoll CR1 SPE LL_SPI_Enable + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_Enable(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR1, SPI_CR1_SPE); +} + +/** + * @brief Disable SPI peripheral + * @note When disabling the SPI, follow the procedure described in the Reference Manual. + * @rmtoll CR1 SPE LL_SPI_Disable + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR1, SPI_CR1_SPE); +} + +/** + * @brief Check if SPI peripheral is enabled + * @rmtoll CR1 SPE LL_SPI_IsEnabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)) ? 1UL : 0UL); +} + +/** + * @brief Set SPI operation mode to Master or Slave + * @note This bit should not be changed when communication is ongoing. + * @rmtoll CR1 MSTR LL_SPI_SetMode\n + * CR1 SSI LL_SPI_SetMode + * @param SPIx SPI Instance + * @param Mode This parameter can be one of the following values: + * @arg @ref LL_SPI_MODE_MASTER + * @arg @ref LL_SPI_MODE_SLAVE + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI, Mode); +} + +/** + * @brief Get SPI operation mode (Master or Slave) + * @rmtoll CR1 MSTR LL_SPI_GetMode\n + * CR1 SSI LL_SPI_GetMode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_MODE_MASTER + * @arg @ref LL_SPI_MODE_SLAVE + */ +__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); +} + +/** + * @brief Set serial protocol used + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @rmtoll CR2 FRF LL_SPI_SetStandard + * @param SPIx SPI Instance + * @param Standard This parameter can be one of the following values: + * @arg @ref LL_SPI_PROTOCOL_MOTOROLA + * @arg @ref LL_SPI_PROTOCOL_TI + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) +{ + MODIFY_REG(SPIx->CR2, SPI_CR2_FRF, Standard); +} + +/** + * @brief Get serial protocol used + * @rmtoll CR2 FRF LL_SPI_GetStandard + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_PROTOCOL_MOTOROLA + * @arg @ref LL_SPI_PROTOCOL_TI + */ +__STATIC_INLINE uint32_t LL_SPI_GetStandard(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_FRF)); +} + +/** + * @brief Set clock phase + * @note This bit should not be changed when communication is ongoing. + * This bit is not used in SPI TI mode. + * @rmtoll CR1 CPHA LL_SPI_SetClockPhase + * @param SPIx SPI Instance + * @param ClockPhase This parameter can be one of the following values: + * @arg @ref LL_SPI_PHASE_1EDGE + * @arg @ref LL_SPI_PHASE_2EDGE + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_CPHA, ClockPhase); +} + +/** + * @brief Get clock phase + * @rmtoll CR1 CPHA LL_SPI_GetClockPhase + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_PHASE_1EDGE + * @arg @ref LL_SPI_PHASE_2EDGE + */ +__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); +} + +/** + * @brief Set clock polarity + * @note This bit should not be changed when communication is ongoing. + * This bit is not used in SPI TI mode. + * @rmtoll CR1 CPOL LL_SPI_SetClockPolarity + * @param SPIx SPI Instance + * @param ClockPolarity This parameter can be one of the following values: + * @arg @ref LL_SPI_POLARITY_LOW + * @arg @ref LL_SPI_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_CPOL, ClockPolarity); +} + +/** + * @brief Get clock polarity + * @rmtoll CR1 CPOL LL_SPI_GetClockPolarity + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_POLARITY_LOW + * @arg @ref LL_SPI_POLARITY_HIGH + */ +__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); +} + +/** + * @brief Set baud rate prescaler + * @note These bits should not be changed when communication is ongoing. SPI BaudRate = fPCLK/Prescaler. + * @rmtoll CR1 BR LL_SPI_SetBaudRatePrescaler + * @param SPIx SPI Instance + * @param BaudRate This parameter can be one of the following values: + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV2 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV4 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV8 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV16 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV32 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV64 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t BaudRate) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_BR, BaudRate); +} + +/** + * @brief Get baud rate prescaler + * @rmtoll CR1 BR LL_SPI_GetBaudRatePrescaler + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV2 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV4 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV8 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV16 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV32 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV64 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 + * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 + */ +__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); +} + +/** + * @brief Set transfer bit order + * @note This bit should not be changed when communication is ongoing. This bit is not used in SPI TI mode. + * @rmtoll CR1 LSBFIRST LL_SPI_SetTransferBitOrder + * @param SPIx SPI Instance + * @param BitOrder This parameter can be one of the following values: + * @arg @ref LL_SPI_LSB_FIRST + * @arg @ref LL_SPI_MSB_FIRST + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitOrder) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_LSBFIRST, BitOrder); +} + +/** + * @brief Get transfer bit order + * @rmtoll CR1 LSBFIRST LL_SPI_GetTransferBitOrder + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_LSB_FIRST + * @arg @ref LL_SPI_MSB_FIRST + */ +__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); +} + +/** + * @brief Set transfer direction mode + * @note For Half-Duplex mode, Rx Direction is set by default. + * In master mode, the MOSI pin is used and in slave mode, the MISO pin is used for Half-Duplex. + * @rmtoll CR1 RXONLY LL_SPI_SetTransferDirection\n + * CR1 BIDIMODE LL_SPI_SetTransferDirection\n + * CR1 BIDIOE LL_SPI_SetTransferDirection + * @param SPIx SPI Instance + * @param TransferDirection This parameter can be one of the following values: + * @arg @ref LL_SPI_FULL_DUPLEX + * @arg @ref LL_SPI_SIMPLEX_RX + * @arg @ref LL_SPI_HALF_DUPLEX_RX + * @arg @ref LL_SPI_HALF_DUPLEX_TX + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t TransferDirection) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE, TransferDirection); +} + +/** + * @brief Get transfer direction mode + * @rmtoll CR1 RXONLY LL_SPI_GetTransferDirection\n + * CR1 BIDIMODE LL_SPI_GetTransferDirection\n + * CR1 BIDIOE LL_SPI_GetTransferDirection + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_FULL_DUPLEX + * @arg @ref LL_SPI_SIMPLEX_RX + * @arg @ref LL_SPI_HALF_DUPLEX_RX + * @arg @ref LL_SPI_HALF_DUPLEX_TX + */ +__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); +} + +/** + * @brief Set frame data width + * @rmtoll CR1 DFF LL_SPI_SetDataWidth + * @param SPIx SPI Instance + * @param DataWidth This parameter can be one of the following values: + * @arg @ref LL_SPI_DATAWIDTH_8BIT + * @arg @ref LL_SPI_DATAWIDTH_16BIT + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_DFF, DataWidth); +} + +/** + * @brief Get frame data width + * @rmtoll CR1 DFF LL_SPI_GetDataWidth + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_DATAWIDTH_8BIT + * @arg @ref LL_SPI_DATAWIDTH_16BIT + */ +__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_DFF)); +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_CRC_Management CRC Management + * @{ + */ + +/** + * @brief Enable CRC + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @rmtoll CR1 CRCEN LL_SPI_EnableCRC + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableCRC(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR1, SPI_CR1_CRCEN); +} + +/** + * @brief Disable CRC + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @rmtoll CR1 CRCEN LL_SPI_DisableCRC + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR1, SPI_CR1_CRCEN); +} + +/** + * @brief Check if CRC is enabled + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @rmtoll CR1 CRCEN LL_SPI_IsEnabledCRC + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)) ? 1UL : 0UL); +} + +/** + * @brief Set CRCNext to transfer CRC on the line + * @note This bit has to be written as soon as the last data is written in the SPIx_DR register. + * @rmtoll CR1 CRCNEXT LL_SPI_SetCRCNext + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetCRCNext(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR1, SPI_CR1_CRCNEXT); +} + +/** + * @brief Set polynomial for CRC calculation + * @rmtoll CRCPR CRCPOLY LL_SPI_SetCRCPolynomial + * @param SPIx SPI Instance + * @param CRCPoly This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly) +{ + WRITE_REG(SPIx->CRCPR, (uint16_t)CRCPoly); +} + +/** + * @brief Get polynomial for CRC calculation + * @rmtoll CRCPR CRCPOLY LL_SPI_GetCRCPolynomial + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->CRCPR)); +} + +/** + * @brief Get Rx CRC + * @rmtoll RXCRCR RXCRC LL_SPI_GetRxCRC + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->RXCRCR)); +} + +/** + * @brief Get Tx CRC + * @rmtoll TXCRCR TXCRC LL_SPI_GetTxCRC + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->TXCRCR)); +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_NSS_Management Slave Select Pin Management + * @{ + */ + +/** + * @brief Set NSS mode + * @note LL_SPI_NSS_SOFT Mode is not used in SPI TI mode. + * @rmtoll CR1 SSM LL_SPI_SetNSSMode\n + * @rmtoll CR2 SSOE LL_SPI_SetNSSMode + * @param SPIx SPI Instance + * @param NSS This parameter can be one of the following values: + * @arg @ref LL_SPI_NSS_SOFT + * @arg @ref LL_SPI_NSS_HARD_INPUT + * @arg @ref LL_SPI_NSS_HARD_OUTPUT + * @retval None + */ +__STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) +{ + MODIFY_REG(SPIx->CR1, SPI_CR1_SSM, NSS); + MODIFY_REG(SPIx->CR2, SPI_CR2_SSOE, ((uint32_t)(NSS >> 16U))); +} + +/** + * @brief Get NSS mode + * @rmtoll CR1 SSM LL_SPI_GetNSSMode\n + * @rmtoll CR2 SSOE LL_SPI_GetNSSMode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_SPI_NSS_SOFT + * @arg @ref LL_SPI_NSS_HARD_INPUT + * @arg @ref LL_SPI_NSS_HARD_OUTPUT + */ +__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +{ + uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); + uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); + return (Ssm | Ssoe); +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_FLAG_Management FLAG Management + * @{ + */ + +/** + * @brief Check if Rx buffer is not empty + * @rmtoll SR RXNE LL_SPI_IsActiveFlag_RXNE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)) ? 1UL : 0UL); +} + +/** + * @brief Check if Tx buffer is empty + * @rmtoll SR TXE LL_SPI_IsActiveFlag_TXE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)) ? 1UL : 0UL); +} + +/** + * @brief Get CRC error flag + * @rmtoll SR CRCERR LL_SPI_IsActiveFlag_CRCERR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)) ? 1UL : 0UL); +} + +/** + * @brief Get mode fault error flag + * @rmtoll SR MODF LL_SPI_IsActiveFlag_MODF + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)) ? 1UL : 0UL); +} + +/** + * @brief Get overrun error flag + * @rmtoll SR OVR LL_SPI_IsActiveFlag_OVR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)) ? 1UL : 0UL); +} + +/** + * @brief Get busy flag + * @note The BSY flag is cleared under any one of the following conditions: + * -When the SPI is correctly disabled + * -When a fault is detected in Master mode (MODF bit set to 1) + * -In Master mode, when it finishes a data transmission and no new data is ready to be + * sent + * -In Slave mode, when the BSY flag is set to '0' for at least one SPI clock cycle between + * each data transfer. + * @rmtoll SR BSY LL_SPI_IsActiveFlag_BSY + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)) ? 1UL : 0UL); +} + +/** + * @brief Get frame format error flag + * @rmtoll SR FRE LL_SPI_IsActiveFlag_FRE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_FRE) == (SPI_SR_FRE)) ? 1UL : 0UL); +} + +/** + * @brief Clear CRC error flag + * @rmtoll SR CRCERR LL_SPI_ClearFlag_CRCERR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_ClearFlag_CRCERR(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->SR, SPI_SR_CRCERR); +} + +/** + * @brief Clear mode fault error flag + * @note Clearing this flag is done by a read access to the SPIx_SR + * register followed by a write access to the SPIx_CR1 register + * @rmtoll SR MODF LL_SPI_ClearFlag_MODF + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_ClearFlag_MODF(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg_sr; + tmpreg_sr = SPIx->SR; + (void) tmpreg_sr; + CLEAR_BIT(SPIx->CR1, SPI_CR1_SPE); +} + +/** + * @brief Clear overrun error flag + * @note Clearing this flag is done by a read access to the SPIx_DR + * register followed by a read access to the SPIx_SR register + * @rmtoll SR OVR LL_SPI_ClearFlag_OVR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_ClearFlag_OVR(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->DR; + (void) tmpreg; + tmpreg = SPIx->SR; + (void) tmpreg; +} + +/** + * @brief Clear frame format error flag + * @note Clearing this flag is done by reading SPIx_SR register + * @rmtoll SR FRE LL_SPI_ClearFlag_FRE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_ClearFlag_FRE(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->SR; + (void) tmpreg; +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_IT_Management Interrupt Management + * @{ + */ + +/** + * @brief Enable error interrupt + * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @rmtoll CR2 ERRIE LL_SPI_EnableIT_ERR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableIT_ERR(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR2, SPI_CR2_ERRIE); +} + +/** + * @brief Enable Rx buffer not empty interrupt + * @rmtoll CR2 RXNEIE LL_SPI_EnableIT_RXNE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableIT_RXNE(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR2, SPI_CR2_RXNEIE); +} + +/** + * @brief Enable Tx buffer empty interrupt + * @rmtoll CR2 TXEIE LL_SPI_EnableIT_TXE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableIT_TXE(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR2, SPI_CR2_TXEIE); +} + +/** + * @brief Disable error interrupt + * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @rmtoll CR2 ERRIE LL_SPI_DisableIT_ERR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableIT_ERR(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR2, SPI_CR2_ERRIE); +} + +/** + * @brief Disable Rx buffer not empty interrupt + * @rmtoll CR2 RXNEIE LL_SPI_DisableIT_RXNE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableIT_RXNE(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR2, SPI_CR2_RXNEIE); +} + +/** + * @brief Disable Tx buffer empty interrupt + * @rmtoll CR2 TXEIE LL_SPI_DisableIT_TXE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR2, SPI_CR2_TXEIE); +} + +/** + * @brief Check if error interrupt is enabled + * @rmtoll CR2 ERRIE LL_SPI_IsEnabledIT_ERR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)) ? 1UL : 0UL); +} + +/** + * @brief Check if Rx buffer not empty interrupt is enabled + * @rmtoll CR2 RXNEIE LL_SPI_IsEnabledIT_RXNE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)) ? 1UL : 0UL); +} + +/** + * @brief Check if Tx buffer empty interrupt + * @rmtoll CR2 TXEIE LL_SPI_IsEnabledIT_TXE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_DMA_Management DMA Management + * @{ + */ + +/** + * @brief Enable DMA Rx + * @rmtoll CR2 RXDMAEN LL_SPI_EnableDMAReq_RX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableDMAReq_RX(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR2, SPI_CR2_RXDMAEN); +} + +/** + * @brief Disable DMA Rx + * @rmtoll CR2 RXDMAEN LL_SPI_DisableDMAReq_RX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR2, SPI_CR2_RXDMAEN); +} + +/** + * @brief Check if DMA Rx is enabled + * @rmtoll CR2 RXDMAEN LL_SPI_IsEnabledDMAReq_RX + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable DMA Tx + * @rmtoll CR2 TXDMAEN LL_SPI_EnableDMAReq_TX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_EnableDMAReq_TX(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CR2, SPI_CR2_TXDMAEN); +} + +/** + * @brief Disable DMA Tx + * @rmtoll CR2 TXDMAEN LL_SPI_DisableDMAReq_TX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CR2, SPI_CR2_TXDMAEN); +} + +/** + * @brief Check if DMA Tx is enabled + * @rmtoll CR2 TXDMAEN LL_SPI_IsEnabledDMAReq_TX + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)) ? 1UL : 0UL); +} + +/** + * @brief Get the data register address used for DMA transfer + * @rmtoll DR DR LL_SPI_DMA_GetRegAddr + * @param SPIx SPI Instance + * @retval Address of data register + */ +__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +{ + return (uint32_t) &(SPIx->DR); +} + +/** + * @} + */ + +/** @defgroup SPI_LL_EF_DATA_Management DATA Management + * @{ + */ + +/** + * @brief Read 8-Bits in the data register + * @rmtoll DR DR LL_SPI_ReceiveData8 + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t LL_SPI_ReceiveData8(SPI_TypeDef *SPIx) +{ + return (*((__IO uint8_t *)&SPIx->DR)); +} + +/** + * @brief Read 16-Bits in the data register + * @rmtoll DR DR LL_SPI_ReceiveData16 + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint16_t LL_SPI_ReceiveData16(SPI_TypeDef *SPIx) +{ + return (uint16_t)(READ_REG(SPIx->DR)); +} + +/** + * @brief Write 8-Bits in the data register + * @rmtoll DR DR LL_SPI_TransmitData8 + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void LL_SPI_TransmitData8(SPI_TypeDef *SPIx, uint8_t TxData) +{ +#if defined (__GNUC__) + __IO uint8_t *spidr = ((__IO uint8_t *)&SPIx->DR); + *spidr = TxData; +#else + *((__IO uint8_t *)&SPIx->DR) = TxData; +#endif /* __GNUC__ */ +} + +/** + * @brief Write 16-Bits in the data register + * @rmtoll DR DR LL_SPI_TransmitData16 + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x00 and Max_Data=0xFFFF + * @retval None + */ +__STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) +{ +#if defined (__GNUC__) + __IO uint16_t *spidr = ((__IO uint16_t *)&SPIx->DR); + *spidr = TxData; +#else + SPIx->DR = TxData; +#endif /* __GNUC__ */ +} + +/** + * @} + */ +#if defined(USE_FULL_LL_DRIVER) +/** @defgroup SPI_LL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); +void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup I2S_LL I2S + * @{ + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_LL_DRIVER) +/** @defgroup I2S_LL_ES_INIT I2S Exported Init structure + * @{ + */ + +/** + * @brief I2S Init structure definition + */ + +typedef struct +{ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_LL_EC_MODE + + This feature can be modified afterwards using unitary function @ref LL_I2S_SetTransferMode().*/ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_LL_EC_STANDARD + + This feature can be modified afterwards using unitary function @ref LL_I2S_SetStandard().*/ + + + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_LL_EC_DATA_FORMAT + + This feature can be modified afterwards using unitary function @ref LL_I2S_SetDataFormat().*/ + + + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_LL_EC_MCLK_OUTPUT + + This feature can be modified afterwards using unitary functions @ref LL_I2S_EnableMasterClock() or @ref LL_I2S_DisableMasterClock.*/ + + + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_LL_EC_AUDIO_FREQ + + Audio Frequency can be modified afterwards using Reference manual formulas to calculate Prescaler Linear, Parity + and unitary functions @ref LL_I2S_SetPrescalerLinear() and @ref LL_I2S_SetPrescalerParity() to set it.*/ + + + uint32_t ClockPolarity; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_LL_EC_POLARITY + + This feature can be modified afterwards using unitary function @ref LL_I2S_SetClockPolarity().*/ + +} LL_I2S_InitTypeDef; + +/** + * @} + */ +#endif /*USE_FULL_LL_DRIVER*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup I2S_LL_Exported_Constants I2S Exported Constants + * @{ + */ + +/** @defgroup I2S_LL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with LL_I2S_ReadReg function + * @{ + */ +#define LL_I2S_SR_RXNE LL_SPI_SR_RXNE /*!< Rx buffer not empty flag */ +#define LL_I2S_SR_TXE LL_SPI_SR_TXE /*!< Tx buffer empty flag */ +#define LL_I2S_SR_BSY LL_SPI_SR_BSY /*!< Busy flag */ +#define LL_I2S_SR_UDR SPI_SR_UDR /*!< Underrun flag */ +#define LL_I2S_SR_OVR LL_SPI_SR_OVR /*!< Overrun flag */ +#define LL_I2S_SR_FRE LL_SPI_SR_FRE /*!< TI mode frame format error flag */ +/** + * @} + */ + +/** @defgroup SPI_LL_EC_IT IT Defines + * @brief IT defines which can be used with LL_SPI_ReadReg and LL_SPI_WriteReg functions + * @{ + */ +#define LL_I2S_CR2_RXNEIE LL_SPI_CR2_RXNEIE /*!< Rx buffer not empty interrupt enable */ +#define LL_I2S_CR2_TXEIE LL_SPI_CR2_TXEIE /*!< Tx buffer empty interrupt enable */ +#define LL_I2S_CR2_ERRIE LL_SPI_CR2_ERRIE /*!< Error interrupt enable */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_DATA_FORMAT Data format + * @{ + */ +#define LL_I2S_DATAFORMAT_16B 0x00000000U /*!< Data length 16 bits, Channel length 16bit */ +#define LL_I2S_DATAFORMAT_16B_EXTENDED (SPI_I2SCFGR_CHLEN) /*!< Data length 16 bits, Channel length 32bit */ +#define LL_I2S_DATAFORMAT_24B (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_0) /*!< Data length 24 bits, Channel length 32bit */ +#define LL_I2S_DATAFORMAT_32B (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_1) /*!< Data length 16 bits, Channel length 32bit */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_POLARITY Clock Polarity + * @{ + */ +#define LL_I2S_POLARITY_LOW 0x00000000U /*!< Clock steady state is low level */ +#define LL_I2S_POLARITY_HIGH (SPI_I2SCFGR_CKPOL) /*!< Clock steady state is high level */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_STANDARD I2s Standard + * @{ + */ +#define LL_I2S_STANDARD_PHILIPS 0x00000000U /*!< I2S standard philips */ +#define LL_I2S_STANDARD_MSB (SPI_I2SCFGR_I2SSTD_0) /*!< MSB justified standard (left justified) */ +#define LL_I2S_STANDARD_LSB (SPI_I2SCFGR_I2SSTD_1) /*!< LSB justified standard (right justified) */ +#define LL_I2S_STANDARD_PCM_SHORT (SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1) /*!< PCM standard, short frame synchronization */ +#define LL_I2S_STANDARD_PCM_LONG (SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1 | SPI_I2SCFGR_PCMSYNC) /*!< PCM standard, long frame synchronization */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_MODE Operation Mode + * @{ + */ +#define LL_I2S_MODE_SLAVE_TX 0x00000000U /*!< Slave Tx configuration */ +#define LL_I2S_MODE_SLAVE_RX (SPI_I2SCFGR_I2SCFG_0) /*!< Slave Rx configuration */ +#define LL_I2S_MODE_MASTER_TX (SPI_I2SCFGR_I2SCFG_1) /*!< Master Tx configuration */ +#define LL_I2S_MODE_MASTER_RX (SPI_I2SCFGR_I2SCFG_0 | SPI_I2SCFGR_I2SCFG_1) /*!< Master Rx configuration */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_PRESCALER_FACTOR Prescaler Factor + * @{ + */ +#define LL_I2S_PRESCALER_PARITY_EVEN 0x00000000U /*!< Odd factor: Real divider value is = I2SDIV * 2 */ +#define LL_I2S_PRESCALER_PARITY_ODD (SPI_I2SPR_ODD >> 8U) /*!< Odd factor: Real divider value is = (I2SDIV * 2)+1 */ +/** + * @} + */ + +#if defined(USE_FULL_LL_DRIVER) + +/** @defgroup I2S_LL_EC_MCLK_OUTPUT MCLK Output + * @{ + */ +#define LL_I2S_MCLK_OUTPUT_DISABLE 0x00000000U /*!< Master clock output is disabled */ +#define LL_I2S_MCLK_OUTPUT_ENABLE (SPI_I2SPR_MCKOE) /*!< Master clock output is enabled */ +/** + * @} + */ + +/** @defgroup I2S_LL_EC_AUDIO_FREQ Audio Frequency + * @{ + */ + +#define LL_I2S_AUDIOFREQ_192K 192000U /*!< Audio Frequency configuration 192000 Hz */ +#define LL_I2S_AUDIOFREQ_96K 96000U /*!< Audio Frequency configuration 96000 Hz */ +#define LL_I2S_AUDIOFREQ_48K 48000U /*!< Audio Frequency configuration 48000 Hz */ +#define LL_I2S_AUDIOFREQ_44K 44100U /*!< Audio Frequency configuration 44100 Hz */ +#define LL_I2S_AUDIOFREQ_32K 32000U /*!< Audio Frequency configuration 32000 Hz */ +#define LL_I2S_AUDIOFREQ_22K 22050U /*!< Audio Frequency configuration 22050 Hz */ +#define LL_I2S_AUDIOFREQ_16K 16000U /*!< Audio Frequency configuration 16000 Hz */ +#define LL_I2S_AUDIOFREQ_11K 11025U /*!< Audio Frequency configuration 11025 Hz */ +#define LL_I2S_AUDIOFREQ_8K 8000U /*!< Audio Frequency configuration 8000 Hz */ +#define LL_I2S_AUDIOFREQ_DEFAULT 2U /*!< Audio Freq not specified. Register I2SDIV = 2 */ +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup I2S_LL_Exported_Macros I2S Exported Macros + * @{ + */ + +/** @defgroup I2S_LL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in I2S register + * @param __INSTANCE__ I2S Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define LL_I2S_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in I2S register + * @param __INSTANCE__ I2S Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define LL_I2S_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup I2S_LL_Exported_Functions I2S Exported Functions + * @{ + */ + +/** @defgroup I2S_LL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Select I2S mode and Enable I2S peripheral + * @rmtoll I2SCFGR I2SMOD LL_I2S_Enable\n + * I2SCFGR I2SE LL_I2S_Enable + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_Enable(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SE); +} + +/** + * @brief Disable I2S peripheral + * @rmtoll I2SCFGR I2SE LL_I2S_Disable + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SE); +} + +/** + * @brief Check if I2S peripheral is enabled + * @rmtoll I2SCFGR I2SE LL_I2S_IsEnabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)) ? 1UL : 0UL); +} + +/** + * @brief Set I2S data frame length + * @rmtoll I2SCFGR DATLEN LL_I2S_SetDataFormat\n + * I2SCFGR CHLEN LL_I2S_SetDataFormat + * @param SPIx SPI Instance + * @param DataFormat This parameter can be one of the following values: + * @arg @ref LL_I2S_DATAFORMAT_16B + * @arg @ref LL_I2S_DATAFORMAT_16B_EXTENDED + * @arg @ref LL_I2S_DATAFORMAT_24B + * @arg @ref LL_I2S_DATAFORMAT_32B + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat) +{ + MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN, DataFormat); +} + +/** + * @brief Get I2S data frame length + * @rmtoll I2SCFGR DATLEN LL_I2S_GetDataFormat\n + * I2SCFGR CHLEN LL_I2S_GetDataFormat + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_I2S_DATAFORMAT_16B + * @arg @ref LL_I2S_DATAFORMAT_16B_EXTENDED + * @arg @ref LL_I2S_DATAFORMAT_24B + * @arg @ref LL_I2S_DATAFORMAT_32B + */ +__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); +} + +/** + * @brief Set I2S clock polarity + * @rmtoll I2SCFGR CKPOL LL_I2S_SetClockPolarity + * @param SPIx SPI Instance + * @param ClockPolarity This parameter can be one of the following values: + * @arg @ref LL_I2S_POLARITY_LOW + * @arg @ref LL_I2S_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) +{ + SET_BIT(SPIx->I2SCFGR, ClockPolarity); +} + +/** + * @brief Get I2S clock polarity + * @rmtoll I2SCFGR CKPOL LL_I2S_GetClockPolarity + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_I2S_POLARITY_LOW + * @arg @ref LL_I2S_POLARITY_HIGH + */ +__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); +} + +/** + * @brief Set I2S standard protocol + * @rmtoll I2SCFGR I2SSTD LL_I2S_SetStandard\n + * I2SCFGR PCMSYNC LL_I2S_SetStandard + * @param SPIx SPI Instance + * @param Standard This parameter can be one of the following values: + * @arg @ref LL_I2S_STANDARD_PHILIPS + * @arg @ref LL_I2S_STANDARD_MSB + * @arg @ref LL_I2S_STANDARD_LSB + * @arg @ref LL_I2S_STANDARD_PCM_SHORT + * @arg @ref LL_I2S_STANDARD_PCM_LONG + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) +{ + MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC, Standard); +} + +/** + * @brief Get I2S standard protocol + * @rmtoll I2SCFGR I2SSTD LL_I2S_GetStandard\n + * I2SCFGR PCMSYNC LL_I2S_GetStandard + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_I2S_STANDARD_PHILIPS + * @arg @ref LL_I2S_STANDARD_MSB + * @arg @ref LL_I2S_STANDARD_LSB + * @arg @ref LL_I2S_STANDARD_PCM_SHORT + * @arg @ref LL_I2S_STANDARD_PCM_LONG + */ +__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); +} + +/** + * @brief Set I2S transfer mode + * @rmtoll I2SCFGR I2SCFG LL_I2S_SetTransferMode + * @param SPIx SPI Instance + * @param Mode This parameter can be one of the following values: + * @arg @ref LL_I2S_MODE_SLAVE_TX + * @arg @ref LL_I2S_MODE_SLAVE_RX + * @arg @ref LL_I2S_MODE_MASTER_TX + * @arg @ref LL_I2S_MODE_MASTER_RX + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) +{ + MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG, Mode); +} + +/** + * @brief Get I2S transfer mode + * @rmtoll I2SCFGR I2SCFG LL_I2S_GetTransferMode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_I2S_MODE_SLAVE_TX + * @arg @ref LL_I2S_MODE_SLAVE_RX + * @arg @ref LL_I2S_MODE_MASTER_TX + * @arg @ref LL_I2S_MODE_MASTER_RX + */ +__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); +} + +/** + * @brief Set I2S linear prescaler + * @rmtoll I2SPR I2SDIV LL_I2S_SetPrescalerLinear + * @param SPIx SPI Instance + * @param PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t PrescalerLinear) +{ + MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV, PrescalerLinear); +} + +/** + * @brief Get I2S linear prescaler + * @rmtoll I2SPR I2SDIV LL_I2S_GetPrescalerLinear + * @param SPIx SPI Instance + * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF + */ +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); +} + +/** + * @brief Set I2S parity prescaler + * @rmtoll I2SPR ODD LL_I2S_SetPrescalerParity + * @param SPIx SPI Instance + * @param PrescalerParity This parameter can be one of the following values: + * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref LL_I2S_PRESCALER_PARITY_ODD + * @retval None + */ +__STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t PrescalerParity) +{ + MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_ODD, PrescalerParity << 8U); +} + +/** + * @brief Get I2S parity prescaler + * @rmtoll I2SPR ODD LL_I2S_GetPrescalerParity + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref LL_I2S_PRESCALER_PARITY_ODD + */ +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); +} + +/** + * @brief Enable the master clock output (Pin MCK) + * @rmtoll I2SPR MCKOE LL_I2S_EnableMasterClock + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableMasterClock(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE); +} + +/** + * @brief Disable the master clock output (Pin MCK) + * @rmtoll I2SPR MCKOE LL_I2S_DisableMasterClock + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE); +} + +/** + * @brief Check if the master clock output (Pin MCK) is enabled + * @rmtoll I2SPR MCKOE LL_I2S_IsEnabledMasterClock + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)) ? 1UL : 0UL); +} + +#if defined(SPI_I2SCFGR_ASTRTEN) +/** + * @brief Enable asynchronous start + * @rmtoll I2SCFGR ASTRTEN LL_I2S_EnableAsyncStart + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableAsyncStart(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_ASTRTEN); +} + +/** + * @brief Disable asynchronous start + * @rmtoll I2SCFGR ASTRTEN LL_I2S_DisableAsyncStart + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableAsyncStart(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_ASTRTEN); +} + +/** + * @brief Check if asynchronous start is enabled + * @rmtoll I2SCFGR ASTRTEN LL_I2S_IsEnabledAsyncStart + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_ASTRTEN) == (SPI_I2SCFGR_ASTRTEN)) ? 1UL : 0UL); +} +#endif /* SPI_I2SCFGR_ASTRTEN */ + +/** + * @} + */ + +/** @defgroup I2S_LL_EF_FLAG FLAG Management + * @{ + */ + +/** + * @brief Check if Rx buffer is not empty + * @rmtoll SR RXNE LL_I2S_IsActiveFlag_RXNE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsActiveFlag_RXNE(SPIx); +} + +/** + * @brief Check if Tx buffer is empty + * @rmtoll SR TXE LL_I2S_IsActiveFlag_TXE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsActiveFlag_TXE(SPIx); +} + +/** + * @brief Get busy flag + * @rmtoll SR BSY LL_I2S_IsActiveFlag_BSY + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsActiveFlag_BSY(SPIx); +} + +/** + * @brief Get overrun error flag + * @rmtoll SR OVR LL_I2S_IsActiveFlag_OVR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsActiveFlag_OVR(SPIx); +} + +/** + * @brief Get underrun error flag + * @rmtoll SR UDR LL_I2S_IsActiveFlag_UDR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)) ? 1UL : 0UL); +} + +/** + * @brief Get frame format error flag + * @rmtoll SR FRE LL_I2S_IsActiveFlag_FRE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsActiveFlag_FRE(SPIx); +} + +/** + * @brief Get channel side flag. + * @note 0: Channel Left has to be transmitted or has been received\n + * 1: Channel Right has to be transmitted or has been received\n + * It has no significance in PCM mode. + * @rmtoll SR CHSIDE LL_I2S_IsActiveFlag_CHSIDE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)) ? 1UL : 0UL); +} + +/** + * @brief Clear overrun error flag + * @rmtoll SR OVR LL_I2S_ClearFlag_OVR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_ClearFlag_OVR(SPI_TypeDef *SPIx) +{ + LL_SPI_ClearFlag_OVR(SPIx); +} + +/** + * @brief Clear underrun error flag + * @rmtoll SR UDR LL_I2S_ClearFlag_UDR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_ClearFlag_UDR(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->SR; + (void)tmpreg; +} + +/** + * @brief Clear frame format error flag + * @rmtoll SR FRE LL_I2S_ClearFlag_FRE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_ClearFlag_FRE(SPI_TypeDef *SPIx) +{ + LL_SPI_ClearFlag_FRE(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_LL_EF_IT Interrupt Management + * @{ + */ + +/** + * @brief Enable error IT + * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). + * @rmtoll CR2 ERRIE LL_I2S_EnableIT_ERR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableIT_ERR(SPI_TypeDef *SPIx) +{ + LL_SPI_EnableIT_ERR(SPIx); +} + +/** + * @brief Enable Rx buffer not empty IT + * @rmtoll CR2 RXNEIE LL_I2S_EnableIT_RXNE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableIT_RXNE(SPI_TypeDef *SPIx) +{ + LL_SPI_EnableIT_RXNE(SPIx); +} + +/** + * @brief Enable Tx buffer empty IT + * @rmtoll CR2 TXEIE LL_I2S_EnableIT_TXE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableIT_TXE(SPI_TypeDef *SPIx) +{ + LL_SPI_EnableIT_TXE(SPIx); +} + +/** + * @brief Disable error IT + * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). + * @rmtoll CR2 ERRIE LL_I2S_DisableIT_ERR + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableIT_ERR(SPI_TypeDef *SPIx) +{ + LL_SPI_DisableIT_ERR(SPIx); +} + +/** + * @brief Disable Rx buffer not empty IT + * @rmtoll CR2 RXNEIE LL_I2S_DisableIT_RXNE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableIT_RXNE(SPI_TypeDef *SPIx) +{ + LL_SPI_DisableIT_RXNE(SPIx); +} + +/** + * @brief Disable Tx buffer empty IT + * @rmtoll CR2 TXEIE LL_I2S_DisableIT_TXE + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) +{ + LL_SPI_DisableIT_TXE(SPIx); +} + +/** + * @brief Check if ERR IT is enabled + * @rmtoll CR2 ERRIE LL_I2S_IsEnabledIT_ERR + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsEnabledIT_ERR(SPIx); +} + +/** + * @brief Check if RXNE IT is enabled + * @rmtoll CR2 RXNEIE LL_I2S_IsEnabledIT_RXNE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsEnabledIT_RXNE(SPIx); +} + +/** + * @brief Check if TXE IT is enabled + * @rmtoll CR2 TXEIE LL_I2S_IsEnabledIT_TXE + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsEnabledIT_TXE(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_LL_EF_DMA DMA Management + * @{ + */ + +/** + * @brief Enable DMA Rx + * @rmtoll CR2 RXDMAEN LL_I2S_EnableDMAReq_RX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableDMAReq_RX(SPI_TypeDef *SPIx) +{ + LL_SPI_EnableDMAReq_RX(SPIx); +} + +/** + * @brief Disable DMA Rx + * @rmtoll CR2 RXDMAEN LL_I2S_DisableDMAReq_RX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) +{ + LL_SPI_DisableDMAReq_RX(SPIx); +} + +/** + * @brief Check if DMA Rx is enabled + * @rmtoll CR2 RXDMAEN LL_I2S_IsEnabledDMAReq_RX + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsEnabledDMAReq_RX(SPIx); +} + +/** + * @brief Enable DMA Tx + * @rmtoll CR2 TXDMAEN LL_I2S_EnableDMAReq_TX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_EnableDMAReq_TX(SPI_TypeDef *SPIx) +{ + LL_SPI_EnableDMAReq_TX(SPIx); +} + +/** + * @brief Disable DMA Tx + * @rmtoll CR2 TXDMAEN LL_I2S_DisableDMAReq_TX + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) +{ + LL_SPI_DisableDMAReq_TX(SPIx); +} + +/** + * @brief Check if DMA Tx is enabled + * @rmtoll CR2 TXDMAEN LL_I2S_IsEnabledDMAReq_TX + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +{ + return LL_SPI_IsEnabledDMAReq_TX(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_LL_EF_DATA DATA Management + * @{ + */ + +/** + * @brief Read 16-Bits in data register + * @rmtoll DR DR LL_I2S_ReceiveData16 + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x0000 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint16_t LL_I2S_ReceiveData16(SPI_TypeDef *SPIx) +{ + return LL_SPI_ReceiveData16(SPIx); +} + +/** + * @brief Write 16-Bits in data register + * @rmtoll DR DR LL_I2S_TransmitData16 + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x0000 and Max_Data=0xFFFF + * @retval None + */ +__STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) +{ + LL_SPI_TransmitData16(SPIx, TxData); +} + +/** + * @} + */ + +#if defined(USE_FULL_LL_DRIVER) +/** @defgroup I2S_LL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); +void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); +void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) +ErrorStatus LL_I2S_InitFullDuplex(SPI_TypeDef *I2Sxext, LL_I2S_InitTypeDef *I2S_InitStruct); +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32F4xx_LL_SPI_H */ + diff --git a/boards/DJI_Board_TypeC/Makefile b/boards/DJI_Board_TypeC/Makefile index e3bfeee9..cb7e42bc 100644 --- a/boards/DJI_Board_TypeC/Makefile +++ b/boards/DJI_Board_TypeC/Makefile @@ -1,5 +1,5 @@ ########################################################################################################################## -# File automatically-generated by tool: [projectgenerator] version: [4.1.0] date: [Mon Jul 24 21:33:59 CST 2023] +# File automatically-generated by tool: [projectgenerator] version: [4.2.0-B44] date: [Wed Apr 10 18:18:17 PDT 2024] ########################################################################################################################## # ------------------------------------------------ diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index a3661449..acd80709 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -51,3 +51,4 @@ add_subdirectory(autoaim) add_subdirectory(sbus) add_subdirectory(unitree_motor) add_subdirectory(brt_encoder) +add_subdirectory(cybergear) diff --git a/examples/cybergear/CMakeLists.txt b/examples/cybergear/CMakeLists.txt new file mode 100644 index 00000000..b4a0021f --- /dev/null +++ b/examples/cybergear/CMakeLists.txt @@ -0,0 +1,26 @@ +# ---------------------------------------------------------------------- # +# # +# Copyright (C) 2022 # +# Illini RoboMaster @ University of Illinois at Urbana-Champaign. # +# # +# This program is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# ---------------------------------------------------------------------- # + +project(example_cybergear ASM C CXX) + +irm_add_arm_executable(${PROJECT_NAME} + TARGET DJI_Board_TypeC + SOURCES main.cc) + diff --git a/examples/cybergear/main.cc b/examples/cybergear/main.cc new file mode 100644 index 00000000..239023f3 --- /dev/null +++ b/examples/cybergear/main.cc @@ -0,0 +1,60 @@ +/**************************************************************************** + * * + * Copyright (C) 2023 RoboMaster. * + * Illini RoboMaster @ University of Illinois at Urbana-Champaign * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + * * + ****************************************************************************/ + +#include "cmsis_os.h" +#include "main.h" +#include "cybergear.h" +#include "bsp_gpio.h" +#include "bsp_print.h" +#include + +static xiaomi::CAN* can = nullptr; +static xiaomi::CyberGear* cybergear = nullptr; +static bsp::GPIO* key = nullptr; + +void RM_RTOS_Init() { + print_use_usb(); + + key = new bsp::GPIO(KEY_GPIO_Port, KEY_Pin); + can = new xiaomi::CAN(&hcan1); + cybergear = new xiaomi::CyberGear(can, 126, xiaomi::Motion_mode); +} + +void RM_RTOS_Default_Task(const void* args) { + UNUSED(args); + + cybergear->SetZeroPosition(); + + while (true) { + if (key->Read() == 0) { + cybergear->Stop(); + osDelay(100); + } + + cybergear->SendMotionCommand(.1, 0., 0., 0., 0.); + print("angle: %.4f speed: %.4f torque: %.4f temp: %.4f master can ID: %d\r\n", + cybergear->GetAngle(), + cybergear->GetSpeed(), + cybergear->GetTorque(), + cybergear->GetTemperature(), + cybergear->GetMasterCanID()); + osDelay(10); + } +} diff --git a/shared/bsp/bsp_can.cc b/shared/bsp/bsp_can.cc index d4db023d..83243cac 100644 --- a/shared/bsp/bsp_can.cc +++ b/shared/bsp/bsp_can.cc @@ -116,6 +116,30 @@ namespace bsp { return length; } + int CAN::TransmitExt(uint32_t id, const uint8_t data[], uint32_t length) { + RM_EXPECT_TRUE(IS_CAN_DLC(length), "CAN tx data length exceeds limit"); + if (!IS_CAN_DLC(length)) + return -1; + + CAN_TxHeaderTypeDef header = { + .StdId = 0x0, + .ExtId = id, // don't care since we use standard id mode + .IDE = CAN_ID_EXT, + .RTR = CAN_RTR_DATA, + .DLC = length, + .TransmitGlobalTime = DISABLE, + }; + + uint32_t mailbox; + if (HAL_CAN_AddTxMessage(hcan_, &header, (uint8_t*)data, &mailbox) != HAL_OK) + return -1; + + // poll for can transmission to complete + while (HAL_CAN_IsTxMessagePending(hcan_, mailbox)); + + return length; + } + void CAN::RxCallback() { CAN_RxHeaderTypeDef header; uint8_t data[MAX_CAN_DATA_SIZE]; @@ -127,7 +151,7 @@ namespace bsp { callback_id = it->second; // find corresponding callback if (rx_callbacks_[callback_id]) - rx_callbacks_[callback_id](data, rx_args_[callback_id]); + rx_callbacks_[callback_id](data, header, rx_args_[callback_id]); } void CAN::ConfigureFilter(bool is_master) { diff --git a/shared/bsp/bsp_can.h b/shared/bsp/bsp_can.h index 389ee7fa..ff08e400 100644 --- a/shared/bsp/bsp_can.h +++ b/shared/bsp/bsp_can.h @@ -31,7 +31,7 @@ namespace bsp { /* can callback function pointer */ -typedef void (*can_rx_callback_t)(const uint8_t data[], void* args); +typedef void (*can_rx_callback_t)(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args); class CAN { public: @@ -75,14 +75,25 @@ class CAN { */ int Transmit(uint16_t id, const uint8_t data[], uint32_t length); + /** + * @brief transmit can messages with extended frame + * + * @param id tx id + * @param data[] data bytes + * @param length length of data, must be in (0, 8] + * + * @return number of bytes transmitted, -1 if failed + */ + int TransmitExt(uint32_t id, const uint8_t data[], uint32_t length); + /** * @brief callback wrapper called from IRQ context * * @note should not be called explicitly form the application side */ - void RxCallback(); + virtual void RxCallback(); - private: + protected: void ConfigureFilter(bool is_master); CAN_HandleTypeDef* hcan_; diff --git a/shared/bsp/bsp_can_bridge.cc b/shared/bsp/bsp_can_bridge.cc index df2b9648..813bdf0f 100644 --- a/shared/bsp/bsp_can_bridge.cc +++ b/shared/bsp/bsp_can_bridge.cc @@ -24,7 +24,8 @@ namespace bsp { -static void bridge_callback(const uint8_t data[], void* args) { +static void bridge_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; CanBridge* bridge = reinterpret_cast(args); bridge->UpdateData(data); } diff --git a/shared/libraries/cybergear.cc b/shared/libraries/cybergear.cc new file mode 100644 index 00000000..caa8511f --- /dev/null +++ b/shared/libraries/cybergear.cc @@ -0,0 +1,334 @@ +#include "bsp_os.h" +#include "cybergear.h" +#include + +namespace xiaomi { + +/** + * @brief 提取电机回复帧扩展ID中的电机CANID + * @param[in] CAN_ID_Frame:电机回复帧中的扩展CANID + * @retval 电机CANID + */ +static uint32_t get_motor_id(uint32_t ext_id) +{ + return (ext_id & 0xFFFF) >> 8; +} + +void CAN::RxCallback() { + CAN_RxHeaderTypeDef header; + uint8_t data[MAX_CAN_DATA_SIZE]; + HAL_CAN_GetRxMessage(hcan_, CAN_RX_FIFO0, &header, data); + + uint16_t callback_id = get_motor_id(header.ExtId); + const auto it = id_to_index_.find(callback_id); + if (it == id_to_index_.end()) + return; + callback_id = it->second; + // find corresponding callback + if (rx_callbacks_[callback_id]) + rx_callbacks_[callback_id](data, header, rx_args_[callback_id]); +} + +/** + * @brief 小米电机回文16位数据转浮点 + * @param[in] x:16位回文 + * @param[in] x_min:对应参数下限 + * @param[in] x_max:对应参数上限 + * @param[in] bits:参数位数 + * @retval 返回浮点值 + */ +static float uint16_to_float(uint16_t x, float x_min, float x_max, int bits) +{ + uint32_t span = (1 << bits) - 1; + float offset = x_max - x_min; + return offset * x / span + x_min; +} + +/** + * @brief 小米电机发送浮点转16位数据 + * @param[in] x:浮点 + * @param[in] x_min:对应参数下限 + * @param[in] x_max:对应参数上限 + * @param[in] bits:参数位数 + * @retval 返回浮点值 + */ +static int float_to_uint(float x, float x_min, float x_max, int bits) +{ + float span = x_max - x_min; + float offset = x_min; + if(x > x_max) x=x_max; + else if(x < x_min) x= x_min; + return (int) ((x-offset)*((float)((1<(args); + switch (header.ExtId >> 24) { + // 通讯类型2 + case Communication_Type_MotorRequest: + motor->UpdateData(data, header); + break; + + // 通讯类型17 + case Communication_Type_GetSingleParameter: + uint16_t index; + float value; + memcpy(&index, data, sizeof(uint16_t)); + memcpy(&value, data + 4, sizeof(float)); + motor->UpdateParameter(index, value); + break; + + // TODO: ignore broadcast and all other message types for now + default: + return; + } +} + +void CyberGear::UpdateData(const uint8_t data[], const CAN_RxHeaderTypeDef& header) { + timestamp_ = bsp::GetHighresTickMicroSec(); + + angle_=uint16_to_float(data[0]<<8 | data[1], P_MIN, P_MAX, 16); + speed_=uint16_to_float(data[2]<<8 | data[3], V_MIN, V_MAX, 16); + torque_=uint16_to_float(data[4]<<8 | data[5], T_MIN, T_MAX, 16); + temp_=(data[6]<<8|data[7])*Temp_Gain; + + master_can_id_ = header.ExtId & 0xFF; + error_code_ = (header.ExtId & 0x1F0000)>>16; +} + +void CyberGear::UpdateParameter(uint16_t index, float value) { +switch (index >> 8) { + case 0x20: + parameters_20_[index & 0xff] = value; + break; + case 0x70: + parameters_70_[index & 0xff] = value; + break; + default: + break; +} +} + +/** + * @brief 写入电机参数 + * @param[in] Motor:对应控制电机结构体 + * @param[in] index:写入参数对应地址 + * @param[in] Value:写入参数值 + * @param[in] Value_type:写入参数数据类型 + * @retval none + */ +void CyberGear::SetMotorParameter(uint16_t index, float value) { + uint8_t tx_data[8]; + uint32_t ext_id = Communication_Type_SetSingleParameter<<24 | Master_CAN_ID<<8 | this->can_id_; + tx_data[0]=index; + tx_data[1]=index>>8; + tx_data[2]=0x00; + tx_data[3]=0x00; + memcpy(tx_data + 4, &value, sizeof(float)); + can_->TransmitExt(ext_id, tx_data, 8); +} + +/** + * @brief 写入电机参数 + * @param[in] Motor:对应控制电机结构体 + * @param[in] index:写入参数对应地址 + * @param[in] Value:写入参数值 + * @param[in] Value_type:写入参数数据类型 + * @retval none + */ +void CyberGear::SetMotorParameter(uint16_t index, uint8_t value) { + uint8_t tx_data[8]; + uint32_t ext_id = Communication_Type_SetSingleParameter<<24 | Master_CAN_ID<<8 | this->can_id_; + tx_data[0]=index; + tx_data[1]=index>>8; + tx_data[2]=0x00; + tx_data[3]=0x00; + tx_data[4]=value; + tx_data[5]=0x00; + tx_data[6]=0x00; + tx_data[7]=0x00; + can_->TransmitExt(ext_id, tx_data, 8); +} + +void CyberGear::GetMotorParameter(uint16_t index) { + uint8_t tx_data[8]; + uint32_t ext_id = Communication_Type_GetSingleParameter<<24 | Master_CAN_ID<<8 | this->can_id_; + tx_data[0]=index; + tx_data[1]=index>>8; + tx_data[2]=0x00; + tx_data[3]=0x00; + tx_data[4]=0x00; + tx_data[5]=0x00; + tx_data[6]=0x00; + tx_data[7]=0x00; + can_->TransmitExt(ext_id, tx_data, 8); +} + +/** + * @brief 小米电机ID检查 + * @param[in] id: 控制电机CAN_ID【出厂默认0x7F】 + * @retval none + */ +// void chack_cybergear(uint8_t ID) +// { +// uint8_t tx_data[8] = {0}; +// txMsg.ExtId = Communication_Type_GetID<<24|Master_CAN_ID<<8|ID; +// can_txd(); +// } + +CyberGear::CyberGear(CAN* can, uint8_t can_id, control_mode_t mode) : can_(can), can_id_(can_id) { + can_->RegisterRxCallback(can_id, cybergear_callback, this); + SetMode(mode); + Start(); +} + +/** + * @brief 使能小米电机 + * @param[in] Motor:对应控制电机结构体 + * @retval none + */ +void CyberGear::Start() +{ + uint8_t tx_data[8] = {0}; + uint32_t ext_id = Communication_Type_MotorEnable<<24|Master_CAN_ID<<8 | can_id_; + can_->TransmitExt(ext_id, tx_data, 8); +} + +/** + * @brief 停止电机 + * @param[in] Motor:对应控制电机结构体 + * @param[in] clear_error:清除错误位(0 不清除 1清除) + * @retval None + */ +void CyberGear::Stop(bool clear_error) +{ + uint8_t tx_data[8] = {0}; + tx_data[0] = clear_error;//清除错误位设置 + uint32_t ext_id = Communication_Type_MotorStop<<24|Master_CAN_ID<<8|can_id_; + can_->TransmitExt(ext_id, tx_data, 8); +} + +/** + * @brief 设置电机模式(必须停止时调整!) + * @param[in] Motor: 电机结构体 + * @param[in] Mode: 电机工作模式(1.运动模式Motion_mode 2. 位置模式Position_mode 3. 速度模式Speed_mode 4. 电流模式Current_mode) + * @retval none + */ +void CyberGear::SetMode(const control_mode_t &mode) +{ + SetMotorParameter(PARAM_RUN_MODE, (uint8_t)mode); +} + +/** + * @brief 设置电机零点 + * @param[in] Motor: 电机结构体 + * @retval none + */ +void CyberGear::SetZeroPosition() +{ + uint8_t tx_data[8]={0}; + tx_data[0] = 1; + uint32_t ext_id = Communication_Type_SetPosZero<<24|Master_CAN_ID<<8|can_id_; + can_->TransmitExt(ext_id, tx_data, 8); +} + +/** + * @brief 设置电机CANID + * @param[in] Motor: 电机结构体 + * @param[in] Motor: 设置新ID + * @retval none + */ +// void set_CANID_cybergear(MI_Motor *Motor,uint8_t CAN_ID) +// { +// uint8_t tx_data[8]={0}; +// txMsg.ExtId = Communication_Type_CanID<<24|CAN_ID<<16|Master_CAN_ID<<8|Motor->CAN_ID; +// Motor->CAN_ID = CAN_ID;//将新的ID导入电机结构体 +// can_txd(); +// } + +/** + * @brief 小米运控模式指令 + * @param[in] Motor: 目标电机结构体 + * @param[in] torque: 力矩设置[-12,12] N*M + * @param[in] position: 位置设置[-12.5,12.5] rad + * @param[in] speed: 速度设置[-30,30] rpm + * @param[in] kp: 比例参数设置 + * @param[in] kd: 微分参数设置 + * @retval none + */ +void CyberGear::SendMotionCommand(float torque, float position, float speed, float kp, float kd) +{ + uint8_t tx_data[8];//发送数据初始化 + //装填发送数据 + tx_data[0]=float_to_uint(position,P_MIN,P_MAX,16)>>8; + tx_data[1]=float_to_uint(position,P_MIN,P_MAX,16); + tx_data[2]=float_to_uint(speed,V_MIN,V_MAX,16)>>8; + tx_data[3]=float_to_uint(speed,V_MIN,V_MAX,16); + tx_data[4]=float_to_uint(kp,KP_MIN,KP_MAX,16)>>8; + tx_data[5]=float_to_uint(kp,KP_MIN,KP_MAX,16); + tx_data[6]=float_to_uint(kd,KD_MIN,KD_MAX,16)>>8; + tx_data[7]=float_to_uint(kd,KD_MIN,KD_MAX,16); + + uint32_t ext_id = Communication_Type_MotionControl<<24|float_to_uint(torque,T_MIN,T_MAX,16)<<8|can_id_; + can_->TransmitExt(ext_id, tx_data, 8); +} + +void CyberGear::SendCurrentCommand(float current) { + SetMotorParameter(PARAM_IQ_REF, current); +} + +void CyberGear::SendPositionCommand(float position, float max_speed, float max_current) { + SetMotorParameter(PARAM_LIMIT_CUR, max_current); + SetMotorParameter(PARAM_LIMIT_SPD, max_speed); + SetMotorParameter(PARAM_LOC_REF, position); +} + +void CyberGear::SetPositionKp(float kp) { + SetMotorParameter(PARAM_LOC_KP, kp); +} + +void CyberGear::SetSpeedKp(float kp) { + SetMotorParameter(PARAM_SPD_KP, kp); +} + +void CyberGear::SetSpeedKi(float ki) { + SetMotorParameter(PARAM_SPD_KI, ki); +} + +float CyberGear::GetAngle() const { + return angle_; +} + +float CyberGear::GetSpeed() const { + return speed_; +} + +float CyberGear::GetTorque() const { + return torque_; +} + +float CyberGear::GetTemperature() const { + return temp_; +} + +float CyberGear::GetPositionKp() const { + return parameters_20_[0x16]; +} + +float CyberGear::GetSpeedKp() const { + return parameters_20_[0x14]; +} + +float CyberGear::GetSpeedKi() const { + return parameters_20_[0x15]; +} + +uint8_t CyberGear::GetMasterCanID() const { + return master_can_id_; +} + +uint32_t CyberGear::GetTimeStamp() const { + return timestamp_; +} + +} // namespace xiaomi diff --git a/shared/libraries/cybergear.h b/shared/libraries/cybergear.h new file mode 100644 index 00000000..89843c6e --- /dev/null +++ b/shared/libraries/cybergear.h @@ -0,0 +1,153 @@ +/** + ****************************(C)SWJTU_ROBOTCON**************************** + * @file cybergear.c/h + * @brief 小米电机函数库 + * @note + * @history + * Version Date Author Modification + * V1.0.0 1-10-2023 ZDYukino 1. done + * + @verbatim + ========================================================================= + ========================================================================= + @endverbatim + ****************************(C)SWJTU_ROBOTCON**************************** + **/ +#pragma once + +#include "bsp_can.h" + +//控制参数最值,谨慎更改 +#define P_MIN -12.5f +#define P_MAX 12.5f +#define V_MIN -30.0f +#define V_MAX 30.0f +#define KP_MIN 0.0f +#define KP_MAX 500.0f +#define KD_MIN 0.0f +#define KD_MAX 5.0f +#define T_MIN -12.0f +#define T_MAX 12.0f +// #define MAX_P 720 +// #define MIN_P -720 +//主机CANID设置 +#define Master_CAN_ID 0x00 //主机ID +//控制命令宏定义 +#define Communication_Type_GetID 0x00 //获取设备的ID和64位MCU唯一标识符 +#define Communication_Type_MotionControl 0x01 //用来向主机发送控制指令 +#define Communication_Type_MotorRequest 0x02 //用来向主机反馈电机运行状态 +#define Communication_Type_MotorEnable 0x03 //电机使能运行 +#define Communication_Type_MotorStop 0x04 //电机停止运行 +#define Communication_Type_SetPosZero 0x06 //设置电机机械零位 +#define Communication_Type_CanID 0x07 //更改当前电机CAN_ID +#define Communication_Type_GetSingleParameter 0x11 //读取单个参数 +#define Communication_Type_SetSingleParameter 0x12 //设定单个参数 +#define Communication_Type_ErrorFeedback 0x15 //故障反馈帧 +//参数读取宏定义 +#define PARAM_RUN_MODE 0x7005 +#define PARAM_IQ_REF 0x7006 +#define PARAM_SPD_REF 0x700A +#define PARAM_LIMIT_TORQUE 0x700B +#define PARAM_CUR_KP 0x7010 +#define PARAM_CUR_KI 0x7011 +#define PARAM_CUR_FILT_GAIN 0x7014 +#define PARAM_LOC_REF 0x7016 +#define PARAM_LIMIT_SPD 0x7017 +#define PARAM_LIMIT_CUR 0x7018 +#define PARAM_MECH_POS 0x7019 +#define PARAM_IQF 0x701A +#define PARAM_MECH_VEL 0x701B +#define PARAM_VBUS 0x701C +#define PARAM_ROTATION 0x701D +#define PARAM_LOC_KP 0x701E +#define PARAM_SPD_KP 0x701F +#define PARAM_SPD_KI 0x7020 + +#define Gain_Angle 720/32767.0 +#define Bias_Angle 0x8000 +#define Gain_Speed 30/32767.0 +#define Bias_Speed 0x8000 +#define Gain_Torque 12/32767.0 +#define Bias_Torque 0x8000 +#define Temp_Gain 0.1 + +#define Motor_Error 0x00 +#define Motor_OK 0X01 + +namespace xiaomi { + +class CAN : public bsp::CAN { + public: + using bsp::CAN::CAN; + void RxCallback() override; +}; + +enum control_mode_t //控制模式定义 +{ + Motion_mode = 0, //运控模式 + Position_mode = 1, //位置模式 + Speed_mode = 2, //速度模式 + Current_mode = 3, //电流模式 +}; + +enum error_t //错误回传对照 +{ + OK = 0,//无故障 + BAT_LOW_ERR = 1,//欠压故障 + OVER_CURRENT_ERR = 2,//过流 + OVER_TEMP_ERR = 3,//过温 + MAGNETIC_ERR = 4,//磁编码故障 + HALL_ERR_ERR = 5,//HALL编码故障 + NO_CALIBRATION_ERR = 6//未标定 +}; + +class CyberGear { //小米电机结构体 + public: + CyberGear(CAN* can, uint8_t can_id, control_mode_t mode = Motion_mode); + + void Start(); + void Stop(bool clear_error = true); + void SetMode(const control_mode_t &mode); + void SendMotionCommand(float torque, float position, float speed, float kp, float kd); + void SendCurrentCommand(float current); + void SendPositionCommand(float position, float max_speed = 2.0, float max_current = 23.0); + void SetPositionKp(float kp); + void SetSpeedKp(float kp); + void SetSpeedKi(float ki); + void SetZeroPosition(); + void UpdateData(const uint8_t data[], const CAN_RxHeaderTypeDef& header); + void UpdateParameter(uint16_t index, float value); + + void SetMotorParameter(uint16_t index, float value); + void SetMotorParameter(uint16_t index, uint8_t value); + void GetMotorParameter(uint16_t index); + + float GetAngle() const; + float GetSpeed() const; + float GetTorque() const; + float GetTemperature() const; + float GetPositionKp() const; + float GetSpeedKp() const; + float GetSpeedKi() const; + uint8_t GetMasterCanID() const; + uint32_t GetTimeStamp() const; + + private: + CAN* can_; + uint8_t can_id_; //CAN ID + + float angle_; //回传角度 + float speed_; //回传速度 + float torque_; //回传力矩 + float temp_; //回传温度 + + float parameters_20_[32]; //parameters with address 0x20XX + float parameters_70_[32]; //parameters with address 0x70XX + + uint32_t timestamp_; + + uint8_t master_can_id_; + uint8_t error_code_; +}; + +} // namespace xiaomi diff --git a/shared/libraries/encoder.cc b/shared/libraries/encoder.cc index 00aba56d..1e2a577b 100644 --- a/shared/libraries/encoder.cc +++ b/shared/libraries/encoder.cc @@ -30,7 +30,8 @@ namespace control { // BRT Encoder //================================================================================================== -static void can_encoder_callback(const uint8_t data[], void* args) { +static void can_encoder_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; BRTEncoder* encoder = reinterpret_cast(args); encoder->UpdateData(data); } @@ -43,7 +44,7 @@ BRTEncoder::BRTEncoder(CAN* can, uint16_t rx_id) : can_(can), rx_id_(rx_id) { void BRTEncoder::UpdateData(const uint8_t data[]) { const uint32_t raw_angle = data[6] << 24 | data[5] << 16 | data[4] << 8 | data[3]; - constexpr float THETA_SCALE = 2 * PI / 1024; // digital -> rad + constexpr float THETA_SCALE = 2 * PI / 1024; // digital -> rad // the maximum digital value range is [0 - 1023] angle_ = raw_angle * THETA_SCALE; diff --git a/shared/libraries/motor.cc b/shared/libraries/motor.cc index f92f7492..96e6d940 100644 --- a/shared/libraries/motor.cc +++ b/shared/libraries/motor.cc @@ -45,7 +45,8 @@ int16_t ClipMotorRange(float output) { * @param data data that come from motor * @param args pointer to a MotorCANBase instance */ -static void can_motor_callback(const uint8_t data[], void* args) { +static void can_motor_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; MotorCANBase* motor = reinterpret_cast(args); motor->UpdateData(data); } @@ -159,12 +160,12 @@ uint16_t Motor3508::GetTemp() const { return raw_temperature_; } /* implements data update callback */ void Motor3510::UpdateData(const uint8_t data[]) { const int16_t raw_theta = data[0] << 8 | data[1]; - const int16_t raw_torque = data[2] << 8 | data[3]; - - constexpr float THETA_SCALE = 2 * PI / 8192; + const int16_t raw_torque = data[2] << 8 | data[3]; + + constexpr float THETA_SCALE = 2 * PI / 8192; theta_ = (float)raw_theta * THETA_SCALE; torque_ = (float)raw_torque; - + connection_flag_=true; } @@ -173,7 +174,7 @@ uint16_t Motor3508::GetTemp() const { return raw_temperature_; } print("theta: %.4f ", theta_); print("raw_torque: %.4f \r\n", torque_); } - + /* override base implementation with max current protection */ void Motor3510::SetOutput(int16_t val){ constexpr int16_t MAX_ABS_CURRENT = 29000; @@ -328,7 +329,8 @@ void Motor2305::SetOutput(int16_t val) { * @param data data that come from motor * @param args pointer to a ServoMotor instance */ -static void servomotor_callback(const uint8_t data[], void* args) { +static void servomotor_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; ServoMotor* servo = reinterpret_cast(args); servo->UpdateData(data); } @@ -632,7 +634,8 @@ bool SteeringMotor::CheckAlignment() { * @param data data that come from motor * @param args pointer to a MotorCANBase instance */ -static void can_motor_4310_callback(const uint8_t data[], void* args) { +static void can_motor_4310_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; Motor4310* motor = reinterpret_cast(args); motor->UpdateData(data); } @@ -755,7 +758,7 @@ void Motor4310::TransmitOutput(Motor4310* motors[], uint8_t num_motors) { } else { RM_EXPECT_TRUE(false, "Invalid mode number!"); } - + motors[i]->can_->Transmit(motors[i]->tx_id_actual_, data, 8); } } diff --git a/shared/libraries/motor.h b/shared/libraries/motor.h index edcdbc7b..396d8ea0 100644 --- a/shared/libraries/motor.h +++ b/shared/libraries/motor.h @@ -209,7 +209,7 @@ class Motor3508 : public MotorCANBase { uint16_t GetTemp() const override final; - + private: volatile int16_t raw_current_get_ = 0; @@ -240,7 +240,7 @@ class Motor3510 : public MotorCANBase { private: volatile float torque_ = 0; /* Torque Value*/ volatile float previous_position_ = 0; - + }; //================================================================================================== diff --git a/shared/libraries/supercap.cc b/shared/libraries/supercap.cc index 9e58c507..aa6bc149 100644 --- a/shared/libraries/supercap.cc +++ b/shared/libraries/supercap.cc @@ -24,7 +24,8 @@ namespace control { -static void supercap_callback(const uint8_t data[], void* args) { +static void supercap_callback(const uint8_t data[], const CAN_RxHeaderTypeDef& header, void* args) { + (void)header; SuperCap* supercap = reinterpret_cast(args); supercap->UpdateData(data); } diff --git a/vehicles/CMakeLists.txt b/vehicles/CMakeLists.txt index 2bb85c5b..203a6b51 100644 --- a/vehicles/CMakeLists.txt +++ b/vehicles/CMakeLists.txt @@ -21,3 +21,4 @@ add_subdirectory(Fortress) add_subdirectory(Sentry) add_subdirectory(Steering) +add_subdirectory(MultiCyberGear) diff --git a/vehicles/MultiCyberGear/CMakeLists.txt b/vehicles/MultiCyberGear/CMakeLists.txt new file mode 100644 index 00000000..3eeffffc --- /dev/null +++ b/vehicles/MultiCyberGear/CMakeLists.txt @@ -0,0 +1,32 @@ +# ---------------------------------------------------------------------- # +# # +# Copyright (C) 2024 # +# Illini RoboMaster @ University of Illinois at Urbana-Champaign. # +# # +# This program is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# ---------------------------------------------------------------------- # + +project(MultiCyberGear ASM C CXX) + +irm_add_arm_executable(multi_cybergear + TARGET DJI_Board_TypeC + SOURCES main.cc + DEPENDS eigen3) + +irm_add_arm_executable(comp_cybergear + TARGET DJI_Board_TypeC + SOURCES compensation.cc + DEPENDS eigen3) + diff --git a/vehicles/MultiCyberGear/compensation.cc b/vehicles/MultiCyberGear/compensation.cc new file mode 100644 index 00000000..8abc5d24 --- /dev/null +++ b/vehicles/MultiCyberGear/compensation.cc @@ -0,0 +1,165 @@ +/**************************************************************************** + * * + * Copyright (C) 2023 RoboMaster. * + * Illini RoboMaster @ University of Illinois at Urbana-Champaign * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + * * + ****************************************************************************/ + +#include + +#include "bsp_print.h" +#include "bsp_os.h" +#include "bsp_gpio.h" +#include "cmsis_os2.h" +#include "main.h" + +#include "cybergear.h" + +#define MOTOR_BASE_ID 127 +#define MOTOR_ARM1_ID 126 +#define MOTOR_ARM2_ID 125 + +#define MOTOR_WEIGHT 0.317 +#define ARM_WEIGHT 0.1 +#define ARM_LENGTH 0.13 +#define GRAVITY 9.8 + +#include + +namespace sym { + +/** + * This function was autogenerated. Do not modify by hand. + * + * Args: + * theta2: Scalar + * theta3: Scalar + * m_motor: Scalar + * m_arm: Scalar + * g: Scalar + * l: Scalar + * + * Outputs: + * t2: Scalar + * t3: Scalar + */ +template +void Forward(const Scalar theta2, const Scalar theta3, const Scalar m_motor, const Scalar m_arm, + const Scalar g, const Scalar l, Scalar* const t2 = nullptr, + Scalar* const t3 = nullptr) { + // Total ops: 27 + + // Input arrays + + // Intermediate terms (7) + const Scalar _tmp0 = std::sin(theta2); + const Scalar _tmp1 = _tmp0 * l; + const Scalar _tmp2 = g * m_motor; + const Scalar _tmp3 = g * m_arm; + const Scalar _tmp4 = l * (_tmp0 * std::cos(theta3) - std::sin(theta3) * std::cos(theta2)); + const Scalar _tmp5 = (Scalar(1) / Scalar(2)) * _tmp4; + const Scalar _tmp6 = -_tmp1; + + // Output terms (2) + if (t2 != nullptr) { + Scalar& _t2 = (*t2); + + _t2 = _tmp1 * _tmp2 + (Scalar(1) / Scalar(2)) * _tmp1 * _tmp3 - _tmp2 * (-_tmp4 + _tmp6) - + _tmp3 * (-_tmp5 + _tmp6); + } + + if (t3 != nullptr) { + Scalar& _t3 = (*t3); + + _t3 = -_tmp2 * _tmp4 - _tmp3 * _tmp5; + } +} // NOLINT(readability/fn_size) + +// NOLINTNEXTLINE(readability/fn_size) +} // namespace sym + +osTimerId_t controlTimer; +const osTimerAttr_t controlTimerAttribute = { + .name = "controlTimer", + .attr_bits = 0, + .cb_mem = nullptr, + .cb_size = 0, +}; + +static xiaomi::CAN* can = nullptr; +//static xiaomi::CyberGear* motor_base = nullptr; +static xiaomi::CyberGear* motor_arm1 = nullptr; +static xiaomi::CyberGear* motor_arm2 = nullptr; +static bsp::GPIO* key = nullptr; + +void controlTask(void* arg) { + UNUSED(arg); + + float theta2 = motor_arm1->GetAngle(); + float theta3 = motor_arm2->GetAngle(); + float t2, t3; + + sym::Forward(theta2, theta3, MOTOR_WEIGHT, ARM_WEIGHT, GRAVITY, ARM_LENGTH, &t2, &t3); + + print("t2: %.4f t3: %.4f\r\n", t2, t3); + + motor_arm1->SendMotionCommand(-t2, 0, 0, 0, 0); + motor_arm2->SendMotionCommand(-t3, 0, 0, 0, 0); +} + +//================================================================================================== +// RM Init +//================================================================================================== + +void RM_RTOS_Init(void) { + print_use_usb(); + + bsp::SetHighresClockTimer(&htim5); + + key = new bsp::GPIO(KEY_GPIO_Port, KEY_Pin); + can = new xiaomi::CAN(&hcan1); + //motor_base = new xiaomi::CyberGear(can, MOTOR_BASE_ID, xiaomi::Motion_mode); + motor_arm1 = new xiaomi::CyberGear(can, MOTOR_ARM1_ID, xiaomi::Motion_mode); + motor_arm2 = new xiaomi::CyberGear(can, MOTOR_ARM2_ID, xiaomi::Motion_mode); +} + +void RM_RTOS_Timers_Init(void) { + controlTimer = osTimerNew(controlTask, osTimerPeriodic, nullptr, &controlTimerAttribute); +} + +//================================================================================================== +// RM Default Task +//================================================================================================== + +void RM_RTOS_Default_Task(const void* arg) { + UNUSED(arg); + + //motor_base->SetZeroPosition(); + motor_arm1->SetZeroPosition(); + motor_arm2->SetZeroPosition(); + + osDelay(1000); + + osTimerStart(controlTimer, 10U); + + while (true) { + osDelay(10); + } +} + +//================================================================================================== +// END +//================================================================================================== diff --git a/vehicles/MultiCyberGear/main.cc b/vehicles/MultiCyberGear/main.cc new file mode 100644 index 00000000..7b15e0a3 --- /dev/null +++ b/vehicles/MultiCyberGear/main.cc @@ -0,0 +1,310 @@ +/**************************************************************************** + * * + * Copyright (C) 2023 RoboMaster. * + * Illini RoboMaster @ University of Illinois at Urbana-Champaign * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + * * + ****************************************************************************/ + +#include + +#include "bsp_print.h" +#include "bsp_os.h" +#include "bsp_gpio.h" +#include "cmsis_os2.h" +#include "main.h" + +#include "cybergear.h" + +#define MOTOR_BASE_ID 127 +#define MOTOR_ARM1_ID 126 + +#define MOTOR_BASE_TARGET_ANGLE (-0.4049) +#define MOTOR_ARM1_TARGET_ANGLE (-1.785) + +#define KP 5.0 +#define KD 0.6 + +#define MOTOR_WEIGHT 0.317 +#define ARM1_LENGTH 0.13 +#define GRAVITY 9.8 + +#include + +namespace sym { + +/** + * This function was autogenerated. Do not modify by hand. + * + * Args: + * t1: Scalar + * tdot1: Scalar + * t2: Scalar + * tdot2: Scalar + * m: Scalar + * dt: Scalar + * l: Scalar + * g: Scalar + * tau1: Scalar + * tau2: Scalar + * + * Outputs: + * f: Matrix51 + * A_mat: Matrix55 + * B_mat: Matrix52 + */ +template +void Forward(const Scalar t1, const Scalar tdot1, const Scalar t2, const Scalar tdot2, + const Scalar m, const Scalar dt, const Scalar l, const Scalar g, const Scalar tau1, + const Scalar tau2, Eigen::Matrix* const f = nullptr, + Eigen::Matrix* const A_mat = nullptr, + Eigen::Matrix* const B_mat = nullptr) { + // Total ops: 43 + + // Input arrays + + // Intermediate terms (13) + const Scalar _tmp0 = std::pow(l, Scalar(2)); + const Scalar _tmp1 = std::sin(t2); + const Scalar _tmp2 = _tmp0 * std::pow(_tmp1, Scalar(2)) * dt; + const Scalar _tmp3 = _tmp2 * m + Scalar(0.10000000000000001); + const Scalar _tmp4 = Scalar(1.0) / (_tmp3); + const Scalar _tmp5 = _tmp1 * m; + const Scalar _tmp6 = _tmp5 * g * l + tau2; + const Scalar _tmp7 = Scalar(1.0) / (m); + const Scalar _tmp8 = dt / _tmp0; + const Scalar _tmp9 = _tmp7 * _tmp8; + const Scalar _tmp10 = dt * std::cos(t2); + const Scalar _tmp11 = tau1 / std::pow(_tmp3, Scalar(2)); + const Scalar _tmp12 = g / l; + + // Output terms (3) + if (f != nullptr) { + Eigen::Matrix& _f = (*f); + + _f(0, 0) = dt * tdot1 + t1; + _f(1, 0) = _tmp4 * tau1 + tdot1; + _f(2, 0) = dt * tdot2 + t2; + _f(3, 0) = _tmp6 * _tmp9 + tdot2; + _f(4, 0) = m; + } + + if (A_mat != nullptr) { + Eigen::Matrix& _A_mat = (*A_mat); + + _A_mat.setZero(); + + _A_mat(0, 0) = 1; + _A_mat(0, 1) = dt; + _A_mat(1, 1) = 1; + _A_mat(1, 2) = -2 * _tmp0 * _tmp10 * _tmp11 * _tmp5; + _A_mat(2, 2) = 1; + _A_mat(3, 2) = _tmp10 * _tmp12; + _A_mat(2, 3) = dt; + _A_mat(3, 3) = 1; + _A_mat(1, 4) = -_tmp11 * _tmp2; + _A_mat(3, 4) = _tmp1 * _tmp12 * _tmp7 * dt - _tmp6 * _tmp8 / std::pow(m, Scalar(2)); + _A_mat(4, 4) = 1; + } + + if (B_mat != nullptr) { + Eigen::Matrix& _B_mat = (*B_mat); + + _B_mat.setZero(); + + _B_mat(1, 0) = _tmp4; + _B_mat(3, 1) = _tmp9; + } +} // NOLINT(readability/fn_size) + +// NOLINTNEXTLINE(readability/fn_size) +} // namespace sym + + +class KalmanFilter { +public: + KalmanFilter() { + // initialize x + x.setZero(); + x[4] = 0.1; + + // initialize P + P.setIdentity(); + + // construct C + C.col(4).setZero(); + C.block<4, 4>(0, 0).setIdentity(); + + // construct Q + Q.setZero(); + Q(0, 0) = 1e-6; + Q(1, 1) = 1e-2; + Q(2, 2) = 1e-6; + Q(3, 3) = 1e-2; + Q(4, 4) = 1e-8; + + // construct R + R.setZero(); + R(0, 0) = 1e-6; + R(1, 1) = 1e-4; + R(2, 2) = 1e-6; + R(3, 3) = 1e-4; + } + + void Update(float tau1, float tau2, float theta1, float dtheta1, float theta2, float dtheta2, float dt) { + Eigen::Matrix x_pred; + Eigen::Matrix P_pred; + Eigen::Matrix A; + Eigen::Matrix B; + + // prediction update + sym::Forward(x[0], x[1], x[2], x[3], x[4], dt, ARM1_LENGTH, GRAVITY, tau1, tau2, &x_pred, &A, &B); + P_pred = A * P * A.transpose() + Q; + + // measurement update + Eigen::Vector4f z(theta1, dtheta1, theta2, dtheta2); + Eigen::Vector4f innovation = z - x.block<4, 1>(0, 0); + innovation[0] = std::remainder(innovation[0], 2.0 * M_PI); + innovation[2] = std::remainder(innovation[2], 2.0 * M_PI); + Eigen::Matrix S = C * P_pred * C.transpose() + R; + Eigen::Matrix K = P_pred * C.transpose() * S.inverse(); + x = x_pred + K * innovation; + P = P_pred - K * C * P_pred; + } + + const Eigen::Matrix GetState() const { + return x; + } + +private: + Eigen::Matrix x; + Eigen::Matrix P; + Eigen::Matrix C; + Eigen::Matrix Q; + Eigen::Matrix R; +}; + + +osTimerId_t controlTimer; +const osTimerAttr_t controlTimerAttribute = { + .name = "controlTimer", + .attr_bits = 0, + .cb_mem = nullptr, + .cb_size = 0, +}; + +osTimerId_t targetTimer; +const osTimerAttr_t targetTimerAttribute = { + .name = "targetTimer", + .attr_bits = 0, + .cb_mem = nullptr, + .cb_size = 0, +}; + +static xiaomi::CAN* can = nullptr; +static xiaomi::CyberGear* motor_base = nullptr; +static xiaomi::CyberGear* motor_arm1 = nullptr; +static bsp::GPIO* key = nullptr; +static KalmanFilter filter; + +static float base_angles[] = {-1.0, -0.5, 0., 0.5, 1.0, 0.5, 0., -0.5}; +static float arm_angles[] = {0.0, 0.4, 0.8, 1.2, 1.6, 1.2, 0.8, 0.4}; +int base_idx = 0; +int arm_idx = 0; + +void controlTask(void* arg) { + UNUSED(arg); + + if (base_idx >= 0 && base_idx < 8) { + motor_base->SendPositionCommand(base_angles[base_idx]); + } + if (arm_idx >= 0 && arm_idx < 8) { + motor_arm1->SendPositionCommand(arm_angles[arm_idx]); + } + + filter.Update(motor_base->GetTorque(), -motor_arm1->GetTorque(), motor_base->GetAngle(), motor_base->GetSpeed() * 2. * M_PI / 60., -motor_arm1->GetAngle(), -motor_arm1->GetSpeed() * 2. * M_PI / 60., 0.002); +} + +void targetTask(void* arg) { + UNUSED(arg); + + base_idx = (base_idx + 1) % 8; + if (base_idx % 8 == 0) { + arm_idx = (arm_idx + 1) % 8; + } +} + +void estimateTask(void* arg) { + UNUSED(arg); +} + +//================================================================================================== +// RM Init +//================================================================================================== + +void RM_RTOS_Init(void) { + print_use_usb(); + + bsp::SetHighresClockTimer(&htim5); + + key = new bsp::GPIO(KEY_GPIO_Port, KEY_Pin); + can = new xiaomi::CAN(&hcan1); + motor_base = new xiaomi::CyberGear(can, MOTOR_BASE_ID, xiaomi::Position_mode); + motor_arm1 = new xiaomi::CyberGear(can, MOTOR_ARM1_ID, xiaomi::Position_mode); +} + +void RM_RTOS_Timers_Init(void) { + controlTimer = osTimerNew(controlTask, osTimerPeriodic, nullptr, &controlTimerAttribute); + targetTimer = osTimerNew(targetTask, osTimerPeriodic, nullptr, &targetTimerAttribute); +} + +//================================================================================================== +// RM Default Task +//================================================================================================== + +void RM_RTOS_Default_Task(const void* arg) { + UNUSED(arg); + + motor_base->SetZeroPosition(); + motor_arm1->SetZeroPosition(); + + motor_base->SendPositionCommand(0.0); + motor_arm1->SendPositionCommand(0.0); + osDelay(1000); + + motor_base->SetSpeedKi(0.002); + motor_arm1->SetSpeedKi(0.002); + motor_base->SetPositionKp(30.); + motor_arm1->SetPositionKp(30.); + motor_base->SetSpeedKp(2.); + motor_arm1->SetSpeedKp(2.); + osDelay(10); + + osTimerStart(controlTimer, 2U); + osDelay(100); + osTimerStart(targetTimer, 1000U); + + while (true) { + const Eigen::Matrix state = filter.GetState(); + + print("estimated mass: %.4f\r\n", state[4]); + + osDelay(10); + } +} + +//================================================================================================== +// END +//==================================================================================================