遥远的星星

STM32下调试CAN通信

2017-06-14

基本流程:
1、初始化CAN模块:
启用CAN时钟
配置CAN功能寄存器(包括位定时,分频等等)
配置CAN过滤器
打开中断
2、初始化I/O口
启用GPIO时钟
打开CAN对应的GPIO引脚
配置重映射(根据实际情况)
3、定义CAN发送结构体,接收结构体
4、开始发送并准备接收总线上信号
5、检查接收邮箱收的数据是否正确

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
void    CAN_Config()
{
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1,ENABLE);
/**Configure the PA11 PA12 to CAN1*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_CAN1);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource12,GPIO_AF_CAN1);

CAN_DeInit(CAN1);
CAN_InitStructure.CAN_ABOM = DISABLE; //自动离线
CAN_InitStructure.CAN_AWUM = DISABLE; //自动唤醒
CAN_InitStructure.CAN_TTCM = DISABLE; //触发通讯模式
CAN_InitStructure.CAN_NART = ENABLE; //禁止报文自动重传
CAN_InitStructure.CAN_RFLM = DISABLE; //报文自动覆盖¨
CAN_InitStructure.CAN_TXFP = DISABLE; //优先级判定
CAN_InitStructure.CAN_Mode = CAN_Mode_Normal; //工作模式
/**configure baudrate 1M */
CAN_InitStructure.CAN_SJW = CAN_SJW_1tq;
CAN_InitStructure.CAN_BS1 = CAN_BS1_6tq;
CAN_InitStructure.CAN_BS2 = CAN_BS2_8tq;
CAN_InitStructure.CAN_Prescaler =20;
CAN_Init(CAN1, &CAN_InitStructure);

CAN_FilterInitStructure.CAN_FilterActivation = ENABLE; //启用过滤
CAN_FilterInitStructure.CAN_FilterFIFOAssignment = CAN_FilterFIFO0; //过滤邮箱0
CAN_FilterInitStructure.CAN_FilterIdHigh= 0x0000; //过滤ID
CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000; //过滤ID掩码
CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMode =CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterNumber = 0;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;
CAN_FilterInit(&CAN_FilterInitStructure);

CAN_ITConfig(CAN1,CAN_IT_FMP0,ENABLE);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
定义CAN结构体:
CanTxMsg msg;
CanRxMsg RxMsg;

msg.StdId = 0x09;
msg.IDE = CAN_Id_Standard;
msg.Data[0]=0x01;
msg.DLC=1;
发送:
`这里写代码片`
CanTx = CAN_Transmit(CAN1,&msg);
中断接收:
void CAN1_RX0_IRQHandler(void)
{
if(CAN_MessagePending(CAN1,CAN_FIFO0) != RESET)
{
CAN_ClearITPendingBit(CAN1,CAN_IT_FMP0);
CAN_Receive(CAN1,CAN_FIFO0,&RxMsg);
msg.Data[0] = RxMsg.Data[2]+1;
msg.DLC =1;
msg.StdId = 0x02;
msg.IDE = CAN_Id_Standard;
if(RxMsg.Data[0] ==0x01)
{
GPIO_ToggleBits(GPIOD,GPIO_Pin_14);
}
CAN_Transmit(CAN1,&msg);
}
}