STM32 CAN通信

CAN通信

两线制:

CANH:
CANL:

配置方式

配置通信速率

STM32 CAN通信_第1张图片

首先根据CAN外设总线时钟配置分频系数CAN_Prescaler,再根据CAN_BS1_4tq和CAN_BS2_4tq来计算出CAN总线的数据传输速率。
简单的公式计算方式就是CAN总线传输速率=(1+CAN_BS1_xtq+CAN_BS2_xtq)/CAN_Prescaler

配置CAN ID和掩码方式

CAN ID可以配置为32位标识符模式,32位掩码模式,16位标识符模式,16位掩码模式。
32位标识符模式:2个筛选ID
32位掩码模式:1组筛选ID
16位标识符模式:4个筛选ID
16位掩码模式:2组筛选ID

帧类别

数据帧:用于发送数据
遥控帧:用于请求数据
错误帧:发送出错消息

配置代码

void CAN1_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    CAN_InitTypeDef CAN_InitStruct;
    CAN_FilterInitTypeDef CAN_FilterInitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    //初始化GPIO PB8(CANRX) PB9(CANTX)
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE);
  
    //配置GPIO
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_PinRemapConfig(GPIO_Remap1_CAN1, ENABLE);
  
    //初始化CAN:设置波特率1Mbps
    //APB1时钟32M,预分频4,CAN时钟8M
    CAN_InitStruct.CAN_Prescaler = 4;
    CAN_InitStruct.CAN_Mode = CAN_Mode_Normal;
    CAN_InitStruct.CAN_SJW = CAN_SJW_2tq;
    CAN_InitStruct.CAN_BS1 = CAN_BS1_4tq;
    CAN_InitStruct.CAN_BS2 = CAN_BS2_3tq;
    //时间触发通信模式
    CAN_InitStruct.CAN_TTCM = DISABLE;
    //自动的总线关闭管理
    CAN_InitStruct.CAN_ABOM = ENABLE;
    //自动唤醒模式
    CAN_InitStruct.CAN_AWUM = ENABLE;
    //禁止自动重发送:消息只发送一次
    CAN_InitStruct.CAN_NART = ENABLE;
    //接收 FIFO 锁定模式:认定下一次消息比FIFO中的消息重要
    CAN_InitStruct.CAN_RFLM = DISABLE;
    //发送 FIFO 优先级:优先级由标识符确定
    CAN_InitStruct.CAN_TXFP = DISABLE;
    CAN_Init(CAN1, &CAN_InitStruct);

    //初始化筛选器
    CAN_FilterInitStruct.CAN_FilterNumber = 0;
    CAN_FilterInitStruct.CAN_FilterScale = CAN_FilterScale_32bit;
    CAN_FilterInitStruct.CAN_FilterMode = CAN_FilterMode_IdMask;
    //32位掩码标准ID模式:筛选器只筛选接收标准ID为0x1的报文
    CAN_FilterInitStruct.CAN_FilterIdHigh = (((u32)0X01<<21|CAN_Id_Standard|CAN_RTR_Data)&0xFFFF0000)>>16;//筛选ID
    CAN_FilterInitStruct.CAN_FilterIdLow = ((u32)0X01<<21|CAN_Id_Standard|CAN_RTR_Data)&0x0000FFFF;//筛选ID
    //(想要发送远程帧 修改对应掩码位为0)
    CAN_FilterInitStruct.CAN_FilterMaskIdHigh = 0xFFE0;//掩码
    CAN_FilterInitStruct.CAN_FilterMaskIdLow = 0X6;//掩码
    CAN_FilterInitStruct.CAN_FilterFIFOAssignment = CAN_Filter_FIFO0;
    CAN_FilterInitStruct.CAN_FilterActivation = ENABLE;
    CAN_FilterInit(&CAN_FilterInitStruct);

    //使能中断
    CAN_ITConfig(CAN1, CAN_IT_FMP0, ENABLE);

    //中断优先级
    NVIC_InitStruct.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

你可能感兴趣的:(M核单片机,stm32)