完整配置CAN的功能``````//GPIO配置```配置CAN 的NVIC,第一优先级组,0优先级 ```static void CAN_NVIC_Config(void) { NVIC_InitTypeDef NVIC_InitStructure; /* Configure one bit for preemption priority */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); /*中断设置*/ NVIC_InitStructure.NVIC_IRQChannel = CAN_RX_IRQ; //CAN RX中断 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } ```CAN模式的配置 ```static void CAN_Mode_Config(void) { CAN_InitTypeDef CAN_InitStructure; /************************CAN通信参数设置**********************************/ /* Enable CAN clock */ RCC_APB1PeriphClockCmd(CAN_CLK, ENABLE); /*CAN 寄存器初始化*/ CAN_DeInit(CAN1); CAN_StructInit(&CAN_InitStructure); /*CANµ¥Ôª³õʼ»¯*/ CAN_InitStructure.CAN_TTCM=DISABLE; //MCR-TTCM 关闭时间触发通信使能模式 CAN_InitStructure.CAN_ABOM=ENABLE; //MCR-ABOM 使能自动离线管理 CAN_InitStructure.CAN_AWUM=ENABLE; //MCR-AWUM使能自动唤醒模式 CAN_InitStructure.CAN_NART=DISABLE; //MCR-NART 禁止报文自动重传 CAN_InitStructure.CAN_RFLM=DISABLE; //MCR-RFLM 接收FIFO 不锁定溢出时新报文会覆盖原报文 CAN_InitStructure.CAN_TXFP=DISABLE; //MCR-TXFP 发送FIFO优先级 取决于报文标识符 CAN_InitStructure.CAN_Mode = CAN_Mode_Normal; //正常工作模式 CAN_InitStructure.CAN_SJW=CAN_SJW_1tq; //BTR-SJW 重新同步跳跃宽带为 1时间单元 /* ss=1 bs1=5 bs2=3 位时间宽度为(1+5+3) 波特率即为时钟周期 tq*(1+3+5) */ CAN_InitStructure.CAN_BS1=CAN_BS1_5tq; //BTR-TS1 时间段1 占用了5个时间单元 CAN_InitStructure.CAN_BS2=CAN_BS2_3tq; //BTR-TS1 时间段2 占用了3个时间单元 /* CAN Baudrate = 1 MBps APB 1 = 45 MHz) */ CAN_InitStructure.CAN_Prescaler =10; //BTR-BRP 45/(1+5+3)/5=1 Mbps or /5 = 0.5Mbps CAN_Init(CANx, &CAN_InitStructure); } ```CAN 筛选器的配置 ```static void CAN_Filter_Config(void) { CAN_FilterInitTypeDef CAN_FilterInitStructure; /*CAN筛选器初始化*/ CAN_FilterInitStructure.CAN_FilterNumber=0; //筛选器组0 CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask; //工作在掩码模式 CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //筛选器位宽为单个32位 CAN_FilterInitStructure.CAN_FilterIdHigh= ((((u32)0x1314<<3)|CAN_ID_EXT|CAN_RTR_DATA)&0xFFFF0000)>>16; CAN_FilterInitStructure.CAN_FilterIdLow= (((u32)0x1314<<3)|CAN_ID_EXT|CAN_RTR_DATA)&0xFFFF; CAN_FilterInitStructure.CAN_FilterMaskIdHigh= 0xFFFF; CAN_FilterInitStructure.CAN_FilterMaskIdLow= 0xFFFF; CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0 ; //FIFO0 CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; CAN_FilterInit(&CAN_FilterInitStructure); CAN_ITConfig(CANx, CAN_IT_FMP0, ENABLE); } ```然后就是根据标志位来判断有没有接收到CAN数据的中断函数```void CAN_RX_IRQHandler(void) { /*从邮箱读出报文*/ CAN_Receive(CANx, CAN_FIFO0, &RxMessage); /*比较ID是否位0x1314 */ if((RxMessage.ExtId==0x1314) && (RxMessage.IDE==CAN_ID_EXT) && (RxMessage.DLC==8) ) { flag1 = 1; //接收成功 } else { flag1 = 0; //接收失败 } }``` 以上就是F103和F104的CAN驱动程序,两个不能正常通信,请大神指点。
查看更多
回到 顶部
发布 问题
分享 好友
手机 浏览
投诉 建议
回到 底部