STM32CubeMX生成基于HAL库的Can收发配置

HAL库 的应该用比较新潮,经常找不到资料。今天说说,在CAN开发中的应用。

一,发送。

static HAL_StatusTypeDef Can_MsgSend(uint32_t ID,uint8_t * pData,uint8_t len)
{
HAL_StatusTypeDef retSTD;
canTxMsg.StdId=ID;//0x500|(GetLocalID()&0xFF);
canTxMsg.IDE=CAN_ID_STD;
canTxMsg.RTR=CAN_RTR_DATA;
canTxMsg.DLC=len;
memcpy(canTxMsg.Data,pData,len);
SendErrorCount=0;

retSTD= HAL_CAN_Transmit(&hcan,200);
//retSTD= HAL_CAN_Transmit_IT(&hcan);
 
return retSTD;  

}


二,配置。

//基本配置

hcan.Instance = CAN;
  hcan.Init.Prescaler =138;// 100;
  hcan.Init.Mode =CAN_MODE_NORMAL;//CAN_MODE_LOOPBACK;// 
  hcan.Init.SJW = CAN_SJW_1TQ;
  hcan.Init.BS1 = CAN_BS1_7TQ;
  hcan.Init.BS2 = CAN_BS2_8TQ;
  hcan.Init.TTCM = DISABLE;
  hcan.Init.ABOM = DISABLE;
  hcan.Init.AWUM = DISABLE;
  hcan.Init.NART = DISABLE;
  hcan.Init.RFLM = DISABLE;
  hcan.Init.TXFP = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }


//过滤器  

CAN_FilterConfTypeDefftcan;
ftcan.FilterIdHigh=0x0000;
ftcan.FilterIdLow=0x0000;
ftcan.FilterScale=CAN_FILTERSCALE_16BIT;
ftcan.FilterMaskIdHigh=0xFFFF;
ftcan.FilterMaskIdLow=0x0000;
ftcan.FilterMode=CAN_FILTERMODE_IDMASK;
 ftcan.FilterFIFOAssignment=CAN_USEFIFO;
ftcan.FilterNumber=0;
ftcan.FilterActivation=ENABLE;


HAL_CAN_ConfigFilter(&hcan, &ftcan);

//收发 缓冲

 hcan.pRxMsg=&canRxMsg; 
hcan.pTxMsg=&canTxMsg;  


三,回调函数

void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan);
void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan);
void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan);


四,设置中断接收.

HAL_CAN_Receive_IT(&hcan,CAN_USEFIFO); 每次接收中断中,要重新设置。

你可能感兴趣的:(STM32,HAL,CAN)