The CAN handle vs channel number

  • June 3, 2015
  • Magnus Carlsson

When writing “Was that the CANlib channel number or Card Number?“, I got a comment asking for clarification about the difference between the CanHandle and channel number since they can both start at zero.

A CAN channel is opened using the function canOpenChannel() in CANlib, passing the channel number as the first argument.

CanHandle handle;
canStatus stat;

int canLibChannelNumber = 0;

handle = canOpenChannel(canLibChannelNumber, canOPEN_ACCEPT_VIRTUAL);
if (handle < 0) {
  printf("canOpenChannel failed, status=%d\n", stat);

This will return a handle that can be any non-negative number (and it is often zero the first time you call it). The handle is used later e.g. when reading the next available CAN messages. If the call to canOpenChannel() fails, a negative error code will be returned instead of the valid handle.

long id;
unsigned char data[8];
unsigned int dlc, flags;
unsigned long timestamp;

stat = canRead(handle, &id, data, &dlc, &flags, &timestamp);
if (stat != canERR_NOMSG) {
  printf("Failed, status == %d\n", stat);

The handle is an internal positive number that should never be edited manually. As mentioned, the CanHandle returned in CANlib could be mixed up with the channel number but later libraries, such as kvrlib, returns a much larger, more random, number in order to minimize the risk of confusion.

I suggest to get into the habit of always declaring the handle as a CanHandle (instead of int) and thereby clearly marking it a handle. While making suggestions, may I also encourage you to always check the return status as we did on canRead() above? This will shorten the debug time when things start to fail…

Author Image

Magnus Carlsson

Magnus Carlsson is a Software Developer for Kvaser AB and has developed firmware and software for Kvaser products since 2007. He has also written a number of articles for Kvaser’s Developer Blog dealing with the popular Python language.