how-to/c/openChannels.c

This example shows how to open a channel in CAN and CAN FD mode. See Open Channel for more information.

------------------------------------------------------------------------------

#include <canlib.h>
#include <stdio.h>
// Print status message if stat contains an error code
static void check(const char* id, canStatus stat)
{
if (stat != canOK) {
char buf[50];
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);
}
} // check
canHandle open_channel_as_can(int channel_number)
{
canHandle hnd;
canStatus stat;
// open channel in CAN mode
hnd = canOpenChannel(channel_number, 0);
if (hnd < 0) {
check("canOpenChannel", (canStatus)hnd);
return hnd;
}
// set the bus speed to 500 kbit/s
stat = canSetBusParams(hnd, canBITRATE_500K, 0, 0, 0, 0, 0);
check("canSetBusParams", stat);
return hnd;
}
canHandle open_channel_as_canfd(int channel_number)
{
canHandle hnd;
canStatus stat;
// open channel in CAN FD mode
if (hnd < 0) {
check("canOpenChannel", (canStatus)hnd);
return hnd;
}
// set the arbitration bitrate to 500 kbit/s, with sampling point to 80%,
// and data phase bitrate to 1000 kbit/s, with sampling point at 80%
stat = canSetBusParams(hnd, canFD_BITRATE_500K_80P, 0, 0, 0, 0, 0);
check("canSetBusParams", stat);
stat = canSetBusParamsFd(hnd, canFD_BITRATE_1M_80P, 0, 0, 0);
check("canSetBusParamsFD", stat);
// return handle to channel
return hnd;
}