Let's start with a simple example.
#include <canlib.h>
#include <stdio.h>
void main(void)
{
canHandle hnd;
canInitializeLibrary();
hnd = canOpenChannel(0, canWANT_EXCLUSIVE);
if (hnd < 0) {
char msg[64];
canGetErrorText((canStatus)hnd, msg, sizeof(msg));
fprintf(stderr, "canOpenChannel failed (%s)\n", msg);
exit(1);
}
canSetBusParams(hnd, canBITRATE_250K, 0, 0, 0, 0, 0);
canSetBusOutputControl(hnd, canDRIVER_NORMAL);
canBusOn(hnd);
canWrite(hnd, 123, "HELLO!", 6, 0);
canWriteSync(hnd, 500);
canBusOff(hnd);
canClose(hnd);
}
What does it do?
- The CANLIB library is initialized by a call to canInitializeLibrary().
- 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. canWANT_EXCLUSIVE means we don't want to share this channel with any other currently executing program.
- The CAN bus bit rate is set 250 kBit/s, using a set of predefined bus parameters.
- The CAN bus driver type is set.
- The CAN chip is activated.
- A message with (11-bit) CAN id = 123, length 6 and contents (decimal) 72, 69, 76, 76, 79, 31 is transmitted.
- Wait until the message is sent or at most 500 ms.
- Inactivate the CAN chip.
- Close the channel.
What does it not do? Almost all error checking is omitted for brevity.