CAN接口:
PI9
PB9
1.配置CAN 通信参数
由于F4的 CAN外设挂载在APB1上,时钟配置后APB1的时钟速率为42MHz,目标通信速率为1000KHz,由公式:
BaudRate = 1/NominalBitTime
NominalBitTime = 1tq + tBS1 +tBS2
设置参数如下:
CAN时钟分频参数为7,BS1为4,BS2为1,CAN模式为Nomal模式。
生成工程
在can.c中添加如下函数
CAN_TxHeaderTypeDef TXHeader;
CAN_RxHeaderTypeDef RXHeader;
uint8_t TXmessage[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
uint8_t RXmessage[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
uint32_t pTxMailbox = 0;
uint32_t CAN_ID = 0x01;
int counT_A = 0;
int counT_B = 0;
void CAN_Config(void)
{
CAN_FilterTypeDef sFilterConfig;
/*配置CAN过滤器*/
sFilterConfig.FilterBank = 0; //过滤器0
sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;
sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;
sFilterConfig.FilterIdHigh = 0x0000; //32位ID
sFilterConfig.FilterIdLow = 0x0000;
sFilterConfig.FilterMaskIdHigh = 0x0000; //32位MASK
sFilterConfig.FilterMaskIdLow = 0x0000;
sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0;//过滤器0关联到FIFO0
sFilterConfig.FilterActivation = ENABLE; //激活滤波器0
sFilterConfig.SlaveStartFilterBank = 14;
if(HAL_CAN_ConfigFilter(&hcan1,&sFilterConfig) != HAL_OK)//初始化过滤器
{
Error_Handler();
}
if(HAL_CAN_Start(&hcan1) != HAL_OK)//打开can
{
Error_Handler();
}
if(HAL_CAN_ActivateNotification(&hcan1,CAN_IT_RX_FIFO0_MSG_PENDING) != HAL_OK)//开启接受邮邮箱0挂起中断
{
Error_Handler();
}
/*配置传输过程*/
TXHeader.StdId = 0x321;
TXHeader.ExtId = 0x01;
TXHeader.RTR = CAN_RTR_DATA;
TXHeader.IDE = CAN_ID_STD;
TXHeader.DLC = 2;
TXHeader.TransmitGlobalTime = DISABLE;
}
//发送函数
void CAN_senddata(CAN_HandleTypeDef *hcan,uint32_t can_id)
{
TXHeader.StdId=can_id ;
TXHeader.ExtId=0x12345000;//0x12345000
TXHeader.DLC=8;
TXHeader.IDE=CAN_ID_EXT;
TXHeader.RTR=CAN_RTR_DATA;
TXHeader.TransmitGlobalTime = DISABLE;
HAL_CAN_AddTxMessage(hcan,&TXHeader,TXmessage,&pTxMailbox);
}
//接受函数
uint32_t CAN1_Receive_Msg(uint8_t *buf)
{
uint32_t i;
uint8_t RxData[8];
if(HAL_CAN_GetRxFifoFillLevel(&hcan1, CAN_RX_FIFO0) != 1)//没有接收到数据,直接退出
{
return 0xF1;
}
if(HAL_CAN_GetRxMessage(&hcan1, CAN_RX_FIFO0, &RXHeader, RxData) != HAL_OK)
{
return 0xF2;
}
for(i=0;i<RXHeader.DLC;i++)
buf[i]=RxData[i];
return RXHeader.DLC;
}
头文件声明
void CAN_Config(void);
extern uint8_t TXmessage[8];
extern uint8_t RXmessage[8];
extern uint32_t CAN_ID;
extern int counT_A;
extern int counT_B;
void CAN_senddata(CAN_HandleTypeDef *hcan,uint32_t can_id);
uint32_t CAN1_Receive_Msg(uint8_t *buf);
主函数添加
循环中设置1ms的发送周期
用CAN分析仪接受
文章来源:https://www.toymoban.com/news/detail-680018.html
完美文章来源地址https://www.toymoban.com/news/detail-680018.html
到了这里,关于野火STM32电机系列(三)Cubemx配置CAN通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!