1. 程式人生 > >STM32下調試CAN通信

STM32下調試CAN通信

mas 結構 bits source ant pen eset disable sca

基本流程:
1、初始化CAN模塊:

啟用CAN時鐘

配置CAN功能寄存器(包括位定時,分頻等等)

配置CAN過濾器

打開中斷

2、初始化I/O口

啟用GPIO時鐘

打開CAN對應的GPIO引腳

配置重映射(根據實際情況)

3、定義CAN發送結構體,接收結構體

4、開始發送並準備接收總線上信號

5、檢查接收郵箱收的數據是否正確

 1 void    CAN_Config()
 2 {
 3     CAN_InitTypeDef         CAN_InitStructure;
 4     CAN_FilterInitTypeDef     CAN_FilterInitStructure;
5 GPIO_InitTypeDef GPIO_InitStructure; 6 RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1,ENABLE); 7 /**Configure the PA11 PA12 to CAN1*/ 8 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12; 9 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; 10 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
11 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; 12 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 13 GPIO_Init(GPIOA,&GPIO_InitStructure); 14 GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_CAN1); 15 GPIO_PinAFConfig(GPIOA,GPIO_PinSource12,GPIO_AF_CAN1); 16 17 CAN_DeInit(CAN1);
18 CAN_InitStructure.CAN_ABOM = DISABLE; //自動離線 19 CAN_InitStructure.CAN_AWUM = DISABLE; //自動喚醒 20 CAN_InitStructure.CAN_TTCM = DISABLE; //觸發通訊模式 21 CAN_InitStructure.CAN_NART = ENABLE; //禁止報文自動重傳 22 CAN_InitStructure.CAN_RFLM = DISABLE; //報文自動覆蓋¨ 23 CAN_InitStructure.CAN_TXFP = DISABLE; //優先級判定 24 CAN_InitStructure.CAN_Mode = CAN_Mode_Normal; //工作模式 25 /**configure baudrate 1M */ 26 CAN_InitStructure.CAN_SJW = CAN_SJW_1tq; 27 CAN_InitStructure.CAN_BS1 = CAN_BS1_6tq; 28 CAN_InitStructure.CAN_BS2 = CAN_BS2_8tq; 29 CAN_InitStructure.CAN_Prescaler =20; 30 CAN_Init(CAN1, &CAN_InitStructure); 31 32 CAN_FilterInitStructure.CAN_FilterActivation = ENABLE; //啟用過濾 33 CAN_FilterInitStructure.CAN_FilterFIFOAssignment = CAN_FilterFIFO0; //過濾郵箱0 34 CAN_FilterInitStructure.CAN_FilterIdHigh= 0x0000; //過濾ID 35 CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000; 36 CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000; //過濾ID掩碼 37 CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000; 38 CAN_FilterInitStructure.CAN_FilterMode =CAN_FilterMode_IdMask; 39 CAN_FilterInitStructure.CAN_FilterNumber = 0; 40 CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit; 41 CAN_FilterInit(&CAN_FilterInitStructure); 42 43 CAN_ITConfig(CAN1,CAN_IT_FMP0,ENABLE); 44 }

定義CAN結構體:

1 CanTxMsg msg;
2 CanRxMsg RxMsg;
3 
4     msg.StdId = 0x09;
5     msg.IDE = CAN_Id_Standard;
6 msg.Data[0]=0x01;
7     msg.DLC=1;
 1 void CAN1_RX0_IRQHandler(void)
 2 {
 3       if(CAN_MessagePending(CAN1,CAN_FIFO0) != RESET)
 4         {
 5             CAN_ClearITPendingBit(CAN1,CAN_IT_FMP0);
 6             CAN_Receive(CAN1,CAN_FIFO0,&RxMsg);
 7           msg.Data[0] = RxMsg.Data[2]+1;
 8             msg.DLC =1;
 9             msg.StdId = 0x02;
10             msg.IDE = CAN_Id_Standard;
11             if(RxMsg.Data[0] ==0x01)
12             {
13                 GPIO_ToggleBits(GPIOD,GPIO_Pin_14);
14             }
15             CAN_Transmit(CAN1,&msg);
16         }
17 }

經過實驗,在通信波特率為20K下可以正常工作。建議在低速下測試,若通信正常,可以逐步提高通信速率。

STM32下調試CAN通信