1. 波特率
tq = 1/(PCLK1/Prescaler) = 1/(42/21) = 1/2
TS1 + 1 = (Time Quanta in Bit Segment 1) = 1
TS2 + 1 = (Time Quanta in Bit Segment 2) = 2
tbs1 = tq * (TS1 + 1) = 1/2
tbs2 = tq * (TS2 + 1) = 1
NominalBitTime = 1*tq + tbsq + tbs1 + tbs2 = 2000(ns)
BaudRate = 1/NominalBitTime = 500000(bit/s)
2. 驱动代码
/* can.c部分代码 */
void MX_CAN1_Init(void)
{
/* USER CODE BEGIN CAN1_Init 0 */
/* USER CODE END CAN1_Init 0 */
/* USER CODE BEGIN CAN1_Init 1 */
/* USER CODE END CAN1_Init 1 */
hcan1.Instance = CAN1;
hcan1.Init.Prescaler = 21;
hcan1.Init.Mode = CAN_MODE_NORMAL;
hcan1.Init.SyncJumpWidth = CAN_SJW_1TQ;
hcan1.Init.TimeSeg1 = CAN_BS1_1TQ;
hcan1.Init.TimeSeg2 = CAN_BS2_2TQ;
hcan1.Init.TimeTriggeredMode = DISABLE;
hcan1.Init.AutoBusOff = DISABLE;
hcan1.Init.AutoWakeUp = DISABLE;
hcan1.Init.AutoRetransmission = DISABLE;
hcan1.Init.ReceiveFifoLocked = DISABLE;
hcan1.Init.TransmitFifoPriority = DISABLE;
if (HAL_CAN_Init(&hcan1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CAN1_Init 2 */
/* USER CODE END CAN1_Init 2 */
}
3. 应用代码
/* stm32f4xx_hal_can.h */
/* 本次代码用到的函数 */
HAL_StatusTypeDef HAL_CAN_Start(CAN_HandleTypeDef *hcan);
HAL_StatusTypeDef HAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan, CAN_TxHeaderTypeDef *pHeader, uint8_t aData[], uint32_t *pTxMailbox);
/* 本次代码用到的结构体 */
typedef struct
{
uint32_t StdId; /*!< Specifies the standard identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */
uint32_t ExtId; /*!< Specifies the extended identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */
uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted.
This parameter can be a value of @ref CAN_identifier_type */
uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted.
This parameter can be a value of @ref CAN_remote_transmission_request */
uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted.
This parameter must be a number between Min_Data = 0 and Max_Data = 8. */
uint32_t Timestamp; /*!< Specifies the timestamp counter value captured on start of frame reception.
@note: Time Triggered Communication Mode must be enabled.
This parameter must be a number between Min_Data = 0 and Max_Data = 0xFFFF. */
uint32_t FilterMatchIndex; /*!< Specifies the index of matching acceptance filter element.
This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */
} CAN_RxHeaderTypeDef;
HAL_CAN_Start(&hcan1);
void can_test(void)
{
uint8_t tx_data[8] = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88};
uint32_t tx_mailbox;
CAN_TxHeaderTypeDef can_tx;
can_tx.StdId = 0x78;//ID
can_tx.RTR = CAN_RTR_DATA;//数据帧
can_tx.IDE = CAN_ID_STD;//标准格式
can_tx.DLC = 0x08;//数据长度
while (HAL_CAN_GetTxMailboxesFreeLevel(&hcan1) < 1);
if (HAL_CAN_AddTxMessage(&hcan1, &can_tx, tx_data, &tx_mailbox) != HAL_OK);
}
5. 测试
身边没有板子,待测试验证。