STM32G474 FDCAN 发送与中断接收代码示例
时间: 2023-08-03 16:31:53 浏览: 200
STM32 CAN总线双机通讯程序示例(中断接收)
4星 · 用户满意度95%
以下是一个简单的示例代码,演示STM32G474 FDCAN的发送和中断接收功能:
```
// 配置FDCAN
void FDCAN_Configuration(void) {
FDCAN_FilterTypeDef sFilterConfig;
// 使能时钟
__HAL_RCC_FDCAN_CLK_ENABLE();
// 配置FDCAN控制器
hfdcan.Instance = FDCAN1;
hfdcan.Init.ClockDivider = FDCAN_CLOCK_DIV1;
hfdcan.Init.FrameFormat = FDCAN_FRAME_CLASSIC;
hfdcan.Init.Mode = FDCAN_MODE_NORMAL;
hfdcan.Init.AutoRetransmission = ENABLE;
hfdcan.Init.TransmitPause = DISABLE;
hfdcan.Init.ProtocolException = DISABLE;
hfdcan.Init.NominalPrescaler = 1;
hfdcan.Init.NominalSyncJumpWidth = 1;
hfdcan.Init.NominalTimeSeg1 = 6;
hfdcan.Init.NominalTimeSeg2 = 3;
hfdcan.Init.DataPrescaler = 1;
hfdcan.Init.DataSyncJumpWidth = 1;
hfdcan.Init.DataTimeSeg1 = 6;
hfdcan.Init.DataTimeSeg2 = 3;
hfdcan.Init.StdFiltersNbr = 1;
hfdcan.Init.ExtFiltersNbr = 0;
hfdcan.Init.TxFifoQueueMode = FDCAN_TX_FIFO_OPERATION;
hfdcan.Init.TxFifoQueueSize = 3;
hfdcan.Init.RxFifo0QueueSize = 2;
hfdcan.Init.RxFifo0Overrun = FDCAN_RX_FIFO0_OVERWRITE;
hfdcan.Init.RxFifo1QueueSize = 2;
hfdcan.Init.RxFifo1Overrun = FDCAN_RX_FIFO1_OVERWRITE;
hfdcan.Init.RxBufferNbr = 0;
hfdcan.Init.TxEventFifoQueueSize = 0;
// 初始化FDCAN控制器
if (HAL_FDCAN_Init(&hfdcan) != HAL_OK)
{
Error_Handler();
}
// 配置FDCAN过滤器
sFilterConfig.IdType = FDCAN_STANDARD_ID;
sFilterConfig.FilterIndex = 0;
sFilterConfig.FilterType = FDCAN_FILTER_MASK;
sFilterConfig.FilterConfig = FDCAN_FILTER_TO_RXFIFO0;
sFilterConfig.FilterID1 = 0x7FF;
sFilterConfig.FilterID2 = 0x7FF;
if (HAL_FDCAN_ConfigFilter(&hfdcan, &sFilterConfig) != HAL_OK)
{
Error_Handler();
}
// 配置FDCAN中断
HAL_NVIC_SetPriority(FDCAN1_IT0_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(FDCAN1_IT0_IRQn);
}
// FDCAN中断处理函数
void FDCAN1_IT0_IRQHandler(void) {
HAL_FDCAN_IRQHandler(&hfdcan);
}
// FDCAN发送数据
void FDCAN_SendData(uint32_t id, uint8_t* data, uint32_t len) {
FDCAN_TxHeaderTypeDef TxHeader;
uint32_t TxMailbox;
// 配置FDCAN消息头
TxHeader.Identifier = id;
TxHeader.IdType = FDCAN_STANDARD_ID;
TxHeader.TxFrameType = FDCAN_DATA_FRAME;
TxHeader.DataLength = len;
TxHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE;
TxHeader.BitRateSwitch = FDCAN_BRS_OFF;
TxHeader.FDFormat = FDCAN_CLASSIC_CAN;
TxHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS;
TxHeader.MessageMarker = 0;
// 发送数据
if (HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan, &TxHeader, data, &TxMailbox) != HAL_OK)
{
Error_Handler();
}
}
// FDCAN中断接收数据
void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs) {
FDCAN_RxHeaderTypeDef RxHeader;
uint8_t data[8];
// 获取接收到的数据
if (HAL_FDCAN_GetRxMessage(hfdcan, FDCAN_RX_FIFO0, &RxHeader, data) != HAL_OK)
{
Error_Handler();
}
// 处理接收到的数据
// ...
}
```
在主函数中,需要先调用FDCAN_Configuration()函数来配置FDCAN控制器和中断。然后可以使用FDCAN_SendData()函数来发送数据,使用HAL_FDCAN_RxFifo0Callback()函数来接收数据。在接收到数据后,可以在回调函数中处理接收到的数据。
阅读全文