STM32F3—CAN通信自發(fā)自收
CAN通信是STM32中比較復(fù)雜的東西之一,它的初始化主要分為兩個(gè)部分,一個(gè)是CAN的初始化,一個(gè)是過(guò)濾器的初始化。自發(fā)自收只需要一個(gè)器件,CAN的模式選擇回環(huán)(Loopback)模式,這種模式下發(fā)出的數(shù)據(jù)也會(huì)被CAN本身接收回來(lái),只需要檢查接收到的數(shù)據(jù)和發(fā)送的數(shù)據(jù)是否一樣,就能測(cè)試發(fā)送是否成功。
代碼:
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;//回環(huán)模式
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);
}
配置完成,開(kāi)始發(fā)送和接收:
void CAN_Test(void)
{
CanTxMsg TXmessage;
CanRxMsg RXmessage;
uint8_t TxMailbox=0;
uint8_t ret=0;
CAN_Config();
TXmessage.StdId=0x123;//ID,標(biāo)識(shí)符
TXmessage.IDE=CAN_ID_STD;//標(biāo)準(zhǔn)ID
TXmessage.RTR=CAN_RTR_DATA;//傳送的是數(shù)據(jù)幀
TXmessage.DLC=3;//數(shù)據(jù)個(gè)數(shù)。不能超過(guò)8個(gè)
TXmessage.Data[0]=0x01;//傳送的數(shù)據(jù)
TXmessage.Data[1]=0x10;
TXmessage.Data[2]=0xFF;
TxMailbox=CAN_Transmit(CAN1,&TXmessage);//發(fā)送,返回的是當(dāng)前郵箱號(hào)
while(CAN_TransmitStatus(CAN1,TxMailbox) !=CANTXOK);//等待發(fā)送完成
while(CAN_MessagePending(CAN1,CAN_FIFO0)<1);//查詢(xún)接受狀態(tài)位,看是否有信息(報(bào)文)到達(dá)
RXmessage.StdId=0x00;//初始化接受結(jié)構(gòu)體
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);//接收信息(報(bào)文)
//最后檢查所接收到的數(shù)據(jù)每一個(gè)項(xiàng)和發(fā)送的是否一樣,如果全部一樣則發(fā)送成功,否則發(fā)送失敗
//設(shè)置標(biāo)志位對(duì)結(jié)果進(jìn)行保存,用串口打印或者LED顯示不同的狀態(tài)來(lái)表示發(fā)送接收情況
}