一、背景
利用EB进行CAN端口配置,主要实现在KIT_A2G_TC397_5V_TFT上实现CAN通信功能。本文主要使用的是EB23,MCAL1.0.0版本进行开发。
由KIT_A2G_TC397_5V_TFT开发原理图可知,CAN00位于RXD P20.7和TXD P20.8
二、配置
1、添加模块
向工程中添加ResourceM、Port、MCU、McalLib、Irq、Dio、Can_17_McmCan等模块
2、MCU配置
在MCU模块中主要配置CAN的时钟,打开MCU中的McuClockSettingConfig选项卡,选择McuMCanClockSourceSelection 为MCAN_CLOCK_SOURCE_MCANI_SEL1,McuMCanFrequency (dynamic range) 为2.0E7
3、Port配置
在Port模块中主要配置CAN的端口,开发板上使用的CAN00位于RXD P20.7和TXD P20.8
打开Port中PortContainer选项卡,找到PortContainer_9
继续打开PortPin,找到PortPin_6为TXD,
设置PortPinDirection 为PORT_PIN_OUT,设置PortPinInitialMode 为ALT5
继续打开PortPin,找到PortPin_5为RXD,
设置PortPinDirection 为PORT_PIN_IN
4、CAN配置
在CAN模块中主要配置CAN相关的属性
打开Can_17_McmCan模块,在General选项卡中选择对应的选项
打开CanController选项卡,新建CanController_0属性,并双击打开
在CanController_0的General中设置相关属性,由于CAN00在P20.7和P20.8上是RXDB
在CanController_0的CanControllerBaudrateConfig新建CanControllerBaudrateConfig_0并打开设置波特率
设置波特率为500K
在Can的CanHardwareObject新建两个对象CanHardwareObject_0和CanHardwareObject_1
CanHardwareObject_0用于接收
CanHardwareObject_1用于发送
双击打开CanHardwareObject_0,设置帧ID类型和接收模式
在CanHwFilter设置接收滤波参数
双击打开CanHardwareObject_1,设置帧ID类型和发送模式
5、Irq配置
在Irq模块中主要配置CAN的中断相关属性
打开Irq模块,找到IrqCanPrioConfig,设置IrqCanSR0Prio、IrqCanSR1Prio、IrqCanSR2Prio、IrqCanSR3Prio的优先级
6、ResourceM设置
在ResourceM模块中主要设置CAN的资源分配
打开ResourceM模块,进入ResourceMMcalCore,设置ResourceMAllocation_0为CAN,并对应CanController_0
三、编译
1、添加文件
点击EB生成代码,将生成的代码添加到Aurix Development Studio工程中,并
将MCAL DEMO中的CanIf_Cbk.c和CanIf_Cbk.h添加到工程中
将Can_17_McmCan_Irq.c添加到工程中
2、添加代码
在main中添加Mcu初始化代码
void User_Mcu_Init(void)
{
const Mcu_ConfigType* ConfigPtr = NULL_PTR;
volatile Mcu_ClockType ClockID = 0;
Std_ReturnType InitClockRetVal;
Mcu_PllStatusType Mcu_GetPllStatusRetVal = MCU_PLL_STATUS_UNDEFINED;
ConfigPtr = &Mcu_Config;
Mcu_Init(ConfigPtr);
InitClockRetVal = Mcu_InitClock(ClockID);
if (InitClockRetVal == E_OK)
{
do
{
Mcu_GetPllStatusRetVal = Mcu_GetPllStatus();
} while (Mcu_GetPllStatusRetVal != MCU_PLL_LOCKED);
#if (MCU_DISTRIBUTE_PLL_CLOCK_API == STD_ON)
Mcu_DistributePllClock();
#endif
}
}
添加Dio初始化代码
void User_Port_Init(void)
{
Port_Init(&Port_Config);
}
添加Can初始化代码
void User_Can_Init()
{
Can_17_McmCan_Init(&Can_17_McmCan_Config);
IrqCan_Init();
/* Enter Critical Section */
SchM_Enter_Can_17_McmCan_CanIntCtrl();
SRC_CAN0INT0.U |= CAN_SRC_SET_SRE;
SRC_CAN0INT1.U |= CAN_SRC_SET_SRE;
SRC_CAN0INT2.U |= CAN_SRC_SET_SRE;
SRC_CAN0INT3.U |= CAN_SRC_SET_SRE;
/* Exit Critical Section */
SchM_Exit_Can_17_McmCan_CanIntCtrl();
Can_17_McmCan_SetControllerMode(Can_17_McmCanConf_CanController_CanController_0, CAN_T_START);
Can_17_McmCan_EnableControllerInterrupts(Can_17_McmCanConf_CanController_CanController_0);
}
CAN发送则调用Can_17_McmCan_Write函数进行发送
unsigned char can_tx_data[][10] = { {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 } };
Can_PduType PduInfo_1[] = { {8, 8, 0x718, can_tx_data[0]} };
unsigned char CanRxDataBuff[20][64];
Can_17_McmCan_Write(Can_17_McmCanConf_CanHardwareObject_CanHardwareObject_1, &PduInfo_1);
CAN接收则会回调CanIf_Cbk.c中的CanIf_RxIndication函数,在其中处理接收报文即可。