微波EDA网,见证研发工程师的成长!
首页 > 射频和无线通信 > 射频无线通信文库 > 基于dsPIC33FJ128MC506的CAN通信

基于dsPIC33FJ128MC506的CAN通信

时间:03-04 来源:电子产品世界 点击:

的含义如下:

/*buf -> 发射寄存器号

txIdentifier ->发射报文的ID

ide -> "0" 报文为标准帧

"1" 报文为扩展帧

remoteTransmit -> "0" 报文为正常报文

"1" 报文为远程报文 */

void ecan1WriteTxMsgBufId(unsigned int buf, long txIdentifier, unsigned int ide, unsigned int remoteTransmit)

{

/*定义局部变量*/

unsigned long word0=0, word1=0, word2=0;

unsigned long sid10_0=0, eid5_0=0, eid17_6=0;

/*赋值*/

eid5_0 = (txIdentifier & 0x7FF);

eid17_6 = (txIdentifier>>6) & 0x7F;

sid10_0 = (txIdentifier>>18) & 0x7FF;

word1 = eid17_6;

if(remoteTransmit==1) // 远程帧

{

word0 = ((sid10_0 < 2) | ide | 0x2);

word2 = ((eid5_0 < 10)| 0x0200);

}

else { //正常帧

word2 = 0;

word0 = (eid5_0 < 2);

}

/*将地址写入发射缓冲器对应的区域 */

ecan1msgBuf[buf][0] = word0;

ecan1msgBuf[buf][1] = word1;

ecan1msgBuf[buf][2] = word2;

}

  写报文内容

/*下面的函数将待发报文内容写入到发射缓冲区,各参数含义如下:

buf -> 发射缓冲器号

dataLength -> 数据的长度

data1/data2/data3/data4 -> 发射数据内容*/

void ecan1WriteTxMsgBufData(unsigned int buf, unsigned int dataLength, unsigned int data1, unsigned int data2, unsigned int data3, unsigned int data4)

{

ecan1msgBuf[buf][2] = ((ecan1msgBuf[buf][2] & 0xFFF0) + dataLength) ;//数据长度

ecan1msgBuf[buf][3] = data1; //数据1

ecan1msgBuf[buf][4] = data2; //数据2

ecan1msgBuf[buf][5] = data3; //数据3

ecan1msgBuf[buf][6] = data4; //数据4

}

报文的接收

报文接收在中断中进行,函数语句如下:

void __attribute__((interrupt, no_auto_psv))_C1Interrupt(void) //CAN1中断

{

IFS2bits.C1IF = 0; //请中断标志

if(C1INTFbits.TBIF) //是否为发射中断

{

C1INTFbits.TBIF = 0;

}

if(C1INTFbits.RBIF) //是否为接收中断

{

C1INTFbits.RBIF = 0; //请接收中断标志位

/*读出报文*/

ReceiveMessageID = (ecan1msgBuf[2][0]>>2);

ReveiveDataLength = (ecan1msgBuf[2][2]&0x000f);

ReceiveData[0] = ecan1msgBuf[2][3];

ReceiveData[1] = ecan1msgBuf[2][4];

ReceiveData[2] = ecan1msgBuf[2][5];

ReceiveData[3] = ecan1msgBuf[2][6];

C1RXFUL1bits.RXFUL2 = 0; //清报文溢出标志

ReceiveNewMessage = 1; //接收标志置位

}

C1RXOVF1bits.RXOVF2 = 0;

}

写标准报文函数

void ecan1WriteMessage(unsigned int ID,unsigned int Length,unsigned int *Data)

{

ecan1WriteTxMsgBufId(0,ID,0,0);

ecan1WriteTxMsgBufData(0,Length,*Data,*(Data+1),*(Data+2),*(Data+3));

C1TR01CONbits.TXREQ0=1;

}

CAN通信示例程序

用于检验ECAN1的发射接收,其功能是收到CANoe发送COMMAND_BSI后,开始发送数据。

int main(void)

{

oscConfig() //振荡器设置

/* 清中断各标志位*/

IFS0=0;

IFS1=0;

IFS2=0;

IFS3=0;

IFS4=0;

ecan1Init(); //初始化ECAN1

dma0init(); //DMA初始化

dma2init();

TJA1054Init(); //TJA1054初始化

/*使能ECAN1中断*/

IEC2bits.C1IE = 1;

C1INTEbits.TBIE = 1;

C1INTEbits.RBIE = 1;

while (1)

{

/*向ECAN1发射缓冲区写报文并请求发射*/

can1WriteMessage(TXMmessageID, TXMessageLength, TXMessage);

}

}

CANoe测试结果如图2所示。

?

  图2 CANoe通讯测试界面

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top