/*********************************************************************
* Function: void CANEnable(int Channel, int BusSpeed )
*
* PreCondition: SPI port configured, CANReset is called, and RXB
* Filters intitialized.
*
* Input: Channel: SPI channel number, 1 based
* BusSpeed: Bus Speed code: CAN_500kbps
* CAN_250kbps, or CAN_125kbps
* mode 1 = REQOP_NORMAL else REQOP_LOOPBACK
*
* Output: None
*
* Side Effects: None
*
* Overview: Sets the CAN bus speed and turns on the CAN controller.
*
* Note: None.
********************************************************************/
void CANEnable( int Channel, int BusSpeed, int mode )
{
//Set CNF1
CAN2515ByteWrite(Channel, CNF1, BusSpeed);
//Set CNF2
// CAN2515ByteWrite(Channel, CNF2,0x80 | PHSEG1_3TQ | PRSEG_1TQ);
CAN2515ByteWrite(Channel, CNF2,0x80 | PHSEG1_3TQ | PRSEG_3TQ);
//Set CNF3
CAN2515ByteWrite(Channel, CNF3, PHSEG2_3TQ);
//Interrupt on RXB0 - CANINTE
CAN2515ByteWrite(Channel, CANINTE,0x01); // Interrupts are on
if(mode)
{
//Set NORMAL mode
CAN2515ByteWrite(Channel, CANCTRL,REQOP_NORMAL | CLKOUT_ENABLED);
CAN2515ByteRead(Channel, CANSTAT); //dummy read to give 2515 time to switch to normal mode
if( (CAN2515ByteRead(Channel, CANSTAT) & 0xE0) != OPMODE_NORMAL )
CAN2515ByteWrite(Channel, CANCTRL,REQOP_NORMAL | CLKOUT_ENABLED);
else
xprintf("\nCAN enabled normal mode \n");
}
else
{
CAN2515ByteWrite(Channel, CANCTRL,REQOP_LOOPBACK | CLKOUT_ENABLED);
CAN2515ByteRead(Channel, CANSTAT); //dummy read to give 2515 time to switch to normal mode
if( (CAN2515ByteRead(Channel, CANSTAT) & 0xE0) != REQOP_LOOPBACK )
{
printf("CAN setting loopback mode failed - try again\n");
CAN2515ByteWrite(Channel, CANCTRL, REQOP_LOOPBACK | CLKOUT_ENABLED);
}
else
xprintf("CAN enabled loop back mode \n");
}
}