void CAN_init(void) {
TRISB = 0x08; /* CANRX(RB3) is input, CANTX(RB2) is output*/
CANCON = 0x80; /* Request configuration mode (CANCON<7:5> = 0b1xx) */
/* Wait until op mode is configuration mode (CANSTAT<2:0> = 0b100) */
while(CANSTAT&0x04 != 0x04);
/* Use enhanced legacy mode (ECANCON<7:6> = 0b01) */
ECANCON = 0x40;
/* Set up baud rate registers */
/* 500 Kbps @ 40MHz */
BRGCON1 = 0x41; /* SWJ = 2TQ BPS = 1 */
BRGCON2 = 0xBA; /* SEG2PHTS = 1, sampled once, PS1 = 8TQ, PropagationT = 3TQ */
BRGCON3 = 0x07; /* Wake-up disabled, PS2 = 8Tq
/* Set up filter and mask registers */
/* B0 is a receive buffer AND B2,B3,B4,B5 are Transmit buffers */
BSEL0 = 0xF8; /* 1111 10-- */
/* Initialize Receive Masks */
/* Accept all SIDs and EIDs */
RXM0EIDH = 0xFF;
RXM0EIDL = 0xFF;
RXM0SIDH = 0xFF;
RXM0SIDL = 0xE0;
RXM1EIDH = 0xFF;
RXM1EIDL = 0xFF;
RXM1SIDH = 0xFF;
RXM1SIDL = 0xE0;
/* Disable all filters */
RXFCON0 = 0x00;
RXFCON1 = 0x00;
/* No Filters assigned to Masks */
MSEL0 = 0xFF; /* Filters 0-2, no mask */
MSEL1 = 0xFF; /* Filters 4-7, no mask */
MSEL2 = 0xFF; /* Filters 8-11, no mask */
MSEL3 = 0xFF; /* Filters 12-15, no mask */
/* Assign all buffers with no filter */
RXFBCON0 = 0xFF;
RXFBCON1 = 0xFF;
RXFBCON2 = 0xFF;
RXFBCON3 = 0xFF;
RXFBCON4 = 0xFF;
RXFBCON5 = 0xFF;
RXFBCON6 = 0xFF;
RXFBCON7 = 0xFF;
/* Initialize Receive Filters */
RXF0EIDH = 0x00;
RXF0EIDL = 0x00;
RXF0SIDH = 0x00;
RXF0SIDL = 0x00;
RXF1EIDH = 0x00;
RXF1EIDL = 0x00;
RXF1SIDH = 0x00;
RXF1SIDL = 0x00;
RXF2EIDH = 0x00;
RXF2EIDL = 0x00;
RXF2SIDH = 0x00;
RXF2SIDL = 0x00;
CANCON = 0x60; /* Request listen only mode (CANCON<7:5> = 0b011) */
/* Wait until op mode is listen only mode (CANSTAT<2:0> = 0b011) */
while(CANSTAT&0x03 != 0x03);
/* Set Receive Mode for buffers */
RXB0CON = 0x00;
RXB1CON = 0x00;
}