sick_dt35/User/device/can.c
2025-04-02 21:42:58 +08:00

47 lines
1.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "can.h"
#include "device/can.h"
#include "stm32f3xx_hal.h"
// CAN 调试结构体实例
// 初始化 CAN
void CAN_Init(CAN_HandleTypeDef *hcan_Cur)
{ //重置CAN
HAL_CAN_Init(hcan_Cur); // 初始化CAN
// 仅初始化CAN不配置接收过滤器
HAL_CAN_Start(hcan_Cur); // 开启CAN
}
// CAN 发送函数,添加超时机制
uint8_t CAN_SendData(CAN_HandleTypeDef *hcan_Cur, uint8_t *pData, uint16_t ID)
{
HAL_StatusTypeDef HAL_RetVal = HAL_ERROR;
uint8_t FreeTxNum = 0;
CAN_TxHeaderTypeDef TxMessage;
TxMessage.StdId = ID;
TxMessage.DLC = 8; /* 默认一帧传输长度为8 */
TxMessage.IDE = CAN_ID_STD;
TxMessage.RTR = CAN_RTR_DATA;
uint32_t timeout = 5000; // 增加超时时间
while (FreeTxNum == 0 && timeout > 0)
{
FreeTxNum = HAL_CAN_GetTxMailboxesFreeLevel(hcan_Cur);
if (FreeTxNum > 0) break; // 如果有空闲邮箱,退出循环
osDelay(1); // 避免忙等待
timeout--;
}
if (timeout == 0)
{
return 1; // 超时,发送失败
}
HAL_RetVal = HAL_CAN_AddTxMessage(hcan_Cur, &TxMessage, pData, (uint32_t *)CAN_TX_MAILBOX1);
if (HAL_RetVal != HAL_OK)
{
return 1; // 发送失败
}
return 0; // 发送成功
}