Archive
CAN Code for Initialization
Here’s some code to get going. The ECAN section of the 18F4580 datasheet describes the modules function and how to use it, so I’ll only briefly describe what’s going on.
To write to certain ECAN configuration registers, you must request to enter a Config mode, then wait for the module to enter it. The Baud rate settings are tricky, but can be found easily from here, Request form for CANopen Bit Timings. Only one Receive Filter is used and linked to Receive Buffer 0. To add more Enable the filter in RFCONx, associate to a Receive buffer with RXFBCONx, then set its identifier. Last is to exit the Config mode by requesting either Normal mode or Loopback mode for testing. An important point here is that the ECAN module won’t exit config mode unless the microcontroller is correctly connected to a CAN driver IC, even for going to Loopback mode.
void ECAN_Init(void)
{
LATB = 0x00;
TRISBbits.TRISB3 = 1;
CANCON = 0x80; //request CONFIG mode
while(CANSTATbits.OPMODE2==0);
ECANCON = 0x40; //Sets ECAN to Mode 1
BRGCON1 = 0x09; //Sets Baud rate
BRGCON2 = 0x84;
BRGCON3 = 0x00;
BSEL0 = 0xfc;
RXM0EIDH = 0x00; // 0's for EID and SID
RXM0EIDL = 0x00;
RXM0SIDH = 0xFF; // Standard ID FILTER
RXM0SIDL = 0xE0; //Mask0 = 0x7ff
RXFCON0 = 0x01; //filter 0 enabled
RXFCON1 = 0x00; //all others disabled
MSEL0 = 0xfc; //Mask0 assigned to Filter0
MSEL1 = 0xFF; //all others no mask
MSEL2 = 0xFF;
MSEL3 = 0xFF;
RXFBCON0 = 0x00; //filter 0 assoc w/ RXB0, 1 w/ RXB1
RXB0CONbits.RXM1 = 1;
RXF0SIDH = 0x04; //Recv Filter0 = 0x020
RXF0SIDL = 0x00; //Std. Identifier
RXF0EIDH = 0x00;
RXF0EIDL = 0x00;
CANCON = 0x00; //Set ECAN to normal mode
//CANCON = 0x40; //Set ECAN to Loopback mode(TEST)
while(CANSTATbits.OPMODE2 == 1); //wait till out of Config Mode
}//end of ECAN_Init()
When setting up a test bus, start with one node set in Loopback mode. In this mode, the acknowledge bits are ignored and allows the node to receive CAN messages transmitted from itself.This will confirm the baud and filter settings are correct. I made a loop of sending and receiving with counters, then displaying on an LCD(nokia 6100). Once I had my two breadboards able to send and receive the same number of messages, I connected them together. Of course the micrcontroller must be connected to a CAN driver IC, the MCP2551, with a 60Ω resistor connected between the CANH and CANL pins, or the module would never get out of config mode.
The datasheet describes how to transmit a message, and doesn’t need any extra configuration. To receive a message, the ECAN module will accept and place data in the proper register, then set a flag that can be polled. An interrupt can be used too.
Hopefully this helps get others going. Later.