Based on your code, you are trying to run the CAN module with the following configuration:
Baud rate: 250kbps
System frequency: 4000000
Time quanta: 8
Sample point: 75%
Are these correct?
I suggest updating your code in three places:
(1) In your initialization code, you may try the following modifications (please note of the comments):
TRISBbits.RB2=0; // CANTX pin as output
TRISBbits.RB3=1; // CANRX pin as input
LATBbits.LATB2 = 1 // Set CANTX pin to high
while (0x80 != (CANSTAT & 0xE0)); // wait until ECAN is in config mode
RXF0SIDH = 0XFF;
RXF0SIDL = 0XE0;
while (0x00 != (CANSTAT & 0xE0)); // wait until ECAN is in Normal mode
(2) In transmitcan.c, you should check first if TXREQ is cleared before writing to the CAN transmit registers to. I noticed that you are also repeatedly calling the ADC initialization routine in while(1), which is not correct.
initialize_ADC(); // ADC initialization code should be added here not in while(1)
(3) In recepcan.c, the code has the tendency to be stuck at
Try updating it using the following (I'm assuming here that the CAN is expecting to receive a Standard message):
if (RXB0CONbits.RXFUL != 0) //CheckRXB0
if ((RXB0SIDL.EXID == 0) //If Standard Message
// If Extended Message
Newer PIC18F devices are now supported by the MPLABX Code Configurator (MCC) plugin. MCC will generate the CAN APIs (including initialization, transmit and receive) for you based on the configuration you set in the GUI. Since setting up the CAN registers manually is such a tedious task, you can try generating code for devices like the PIC18F25K80
, and tweak it for the PIC18F2580.
If you are not familiar with MCC, this application note can help you get started:MPLAB® Code Configurator CAN 2.0B Module for PIC18 Microcontrollers
Or, I strongly recommend that you migrate to a newer device that is supported by MCC for your CAN project.
Hope this helps. :)