STM32F3—CAN通信自发自收
扫描二维码
随时随地手机看文章
CAN通信是STM32中比较复杂的东西之一,它的初始化主要分为两个部分,一个是CAN的初始化,一个是过滤器的初始化。自发自收只需要一个器件,CAN的模式选择回环(Loopback)模式,这种模式下发出的数据也会被CAN本身接收回来,只需要检查接收到的数据和发送的数据是否一样,就能测试发送是否成功。
代码:
void CAN_Config(void)
{
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1,ENABLE);
CAN_DeInit(CAN1);
CAN_StructInit(&CAN_InitStructure);
CAN_InitStructure.CAN_TTCM = DISABLE;
CAN_InitStructure.CAN_ABOM = DISABLE;
CAN_InitStructure.CAN_AWUM = DISABLE;
CAN_InitStructure.CAN_NART = DISABLE;
CAN_InitStructure.CAN_RFLM = DISABLE;
CAN_InitStructure.CAN_TXFP = DISABLE;
CAN_InitStructure.CAN_Mode=CAN_Mode_LoopBack;//回环模式
CAN_InitStructure.CAN_SJW=CAN_SJW_1tq;//1
CAN_InitStructure.CAN_BS1=CAN_BS1_9tq;//9
CAN_InitStructure.CAN_BS2=CAN_BS2_8tq;//8
CAN_InitStructure.CAN_Prescaler=16;//16分频
CAN_Init(CAN1,&CAN_InitStructure);
CAN_FilterInitStructure.CAN_FilterNumber=0;
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;//屏蔽模式
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment = CAN_FilterFIFO0;
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
}
配置完成,开始发送和接收:
void CAN_Test(void)
{
CanTxMsg TXmessage;
CanRxMsg RXmessage;
uint8_t TxMailbox=0;
uint8_t ret=0;
CAN_Config();
TXmessage.StdId=0x123;//ID,标识符
TXmessage.IDE=CAN_ID_STD;//标准ID
TXmessage.RTR=CAN_RTR_DATA;//传送的是数据帧
TXmessage.DLC=3;//数据个数。不能超过8个
TXmessage.Data[0]=0x01;//传送的数据
TXmessage.Data[1]=0x10;
TXmessage.Data[2]=0xFF;
TxMailbox=CAN_Transmit(CAN1,&TXmessage);//发送,返回的是当前邮箱号
while(CAN_TransmitStatus(CAN1,TxMailbox) !=CANTXOK);//等待发送完成
while(CAN_MessagePending(CAN1,CAN_FIFO0)<1);//查询接受状态位,看是否有信息(报文)到达
RXmessage.StdId=0x00;//初始化接受结构体
RXmessage.IDE=CAN_ID_STD;
RXmessage.DLC=0;
RXmessage.Data[0]=0;
RXmessage.Data[1]=0;
RXmessage.Data[2]=0;
CAN_Receive(CAN1,CAN_FIFO0,&RXmessage);//接收信息(报文)
//最后检查所接收到的数据每一个项和发送的是否一样,如果全部一样则发送成功,否则发送失败
//设置标志位对结果进行保存,用串口打印或者LED显示不同的状态来表示发送接收情况
}