国民技术
直播中

xiaopeng

11年用户 223经验值
擅长:嵌入式技术,处理器/DSP
私信 关注
[经验]

【国民技术N32项目移植】CAN数据收发

说明

本次移植CAN驱动程序。
开发板MCU有两路CAN接口,本次选择其中一路来进行移植。

驱动移植

1、初始化

CAN驱动的初始化主要涉及到三部分内容:

  • 对can初始化结构体的配置
  • 接收过滤器配置
  • NVIC中断配置

初始化结构体的配置主要配置操作模式,波特率,时钟分频等参数。波特率包含对同步跳转宽度和TBS1TBS2的配置,详细如下:

CAN_InitType CAN_InitStructure;
    /* Configure CAN */
    RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_CAN1, ENABLE);
    /* CAN register init */
    CAN_DeInit(CAN1);
    /* Struct init*/
    CAN_InitStruct(&CAN_InitStructure);
    /* CAN cell init */
    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;
    /*Initializes the CAN */
    CAN_Init(CAN1, &CAN_InitStructure);

接收过滤器配置,主要配置需要接收的ID号,过滤模式支持列表模式和,位屏蔽模式两种。另外就是对消息发送和接收的中断进行使能。

CAN_FilterInitType CAN_FilterInitStructure;
    /* CAN filter init */
    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;
    /* Configure the NVIC Preemption Priority Bits */
    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帧。

测试如下:

图片.png

can收发驱动移植成功。

更多回帖

发帖
×
20
完善资料,
赚取积分