diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5cc5c04..ec1752f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,32 +1,31 @@ -repos: - - - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 7d85583be209cb547946c82fbe51f4bc5dd1d017 - hooks: - - id: clang-format - args: [--style=Google] - files: \.(cpp|hpp|c|h)$ - stages: [commit] - - - repo: https://github.com/pre-commit/mirrors-prettier - rev: v2.5.1 - hooks: - - id: prettier - files: \.(js|ts|jsx|tsx|css|less|html|json|markdown|md|yaml|yml)$ - - - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.4.1 - hooks: - - id: ruff - types_or: [ python, pyi ] - args: [ --fix ] - stages: [commit] - - id: ruff-format - stages: [commit] - - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml \ No newline at end of file +repos: + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: 7d85583be209cb547946c82fbe51f4bc5dd1d017 + hooks: + - id: clang-format + args: [--style=Google] + files: \.(cpp|hpp|c|h)$ + stages: [pre-commit] + + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v2.5.1 + hooks: + - id: prettier + files: \.(js|ts|jsx|tsx|css|less|html|json|markdown|md|yaml|yml)$ + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.4.1 + hooks: + - id: ruff + types_or: [python, pyi] + args: [--fix] + stages: [pre-commit] + - id: ruff-format + stages: [pre-commit] + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml diff --git a/Components/FDCan.cpp b/Components/FDCan.cpp new file mode 100644 index 0000000..5fc8fed --- /dev/null +++ b/Components/FDCan.cpp @@ -0,0 +1,429 @@ +/* + * FDCan.cpp + * + * Created on: Aug 24, 2024 + * Author: goada + */ + +#include "FDCan.h" + +#include +#include + +#include "main.h" + +FDCanController *callbackcontroller = nullptr; + +void CANError() { + while (1) { + HAL_Delay(100); // + } +} + +FDCanController::~FDCanController() { + if (callbackcontroller == this) { + callbackcontroller = nullptr; + } +} + +#define MIN(a, b) (((a) > (b)) ? (b) : (a)) + +/* @brief Send a string through CANBus, not including the null terminator + * @param msg Null-terminated string + * @param logIndex Index of the log type to be sent + * @return Success + */ +bool FDCanController::SendStringByLogIndex(const char *msg, uint16_t logIndex) { + return SendByMsgID((const uint8_t *)msg, strlen(msg), + registeredLogs[logIndex].startingMsgID); +} + +/* @brief Send a message through CANBus, in multiple frames and incrementing the + * msg ID if needed. + * @param msg Bytes to send + * @param len Length of msg + * @param ID Starting CAN identifier of message, will be incremented if len > 64 + * bytes + * @return Success + */ +bool FDCanController::SendByMsgID(const uint8_t *msg, size_t len, uint16_t ID) { + size_t framesToSend = (len - 1) / 64 + 1; + + if (ID >= 2048 - framesToSend) { + // ID too large + return false; + } + + FDCAN_TxHeaderTypeDef txheader; + txheader.IdType = FDCAN_STANDARD_ID; + txheader.TxFrameType = FDCAN_DATA_FRAME; + txheader.ErrorStateIndicator = FDCAN_ESI_ACTIVE; + txheader.BitRateSwitch = FDCAN_BRS_ON; + txheader.FDFormat = FDCAN_FD_CAN; + txheader.TxEventFifoControl = FDCAN_NO_TX_EVENTS; + txheader.MessageMarker = 0; + txheader.DataLength = FDCAN_DLC_BYTES_64; + + uint8_t data[64]; + + for (size_t frame = 0; frame < framesToSend; frame++) { + txheader.Identifier = ID + frame; + + // Length will be 64 bytes, except for the final frame, + // which will be minimum required for the remaining data + if (frame == framesToSend - 1) txheader.DataLength = FDGetModDLC(len); + + // If data won't fill the whole buffer, fill buf with zeros. + if (len < 64) { + memset(data + len, 0x00, 64 - len); + } + + memcpy(data, msg + 64 * frame, MIN(len, 64)); + len -= 64; + + while (HAL_FDCAN_GetTxFifoFreeLevel(fdcan) < 1) { + } + + HAL_StatusTypeDef stat = + HAL_FDCAN_AddMessageToTxFifoQ(fdcan, &txheader, &data[0]); + + if (stat != HAL_OK) { + return false; + } + } + + return true; +} + +/* @brief Callback for receiving a CAN message. + * @param CAN handle + */ +void RXMsgCallback(FDCAN_HandleTypeDef *fdcan) { + if (callbackcontroller) callbackcontroller->RaiseFXFlag(); +} + +// TODO +// make it able to register all the logs after being initialized. needed because +// the autonode needs to use the driver to send a join request, THEN decide what its log IDs are + + + +/* @brief Constructor. Also initializes FDCAN filters and callback. + * Calls CANError if error in initialization. Two controllers should not + * share the same FDCAN peripheral. + * @param fdcan Handle to FDCAN peripheral + */ +FDCanController::FDCanController(FDCAN_HandleTypeDef *fdcan, + FDCanController::LogInitStruct *logs, + uint16_t numLogs) { + this->fdcan = fdcan; + + + + InitFDCAN(); +} + +/* @brief Registers a filter that directs an FDCAN message ID to a certain RX + * buffer. Filter will be placed in next available filter slot. Must ensure + * there are enough Std Filters configured in the FDCAN parameter settings. + * @param msgID FDCAN message ID to direct. + * @param rxBufferNum FDCAN RX buffer index to direct to. + * @return HAL_OK on success. + */ +HAL_StatusTypeDef FDCanController::RegisterFilterRXBuf(uint16_t msgID, + uint8_t rxBufferNum) { + if (nextUnregisteredFilterID >= numFDFilters) { + return HAL_ERROR; + } + FDCAN_FilterTypeDef filter; + + filter.IdType = FDCAN_STANDARD_ID; + filter.FilterIndex = nextUnregisteredFilterID; + filter.FilterConfig = FDCAN_FILTER_TO_RXBUFFER; + filter.FilterID1 = msgID; + filter.RxBufferIndex = rxBufferNum; + filter.IsCalibrationMsg = 0; + + nextUnregisteredFilterID++; + return HAL_FDCAN_ConfigFilter(fdcan, &filter); +} + +/* @brief Registers a series of RX buffers where a (multi-frame) log data + * matching a certain range of message IDs will be directed. Once registered, + * receiving a frame into the latest of these buffers will trigger the callback. + * The log will require one frame per 64 bytes, rounded up. + * @param msgIDStart The lowest message ID that the (multi-frame) log will + * contain. Will use one successive ID per required frame. Different log types + * must not register overlapping ID ranges. Must be between 0 and 2048-[required + * frames]. + * @param rxBufStart The lowest RX buffer index the log will be directed to. + * Must be between 0 and [registered + * buffer num]-[required frames]. + * @param length Length in bytes that the log contains. + */ +HAL_StatusTypeDef FDCanController::RegisterLogType(uint16_t msgIDStart, + uint8_t rxBufStart, + uint16_t length) { + registeredLogs[numRegisteredLogs].startingRXBuf = rxBufStart; + registeredLogs[numRegisteredLogs].endingRXBuf = + rxBufStart + (length - 1) / 64; + registeredLogs[numRegisteredLogs].byteLength = length; + registeredLogs[numRegisteredLogs].startingMsgID = msgIDStart; + for (uint16_t i = 0; i < ((length - 1) / 64 + 1); i++) { + HAL_StatusTypeDef stat = + RegisterFilterRXBuf(msgIDStart + i, rxBufStart + i); + if (stat != HAL_OK) { + return stat; + } + } + numRegisteredLogs++; + return HAL_OK; +} + +/* @brief FDCAN frames can only be certain size values between 0 and 64. + * Returns next-highest valid FDCAN size for a given byte length. + * @param unroundedlen Byte length to be rounded. + * @return Total byte size representable by series of valid FDCAN frame sizes. + */ +const uint16_t FDCanController::FDRoundDataSize(uint16_t unroundedLen) { + uint8_t mod = (unroundedLen - 1) % 64 + 1; + + // Round up remainder + if (mod <= 8) { + } else if (mod <= 12) + mod = 12; + else if (mod <= 16) + mod = 16; + else if (mod <= 20) + mod = 20; + else if (mod <= 24) + mod = 24; + else if (mod <= 32) + mod = 32; + else if (mod <= 48) + mod = 48; + else + mod = 64; + + return (unroundedLen - 1) / 64 * 64 + mod; +} + +/* @brief Returns the FDCAN DLC code of the final frame required to send a msg + * of given size. + * @param unroundedlen Total message size in bytes + * @return Valid FDCAN_DLC_BYTES value capable of containing final frame size + */ +const uint32_t FDCanController::FDGetModDLC(uint16_t unroundedLen) { + uint8_t mod = (unroundedLen - 1) % 64 + 1; + + if (mod <= 8) return mod; + if (mod <= 12) return FDCAN_DLC_BYTES_12; + if (mod <= 16) return FDCAN_DLC_BYTES_16; + if (mod <= 20) return FDCAN_DLC_BYTES_20; + if (mod <= 24) return FDCAN_DLC_BYTES_24; + if (mod <= 32) return FDCAN_DLC_BYTES_32; + if (mod <= 48) return FDCAN_DLC_BYTES_48; + return FDCAN_DLC_BYTES_64; +} + +inline void FDCanController::RaiseFXFlag() { RXFlag = true; } + +/* @brief Faster version of HAL_FDCAN_GetRxMessage that assumes an RX buffer + * and does not return an Rx Header. + * @param fdcan Handle to the FDCAN + * @param buf RX buffer number + * @param data Pointer to buffer that will receive data from this buffer. + */ +HAL_StatusTypeDef fastGetRXMsg(FDCAN_HandleTypeDef *fdcan, uint8_t buf, + uint8_t *data) { + uint32_t *RxAddress; + HAL_FDCAN_StateTypeDef state = fdcan->State; + + if (state == HAL_FDCAN_STATE_BUSY) { + /* Calculate Rx buffer address */ + RxAddress = (uint32_t *)(fdcan->msgRam.RxBufferSA + + (buf * fdcan->Init.RxBufferSize * 4U)) + + 1; + + uint32_t DataLength = ((*RxAddress & ((uint32_t)0x000F0000U)) >> 16U); + + RxAddress++; + + /* Retrieve Rx payload */ + static const uint8_t DLCtoBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, + 8, 12, 16, 20, 24, 32, 48, 64}; + memcpy(data, (uint8_t *)RxAddress, DLCtoBytes[DataLength]); + + /* Clear the New Data flag of the current Rx buffer */ + if (buf < FDCAN_RX_BUFFER32) { + fdcan->Instance->NDAT1 = ((uint32_t)1U << buf); + } else /* FDCAN_RX_BUFFER32 <= RxLocation <= FDCAN_RX_BUFFER63 */ + { + fdcan->Instance->NDAT2 = ((uint32_t)1U << (buf & 0x1FU)); + } + + /* Return function status */ + return HAL_OK; + } else { + /* Update error code */ + fdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/* @brief Receives the first full message collected in the dedicated RX buffers + * into the out buffer. + * @param out Output data. Must be the size of the maximum expected message + * size, rounded with FDRoundDataSize(). + * @param logID Output of the index of the log. + * @return Size in bytes of received message. If no message, returns 0 and out + * is unmodified. + */ +uint16_t FDCanController::ReceiveFirstLogFromRXBuf(uint8_t *out, + uint16_t *logID) { + if (!RXFlag) { + return 0; + } + for (uint8_t i = 0; i < numRegisteredLogs; i++) { + uint16_t len = ReceiveLogTypeFromRXBuf(out, i); + if (len > 0) { + // data now contains entire multi-frame log, potentially padded with + // some 0s + // Received full log, do send or something + *logID = i; + return len; + } + } + RXFlag = false; + return 0; +} + +uint16_t FDCanController::ReceiveLogTypeFromRXBuf(uint8_t *out, + uint16_t logIndexFilter) { + if (!RXFlag) { + return 0; + } + + const LogRegister &thisRegisteredLog = registeredLogs[logIndexFilter]; + if (thisRegisteredLog.byteLength == 0) { + return 0; + } + if (HAL_FDCAN_IsRxBufferMessageAvailable(fdcan, + thisRegisteredLog.endingRXBuf)) { + if (readingRXBufSemaphore) { + return 0; // something else using the semaphore + } + readingRXBufSemaphore = true; + + // Received full log + uint8_t *d = out; + for (uint8_t b = thisRegisteredLog.startingRXBuf; + b <= thisRegisteredLog.endingRXBuf; b++) { + fastGetRXMsg(fdcan, b, d); + d += 64; + } + + readingRXBufSemaphore = false; + // data now contains entire multi-frame log, potentially padded with + // some 0s + // Received full log, do send or something + return thisRegisteredLog.byteLength; + } + + return 0; +} + +/* @brief Sends a log message to a registered buffer. + * @param msg Pointer to data to send. Must be large enough to hold the target + * log's size. + * @param logIndex Index of the log to send to. + */ +bool FDCanController::SendByLogIndex(const uint8_t *msg, uint16_t logIndex) { + return SendByMsgID(msg, registeredLogs[logIndex].byteLength, + registeredLogs[logIndex].startingMsgID); +} + +HAL_StatusTypeDef FDCanController::RegisterLogs(LogInitStruct *logs, uint16_t numLogs) { + + for (uint16_t i = 0; i < numLogs; i++) { + numFDFilters += (logs[i].byteLength - 1) / 64 + 1; + } + + fdcan->Init.RxBuffersNbr = numFDFilters; + fdcan->Init.StdFiltersNbr = numFDFilters; + fdcan->Init.RxBufferSize = FDCAN_DATA_BYTES_64; + fdcan->Init.RxFifo0ElmtSize = FDCAN_DATA_BYTES_64; + fdcan->Init.TxElmtSize = FDCAN_DATA_BYTES_64; + + if (HAL_FDCAN_Init(fdcan) != HAL_OK) { + CANError(); + } + + for (uint16_t i = 0; i < numLogs; i++) { + if (RegisterLogType(logs[i].startingMsgID, nextUnregisteredFilterID, + logs[i].byteLength) != HAL_OK) { + CANError(); + } + } + + return HAL_FDCAN_Start(fdcan); +} + +/* @brief Registers a filter that directs a range of msg IDs to RX FIFO 0. + * @param msgIDMin Minimum message ID, inclusive, 0-2047 + * @param msgIDMax Maximum message ID, inclusive, 0-2047 + * @return HAL_OK on success + */ +HAL_StatusTypeDef FDCanController::RegisterFilterRXFIFO(uint16_t msgIDMin, + uint16_t msgIDMax) { + FDCAN_FilterTypeDef filter; + filter.IdType = FDCAN_STANDARD_ID; + filter.FilterIndex = nextUnregisteredFilterID; + filter.FilterType = FDCAN_FILTER_RANGE; + filter.FilterConfig = FDCAN_FILTER_TO_RXFIFO0; + filter.FilterID1 = msgIDMin; + filter.FilterID2 = msgIDMax; + + nextUnregisteredFilterID++; + return HAL_FDCAN_ConfigFilter(fdcan, &filter); +} + +HAL_StatusTypeDef FDCanController::GetRxFIFO(uint8_t *out, uint32_t *msgIDOut) { + if(HAL_FDCAN_GetRxFifoFillLevel(fdcan, 0) == 0) { + return HAL_ERROR; + } + FDCAN_RxHeaderTypeDef header; + HAL_FDCAN_GetRxMessage(fdcan, FDCAN_RX_FIFO0, &header, out); + *msgIDOut = header.Identifier; + return HAL_OK; +} + +HAL_StatusTypeDef FDCanController::InitFDCAN() { + HAL_StatusTypeDef stat; + if (HAL_FDCAN_ConfigGlobalFilter(fdcan, FDCAN_REJECT, FDCAN_REJECT, + FDCAN_REJECT_REMOTE, + FDCAN_REJECT_REMOTE) != HAL_OK) { + CANError(); + } + + // Turn on callback for receiving msg + stat = + HAL_FDCAN_ActivateNotification(fdcan, FDCAN_IT_RX_BUFFER_NEW_MESSAGE, 0); + if (stat != HAL_OK) { + CANError(); + } + + // Set callback + stat = HAL_FDCAN_RegisterCallback(fdcan, HAL_FDCAN_RX_BUFFER_NEW_MSG_CB_ID, + RXMsgCallback); + if (stat != HAL_OK) { + CANError(); + } + + stat = HAL_FDCAN_Start(fdcan); + if (stat != HAL_OK) { + CANError(); + } + return stat; +} diff --git a/Components/FDCan.h b/Components/FDCan.h new file mode 100644 index 0000000..37c232b --- /dev/null +++ b/Components/FDCan.h @@ -0,0 +1,80 @@ +/* + * FDCan.hpp + * + * Created on: Aug 24, 2024 + * Author: goada + */ + +#ifndef FDCAN_H_ +#define FDCAN_H_ + +#include "stm32h7xx.h" + +constexpr size_t MAX_FDCAN_RX_BUFFERS = 64; + +class FDCanController { + public: + struct LogInitStruct { + uint16_t byteLength = 0; + uint16_t startingMsgID = 0; + }; + + FDCanController(FDCAN_HandleTypeDef *fdcan, + FDCanController::LogInitStruct *logs, uint16_t numLogs); + ~FDCanController(); + FDCanController(const FDCanController &) = delete; + FDCanController &operator=(const FDCanController &) = delete; + + bool SendByLogIndex(const uint8_t *msg, uint16_t logIndex); + + bool SendStringByLogIndex(const char *msg, uint16_t logIndex); + + bool SendByMsgID(const uint8_t *msg, size_t len, uint16_t ID); + + HAL_StatusTypeDef RegisterLogs(LogInitStruct *logs, uint16_t numLogs); + + uint16_t ReceiveFirstLogFromRXBuf(uint8_t *out, uint16_t *msgID); + uint16_t ReceiveLogTypeFromRXBuf(uint8_t *out, uint16_t logIndexFilter); + + HAL_StatusTypeDef RegisterLogType(uint16_t msgIDStart, uint8_t rxBufStart, + uint16_t length); + + static const uint16_t FDRoundDataSize(uint16_t unroundedLen); + static const uint32_t FDGetModDLC(uint16_t unroundedLen); + + inline void RaiseFXFlag(); + + HAL_StatusTypeDef GetRxFIFO(uint8_t* out, uint32_t* msgIDOut); + HAL_StatusTypeDef RegisterFilterRXFIFO(uint16_t msgIDMin, uint16_t msgIDMax); + + protected: + struct LogRegister { + uint8_t startingRXBuf = 0; + uint8_t endingRXBuf = 0; + uint16_t byteLength = 0; + uint16_t startingMsgID = 0; + }; + + FDCAN_HandleTypeDef *fdcan; + + uint8_t numFDFilters = 0; + + uint8_t nextUnregisteredFilterID = 0; + uint8_t numRegisteredLogs = 0; + LogRegister registeredLogs[MAX_FDCAN_RX_BUFFERS]; + + HAL_StatusTypeDef RegisterFilterRXBuf(uint16_t msgID, uint8_t rxBufferNum); + + HAL_StatusTypeDef InitFDCAN(); + + volatile bool RXFlag = false; + + bool readingRXBufSemaphore = false; +}; + +extern FDCanController *callbackcontroller; +void RXMsgCallback(FDCAN_HandleTypeDef *hfdcan); + +void CANError(); + +#endif /* FDCAN_H_ */ diff --git a/Core/Src/fdcan_testmain.cpp b/Core/Src/fdcan_testmain.cpp new file mode 100644 index 0000000..e6d533a --- /dev/null +++ b/Core/Src/fdcan_testmain.cpp @@ -0,0 +1,373 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : main.c + * @brief : Main program body + ****************************************************************************** + * @attention + * + * Copyright (c) 2024 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ +#include + +#include + +#include "FDCan.h" +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN PTD */ + +/* USER CODE END PTD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ + +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ + +FDCAN_HandleTypeDef hfdcan1; + +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); +static void MPU_Config(void); +static void MX_GPIO_Init(void); +static void MX_FDCAN1_Init(void); +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* Private user code ---------------------------------------------------------*/ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** + * @brief The application entry point. + * @retval int + */ +int main(void) { + /* USER CODE BEGIN 1 */ + + /* USER CODE END 1 */ + + /* MPU Configuration--------------------------------------------------------*/ + MPU_Config(); + + /* MCU Configuration--------------------------------------------------------*/ + + /* Reset of all peripherals, Initializes the Flash interface and the Systick. + */ + HAL_Init(); + + /* USER CODE BEGIN Init */ + + /* USER CODE END Init */ + + /* Configure the system clock */ + SystemClock_Config(); + + /* USER CODE BEGIN SysInit */ + + /* USER CODE END SysInit */ + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + MX_FDCAN1_Init(); + /* USER CODE BEGIN 2 */ + + /* USER CODE END 2 */ + + /* Infinite loop */ + /* USER CODE BEGIN WHILE */ + + // This test code will send one of each these messages in a cycle + FDCanController::LogInitStruct logs[] = {{64, 0}, {64, 1}, {127, 2}, + {257, 4}, {103, 233}, {531, 100}}; + FDCanController cont = { + &hfdcan1, logs, sizeof(logs) / sizeof(FDCanController::LogInitStruct)}; + callbackcontroller = &cont; + + int completed = 0; + uint32_t lastRxTick = HAL_GetTick(); + uint32_t lastTxTick = HAL_GetTick(); + uint32_t totalRxTicks = 0; + uint32_t totalTxTicks = 0; + while (1) { + /* USER CODE END WHILE */ + + /* USER CODE BEGIN 3 */ + uint8_t data[logs[completed % + (sizeof(logs) / sizeof(FDCanController::LogInitStruct))] + .byteLength]; + for (size_t i = 0; i < sizeof(data); i++) { + data[i] = rand(); + } + + lastTxTick = HAL_GetTick(); + cont.SendByLogIndex( + data, + completed % (sizeof(logs) / sizeof(FDCanController::LogInitStruct))); + + { + uint32_t thisTick = HAL_GetTick(); + totalTxTicks += thisTick - lastTxTick; + lastTxTick = thisTick; + } + + uint8_t received_data[FDCanController::FDRoundDataSize(sizeof(data))]; + + memset(received_data, 0x00, sizeof(received_data)); + + uint16_t received_id = 0; + lastRxTick = HAL_GetTick(); + + while (true) { + if (cont.ReceiveFromRXBuf(received_data, &received_id)) { + UNUSED(received_id); + // Verify received data is the same + if (!memcmp(data, received_data, sizeof(data)) || + received_id != + completed % + (sizeof(logs) / sizeof(FDCanController::LogInitStruct))) { + // equal + break; + } else { + Error_Handler(); + } + } + } + // Verify nothing has gone into a FIFO + auto rxfifofilllvl = HAL_FDCAN_GetRxFifoFillLevel(&hfdcan1, FDCAN_RX_FIFO0); + if (rxfifofilllvl >= 1) { + Error_Handler(); + } + { + uint32_t thisTick = HAL_GetTick(); + totalRxTicks += thisTick - lastRxTick; + lastRxTick = thisTick; + } + + completed++; + if (completed % 10000 == 0) { + float elapsedTx = totalTxTicks / 10000.0f; + float elapsedRx = totalRxTicks / 10000.0f; + UNUSED(elapsedTx); + UNUSED(elapsedRx); + totalTxTicks = 0; + totalRxTicks = 0; + // After completed 10000 sends and receives. Add a breakpoint or print + // here. elapsedTx and elapsedRx are the average time in milliseconds. + } + } + /* USER CODE END 3 */ +} + +/** + * @brief System Clock Configuration + * @retval None + */ +void SystemClock_Config(void) { + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + + /*AXI clock gating */ + RCC->CKGAENR = 0xFFFFFFFF; + + /** Supply configuration update enable + */ + HAL_PWREx_ConfigSupply(PWR_DIRECT_SMPS_SUPPLY); + + /** Configure the main internal regulator output voltage + */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0); + + while (!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) { + } + + /** Initializes the RCC Oscillators according to the specified parameters + * in the RCC_OscInitTypeDef structure. + */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; + RCC_OscInitStruct.HSIState = RCC_HSI_DIV1; + RCC_OscInitStruct.HSICalibrationValue = 64; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; + RCC_OscInitStruct.PLL.PLLM = 4; + RCC_OscInitStruct.PLL.PLLN = 35; + RCC_OscInitStruct.PLL.PLLP = 2; + RCC_OscInitStruct.PLL.PLLQ = 4; + RCC_OscInitStruct.PLL.PLLR = 2; + RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3; + RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE; + RCC_OscInitStruct.PLL.PLLFRACN = 0; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + Error_Handler(); + } + + /** Initializes the CPU, AHB and APB buses clocks + */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | + RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2 | + RCC_CLOCKTYPE_D3PCLK1 | RCC_CLOCKTYPE_D1PCLK1; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1; + RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2; + RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2; + RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2; + RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2; + + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_6) != HAL_OK) { + Error_Handler(); + } +} + +/** + * @brief FDCAN1 Initialization Function + * @param None + * @retval None + */ +static void MX_FDCAN1_Init(void) { + /* USER CODE BEGIN FDCAN1_Init 0 */ + + /* USER CODE END FDCAN1_Init 0 */ + + /* USER CODE BEGIN FDCAN1_Init 1 */ + + /* USER CODE END FDCAN1_Init 1 */ + hfdcan1.Instance = FDCAN1; + hfdcan1.Init.FrameFormat = FDCAN_FRAME_FD_BRS; + hfdcan1.Init.Mode = FDCAN_MODE_EXTERNAL_LOOPBACK; + hfdcan1.Init.AutoRetransmission = ENABLE; + hfdcan1.Init.TransmitPause = DISABLE; + hfdcan1.Init.ProtocolException = DISABLE; + hfdcan1.Init.NominalPrescaler = 1; + hfdcan1.Init.NominalSyncJumpWidth = 19; + hfdcan1.Init.NominalTimeSeg1 = 124; + hfdcan1.Init.NominalTimeSeg2 = 19; + hfdcan1.Init.DataPrescaler = 1; + hfdcan1.Init.DataSyncJumpWidth = 8; + hfdcan1.Init.DataTimeSeg1 = 9; + hfdcan1.Init.DataTimeSeg2 = 8; + hfdcan1.Init.MessageRAMOffset = 0; + hfdcan1.Init.StdFiltersNbr = 10; + hfdcan1.Init.ExtFiltersNbr = 0; + hfdcan1.Init.RxFifo0ElmtsNbr = 3; + hfdcan1.Init.RxFifo0ElmtSize = FDCAN_DATA_BYTES_64; + hfdcan1.Init.RxFifo1ElmtsNbr = 0; + hfdcan1.Init.RxFifo1ElmtSize = FDCAN_DATA_BYTES_8; + hfdcan1.Init.RxBuffersNbr = 10; + hfdcan1.Init.RxBufferSize = FDCAN_DATA_BYTES_64; + hfdcan1.Init.TxEventsNbr = 0; + hfdcan1.Init.TxBuffersNbr = 0; + hfdcan1.Init.TxFifoQueueElmtsNbr = 4; + hfdcan1.Init.TxFifoQueueMode = FDCAN_TX_FIFO_OPERATION; + hfdcan1.Init.TxElmtSize = FDCAN_DATA_BYTES_64; + if (HAL_FDCAN_Init(&hfdcan1) != HAL_OK) { + Error_Handler(); + } + /* USER CODE BEGIN FDCAN1_Init 2 */ + + /* USER CODE END FDCAN1_Init 2 */ +} + +/** + * @brief GPIO Initialization Function + * @param None + * @retval None + */ +static void MX_GPIO_Init(void) { + /* USER CODE BEGIN MX_GPIO_Init_1 */ + /* USER CODE END MX_GPIO_Init_1 */ + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + + /* USER CODE BEGIN MX_GPIO_Init_2 */ + /* USER CODE END MX_GPIO_Init_2 */ +} + +/* USER CODE BEGIN 4 */ + +/* USER CODE END 4 */ + +/* MPU Configuration */ + +void MPU_Config(void) { + MPU_Region_InitTypeDef MPU_InitStruct = {0}; + + /* Disables the MPU */ + HAL_MPU_Disable(); + + /** Initializes and configures the Region and the memory to be protected + */ + MPU_InitStruct.Enable = MPU_REGION_ENABLE; + MPU_InitStruct.Number = MPU_REGION_NUMBER0; + MPU_InitStruct.BaseAddress = 0x0; + MPU_InitStruct.Size = MPU_REGION_SIZE_4GB; + MPU_InitStruct.SubRegionDisable = 0x87; + MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; + MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS; + MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; + MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE; + MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; + MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE; + + HAL_MPU_ConfigRegion(&MPU_InitStruct); + /* Enables the MPU */ + HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT); +} + +/** + * @brief This function is executed in case of error occurrence. + * @retval None + */ +void Error_Handler(void) { + /* USER CODE BEGIN Error_Handler_Debug */ + /* User can add his own implementation to report the HAL error return state */ + __disable_irq(); + while (1) { + } + /* USER CODE END Error_Handler_Debug */ +} + +#ifdef USE_FULL_ASSERT +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t *file, uint32_t line) { + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line + number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, + line) */ + /* USER CODE END 6 */ +} +#endif /* USE_FULL_ASSERT */