说明
本次移植CAN驱动程序。
开发板MCU有两路CAN接口,本次选择其中一路来进行移植。
驱动移植
1、初始化
CAN驱动的初始化主要涉及到三部分内容:
- 对can初始化结构体的配置
- 接收过滤器配置
- NVIC中断配置
初始化结构体的配置主要配置操作模式,波特率,时钟分频等参数。波特率包含对同步跳转宽度和TBS1 和TBS2 的配置,详细如下:
CAN_InitType CAN_InitStructure;
RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_CAN1, ENABLE);
CAN_DeInit(CAN1);
CAN_InitStruct(&CAN_InitStructure);
CAN_InitStructure.TTCM = DISABLE;
CAN_InitStructure.ABOM = DISABLE;
CAN_InitStructure.AWKUM = DISABLE;
CAN_InitStructure.NART = DISABLE;
CAN_InitStructure.RFLM = DISABLE;
CAN_InitStructure.TXFP = ENABLE;
CAN_InitStructure.OperatingMode = OPERATINGMODE;
CAN_InitStructure.RSJW = CAN_BIT_RSJW;
CAN_InitStructure.TBS1 = CAN_BIT_BS1;
CAN_InitStructure.TBS2 = CAN_BIT_BS2;
CAN_InitStructure.BaudRatePrescaler = CAN_BAUDRATEPRESCALER;
CAN_Init(CAN1, &CAN_InitStructure);
接收过滤器配置,主要配置需要接收的ID号,过滤模式支持列表模式和,位屏蔽模式两种。另外就是对消息发送和接收的中断进行使能。
CAN_FilterInitType CAN_FilterInitStructure;
CAN_FilterInitStructure.Filter_Num = CAN_FILTERNUM0;
CAN_FilterInitStructure.Filter_Mode = CAN_Filter_IdMaskMode;
CAN_FilterInitStructure.Filter_Scale = CAN_Filter_32bitScale;
CAN_FilterInitStructure.Filter_HighId = CAN_FILTER_STDID(0x400);
CAN_FilterInitStructure.Filter_LowId = CAN_FILTER_STDID(0x400);
CAN_FilterInitStructure.FilterMask_HighId = CAN_STD_ID_H_MASK_DONT_CARE;
CAN_FilterInitStructure.FilterMask_LowId = CAN_STD_ID_L_MASK_DONT_CARE;
CAN_FilterInitStructure.Filter_FIFOAssignment = CAN_FIFO0;
CAN_FilterInitStructure.Filter_Act = ENABLE;
CAN1_InitFilter(&CAN_FilterInitStructure);
CAN_INTConfig(CAN1, CAN_INT_FMP0, ENABLE);
NVIC配置can中断的优先级:
NVIC_InitType NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
初始化完成后,就可以调用库函数就行数据的发送和接收了:
CANTxMessage 用于发送can消息
CAN_ReceiveMessage 用于读取can消息
收发测试
本测试程序中,每秒发送一帧can数据,同时通过中断的方式接收can消息,并通过uart打印出收到的can帧。
测试如下:
can收发驱动移植成功。
|