Recent Posts
CAN Bus Prototyping With Arduino Uno - The MCP2515 Library
Posted by
onThis post is part of a series about Controller Area Network (CAN Bus) Prototyping With the Arduino Uno.
As with any serial networking controller, the essential functions are:
- Initialization
- Read Data
- Write Data
- Check Status
In case of the MCP2515 library, these functions are represented by:
- Initialization: CAN0.begin
- Read Data: CAN0.readMsgBuf incl. CAN0.checkReceive, CAN0.getCanId
- Write Data: CAN0.sendMsgBuf
- Check Status: CAN0.checkError
Function Calls
Function: CAN0.begin
Purpose:
Initializes
the CAN controller and sets the speed (baud rate)
Parameter:
CAN_5KPS
… CAN_1000KPS (See mcp_can_dfs.h)
Return Code:
CAN_OK
= Initialization okay
CAN_FAILINIT
= Initialization failed
Function: CAN0.checkReceive
Purpose:
Check if message was
received
Parameter:
None
Return
Code:
CAN_MSGAVAIL = Message
available
CAN_NOMSG =
No message
Function: CAN0.readMsgBuf
Purpose:
Read the message buffer
Parameter:
nMsgLen returns the message
length (number of data bytes)
nMsgBuffer
returns the actual message
Return
Code:
None
Function: CAN0.getCANId
Purpose:
Retrieves the ID of the
received message
Parameter:
None
Return
Code:
m_nID = Message ID
Function: CAN0. sendMsgBuf
Purpose:
Send a message buffer
Parameter:
id = Message ID
ext =
CAN_STDID (11-bit ID) or CAN_EXTID (29-bit ID)
len = Number
of data bytes (0…8)
buf =
Message buffer
Return
Code:
None
Function: CAN0.checkError
Purpose:
Checks CAN controller for
errors
Parameter:
None
Return
Code:
CAN_OK = Status okay
CAN_CTRLERROR
= Error
There are further functions, among others, for message filtering and settings masks, and they are worth being checked out for more sophisticated functions, but they are not necessary for simple CAN communication tasks.
Implementation
The implementation of the MPC2515 library is fairly easy: Open Arduino, create a new file, then use the menu items Sketch->Add File… to include the following files to the project:
- mcp_can.cpp
- mcp_can.h
- mcp_can_dfs.h
In the Arduino project file add the following on top:
#include "mcp_can.h"
#include <SPI.h>
MCP_CAN CAN0(10);
Let me repeat here: The Seeed Studio CAN Bus shield has been undergoing some hardware changes to become compatible with systems such as the Arduino Mega 2560. The version 1.0 will work with the Arduino Uno, while all higher versions also work with the Mega 2560. This will also affect the code of the Arduino projects, specifically the line “MCP_CAN CAN0(10);” in the main module selecting the CS pin. That line must change to “MCP_CAN CAN0(9);” for all CAN bus shield versions above 1.0.
You are now ready to go. The following chapters will describe how to implement the function calls.