STM32的CAN匯流排初始化

weixin_41719055發表於2018-04-03
void CAN_Configuration(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;   
  CAN_InitTypeDef        CAN_InitStructure;
  CAN_FilterInitTypeDef  CAN_FilterInitStructure;
  /* CAN register init */
 // CAN_DeInit();
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN, ENABLE);//剛開始漏掉這句,一直無法進入初始化模式
  RCC_APB2PeriphClockCmd( RCC_APB2Periph_AFIO, ENABLE ); //¸´Î»CAN1µÄËùÓмĴæÆ÷
 // RCC_APB1PeriphResetCmd(RCC_APB1Periph_CAN, ENABLE);
 // CAN_StructInit(&CAN_InitStructure);  //½«¼Ä´æÆ÷È«²¿ÉèÖóÉĬÈÏÖµ
  /*ÅäÖÃCAN¶Ë¿ÚCAN pin: RX*/
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;   //IO¶Ë¿ÚµÄµÚ8λ
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode =GPIO_Mode_IPU;// GPIO_Mode_IN_FLOATING;   //¶Ë¿ÚģʽΪÉÏÀ­ÊäÈ뷽ʽ
  GPIO_Init(GPIOB, &GPIO_InitStructure);
   /* Configure CAN pin: TX */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;   //IO¶Ë¿ÚµÄµÚ9λ
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;   //¶Ë¿ÚģʽΪ¸´ÓÃÍÆÀ­Êä³ö·½Ê½
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  GPIO_PinRemapConfig(GPIO_Remap1_CAN , ENABLE);           //Öض¨ÒåCAN1µ½PB¿Ú
  /* CAN cell init */
  CAN_InitStructure.CAN_TTCM=DISABLE;  //½ûֹʱ¼ä´¥·¢Í¨ÐÅ·½Ê½
  CAN_InitStructure.CAN_ABOM=DISABLE;  //½ûÖ¹CAN×ÜÏß×Ô¶¯¹Ø±Õ¹ÜÀí
  CAN_InitStructure.CAN_AWUM=DISABLE;  //½ûÖ¹×Ô¶¯»½ÐÑģʽ
  CAN_InitStructure.CAN_NART=ENABLE;  //½ûÖ¹·Ç×Ô¶¯ÖØ´«Ä£Ê½
  CAN_InitStructure.CAN_RFLM=DISABLE;  //½ûÖ¹½ÓÊÕFIFOËø¶¨
  CAN_InitStructure.CAN_TXFP=DISABLE;//ENABLE;  //½ûÖ¹·¢ËÍFIFOÓÅÏȼ¶
  CAN_InitStructure.CAN_Mode=CAN_Mode_Normal;//CAN_Mode_LoopBack;//CAN_Mode_Normal;           //ÉèÖÃCAN¹¤×÷·½Ê½ÎªÕý³£ÊÕ·¢Ä£Ê½
  /* CAN ²¨ÌØÂÊ */
  CAN_InitStructure.CAN_SJW=CAN_SJW_1tq;  //ÉèÖÃÖØÐÂͬ²½ÌøתµÄʱ¼äÁ¿×Ó
  CAN_InitStructure.CAN_BS1=CAN_BS1_9tq;  //ÉèÖÃ×Ö¶Î1µÄʱ¼äÁ¿×ÓÊý
  CAN_InitStructure.CAN_BS2=CAN_BS2_8tq;  //ÉèÖÃ×Ö¶Î2µÄʱ¼äÁ¿×ÓÊý
  CAN_InitStructure.CAN_Prescaler=20;  //·ÖƵϵÊý µÍ²¨ÌØÂÊÔ¶¾àÀë´«Êä¸üÎȶ¨£¬Èç¹û¾àÀë¶Ì¿ÉÒÔµ÷СÕâ¸öÖµ
  CAN_Init(&CAN_InitStructure);          //ÓÃÒÔÉϲÎÊý³õʼ»¯CAN1¶Ë¿Ú


  /* CAN filter init */
  CAN_FilterInitStructure.CAN_FilterNumber=0;   //Ñ¡ÔñCAN¹ýÂËÆ÷0
  CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;   //³õʼ»¯Îª±êʶ/ÆÁ±Îģʽ
  CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;   //Ñ¡Ôñ¹ýÂËÆ÷Ϊ32λ
  CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;   //¹ýÂËÆ÷±êʶºÅ¸ß16λ
  CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;   //¹ýÂËÆ÷±êʶºÅµÍ16λ
  //ÏÂÃæÈ«0£¬Ã»¹ýÂËÈκαêʶºÅ
  CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;   //¸ù¾ÝģʽѡÔñ¹ýÂËÆ÷±êʶºÅ»òÆÁ±ÎºÅµÄ¸ß16λ
  CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;   //¸ù¾ÝģʽѡÔñ¹ýÂËÆ÷±êʶºÅ»òÆÁ±ÎºÅµÄµÍ16λ
  CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_FIFO0;   //½«FIFO 0·ÖÅä¸ø¹ýÂËÆ÷0
  CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;   //ʹÄܹýÂËÆ÷
  CAN_FilterInit(&CAN_FilterInitStructure);
 
 /* CAN FIFO0 ½ÓÊÕÖжÏʹÄÜ */ 
 // CAN_ITConfig(CAN_IT_FMP0, ENABLE);

}

折騰了一天一直無法弄出來,是在以前程式上加個CAN功能,時鐘使能在void RCC_Configuration(void)定義的,新增CAN忘了定義CAN時鐘,弄一天都要開始懷疑人生了!!!!

相關文章