The CAN handle vs channel number

  • June 3, 2015
  • check-paym check-pay

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

check-paym check-pay

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. abc