Dependents:   Kamal_CAN ReadFromSerial446

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers CAN3.cpp Source File

CAN3.cpp

00001 #include "CAN3.h"
00002 
00003 #include "mbed.h"
00004 #include "mcp2515.h"
00005 #include "mcp2515_can.h"
00006 #include "mcp2515_defs.h"
00007 
00008 
00009 CAN3::CAN3(SPI& _spi, PinName ncs, PinName itr)
00010         : spi(_spi), _mcp(spi, ncs), _itr(itr) {
00011     printf("\n\rcan = %d",this);
00012 
00013 }
00014 
00015 uint8_t CAN3::read(CANMessage *msg) {
00016     uint8_t stat, res;
00017 
00018     stat = _mcp.readStatus();
00019 
00020     if ( stat & MCP_STAT_RX0IF ) {
00021         // Msg in Buffer 0
00022         _mcp.read_canMsg( MCP_RXBUF_0, msg);
00023         _mcp.modifyRegister(MCP_CANINTF, MCP_RX0IF, 0);
00024         res = CAN_OK;
00025     } else if ( stat & MCP_STAT_RX1IF ) {
00026         // Msg in Buffer 1
00027         _mcp.read_canMsg( MCP_RXBUF_1, msg);
00028         _mcp.modifyRegister(MCP_CANINTF, MCP_RX1IF, 0);
00029         res = CAN_OK;
00030     } else {
00031         res = CAN_NOMSG;
00032     }
00033 
00034     return res;
00035 }
00036 
00037 uint8_t CAN3::checkReceive(void) {
00038     uint8_t res;
00039 
00040     res = _mcp.readStatus(); // RXnIF in Bit 1 and 0
00041     if ( res & MCP_STAT_RXIF_MASK ) {
00042         return CAN_MSGAVAIL;
00043     } else {
00044         return CAN_NOMSG;
00045     }
00046 }
00047 
00048 void CAN3::write(CANMessage* test) {
00049     uint8_t  txbuf_n;
00050     _mcp.getNextFreeTXBuf(&txbuf_n);
00051     _mcp.write_canMsg(txbuf_n,test);
00052     _mcp.start_transmit( txbuf_n );
00053 }
00054 
00055 void CAN3::rise(void (*fptr)(void)) {
00056     _itr.rise(fptr);
00057 }
00058 
00059 void CAN3::fall(void (*fptr2)(void)) {
00060     _itr.fall(fptr2);
00061 }
00062 
00063 int CAN3::frequency(int canSpeed) {
00064 
00065     uint8_t res;
00066 
00067     res = _mcp.init(canSpeed); //CAN_500KBPS_8MHZ
00068     wait(.001);
00069 
00070     _mcp.setRegister(MCP_CANINTE, 0x3);//0x3); //MCP_RX_INT);
00071     _mcp.setRegister(MCP_CANINTF, 0x3);// 0xff);
00072 
00073 
00074 //RX0,1 as rx0,1 digital interrupt outputs
00075 //_mcp.setRegister(BFPCTRL, 0xf);
00076 
00077 //[Set TX0,1,2 as digital inputs
00078 //_mcp.setRegister(TXRTSCTRL, 0x0);
00079 
00080     // printf("Setting Normal-Mode - \n\r ");
00081     if ( _mcp.setCANCTRL_Mode(MODE_NORMAL) == MCP2515_OK) { //MODE_NORMAL MODE_LOOPBACK
00082         //     printf("OK\n\r");
00083     } else {
00084         error("failed\n\r");
00085     }
00086 
00087     _mcp.dumpExtendedStatus();
00088     wait(.001);
00089 
00090     if (res != MCP2515_OK) {
00091         return 0;
00092 
00093     }
00094     return 1;
00095 }