Hello, CAN!

Let's start with a simple example.

#include <canlib.h>
#include <stdio.h>
void main(void)
canHandle hnd;
if (hnd < 0) {
char msg[64];
canGetErrorText((canStatus)hnd, msg, sizeof(msg));
fprintf(stderr, "canOpenChannel failed (%s)\n", msg);
canSetBusParams(hnd, canBITRATE_250K, 0, 0, 0, 0, 0);
canWrite(hnd, 123, "HELLO!", 6, 0);
canWriteSync(hnd, 500);

What does it do?

  1. The CANlib library is initialized by a call to canInitializeLibrary().
  2. A channel to a CAN circuit is opened. In this case we open channel 0 which should be the first channel on the CAN interface. canOPEN_EXCLUSIVE means we don't want to share this channel with any other currently executing program.
  3. The CAN bus bit rate is set 250 kBit/s, using a set of predefined bus parameters.
  4. The CAN bus driver type is set.
  5. The CAN chip is activated.
  6. A message with (11-bit) CAN id = 123, length 6 and contents (decimal) 72, 69, 76, 76, 79, 33 is transmitted.
  7. Wait until the message is sent or at most 500 ms.
  8. Inactivate the CAN chip.
  9. Close the channel.

What does it not do? Almost all error checking is omitted for brevity, see Error checking.

Error checking

The CANlib API consists exclusively of functions. Most of the functions return a status code of type canStatus, which is a negative number if the call failed, see canERR_xxx, and canOK (zero) if the call succeeded.

To get a textual description of an error code, use canGetErrorText()

Example. Error checking of canStatus and using canGetErrorText() to print a textual message.

// Print status message if stat contains an error code
static void checkStatus(char* id, canStatus stat)
if (stat != canOK) {
char buf[100];
buf[0] = '\0';
// Retreive informational text about the status code
canGetErrorText(stat, buf, sizeof(buf));
printf("%s: failed, stat=%d (%s)\n", id, (int)stat, buf);
} // checkStatus
// We check the status returned by the call to canSetBusParams
stat = canSetBusParams(hnd, canBITRATE_250K, 0, 0, 0, 0, 0);
checkStatus("canSetBusParams", stat);

CANlib Core API Calls

The following calls can be considered the CANlib "core" as they are essential for almost any program that uses the CAN bus.