Skip to content
Open in AI

Kvaser CANlib SDK ​

Overview ​

Kvaser CANlib SDK is Kvaser's official software development kit for building custom tools around Kvaser CAN, CAN FD, LIN, remote CAN, and data-logger interfaces. On CANmeleon devices running Kvaser FD or Kvaser Leaf firmware, CANlib provides programmatic control for:

  • Enumerating detected Kvaser CAN channels and device metadata;
  • Opening and closing CAN / CAN FD channels;
  • Configuring Classic CAN or CAN FD bit timing;
  • Controlling Bus On and Bus Off transitions;
  • Transmitting and receiving Classic CAN and CAN FD frames;
  • Reading channel status, error counters, error flags, and timestamps;
  • Integrating with automated test benches and verification scripts.

Obtain the SDK ​

Install the official Kvaser driver and CANlib SDK before building or running applications:

Main SDK Components ​

Beyond basic frame transmission, the Kvaser CANlib SDK bundles several specialized libraries:

ComponentPurpose
CANlibCore CAN / CAN FD communication library used to interact with Kvaser CAN channels (primary library used with CANmeleon Kvaser firmware).
LINlibCommunication library for Kvaser LIN interfaces.
kvaDbLibDatabase manipulation library for creating, reading, writing, and editing CAN database (.dbc) definitions.
kvlclibLog-file format converter for log data recorded by Kvaser Memorator loggers.
kvmlibHost library for interacting with Kvaser Memorator data-logger hardware.
kvaMemoLibXMLConverts XML logger configurations into binary configuration images for Kvaser Memorator devices.
kvrlibDiscovery and configuration library for Ethernet- or Wi-Fi-connected Kvaser remote devices.

Virtual Hardware and Virtual Channels ​

The Kvaser driver and CANlib SDK provide virtual CAN hardware and channels so you can develop and debug host software without physical CAN hardware attached. Typical uses include:

  • Early host UI and workflow prototyping before bench hardware is connected;
  • Automated CI or script logic verification;
  • Frame encoding/decoding checks and offline software demonstrations.

Install the Kvaser Virtual CAN Driver component, and pass canOPEN_ACCEPT_VIRTUAL when opening a channel if virtual channels are permitted:

cpp
canOpenChannel(channel, canOPEN_ACCEPT_VIRTUAL);

Virtual channels test software logic only; they do not test physical CAN bus transceivers, bus load, ACK behavior, or electrical error frames.

Supported Languages and Toolchains ​

Kvaser CANlib SDK provides headers, import libraries, wrappers, or bindings for common environments including:

  • C / C++ (MSVC, GCC, MinGW);
  • C# / .NET / Managed C++ / Visual Basic;
  • Delphi;
  • Python (python-can or Kvaser's canlib Python package);
  • Any language environment capable of calling native shared libraries (.dll / .so).

Typical CANlib Call Sequence ​

A standard Classic CAN session follows these steps:

  1. Initialize the library (canInitializeLibrary()).
  2. Query the number of available channels (canGetNumberOfChannels()).
  3. Inspect channel names, device models, EANs, or serial numbers (canGetChannelData()).
  4. Open the target channel (canOpenChannel()).
  5. Configure bus bit timing (canSetBusParams(), plus canSetBusParamsFd() for CAN FD).
  6. Set the driver output mode (canSetBusOutputControl(), e.g., canDRIVER_NORMAL or canDRIVER_SILENT).
  7. Go on bus (canBusOn()).
  8. Transmit (canWrite() / canWriteSync()) and receive (canRead() / canReadWait()) frames.
  9. Read bus status and error flags as needed (canReadStatus() / canReadErrorCounters()).
  10. Go off bus (canBusOff()) when finished.
  11. Close the channel handle (canClose()).

C/C++ Channel Enumeration Example ​

cpp
#include <canlib.h>
#include <iostream>

int main()
{
    canInitializeLibrary();

    int channelCount = 0;
    canStatus status = canGetNumberOfChannels(&channelCount);

    if (status != canOK)
    {
        std::cout << "canGetNumberOfChannels failed." << std::endl;
        return -1;
    }

    std::cout << "Detected Kvaser channels: "
              << channelCount
              << std::endl;

    for (int ch = 0; ch < channelCount; ch++)
    {
        char channelName[128] = {0};

        status = canGetChannelData(
            ch,
            canCHANNELDATA_CHANNEL_NAME,
            channelName,
            sizeof(channelName));

        if (status == canOK)
        {
            std::cout << "Channel "
                      << ch
                      << " : "
                      << channelName
                      << std::endl;
        }
    }

    return 0;
}

In multi-device setups, also query canCHANNELDATA_CARD_UPC_NO (EAN), canCHANNELDATA_CARD_SERIAL_NO, and canCHANNELDATA_CHAN_NO_ON_CARD to bind channels deterministically.

C/C++ Classic CAN Transmit Example ​

The example below opens channel 0, sets a 500 kbit/s Classic CAN bitrate, and transmits an 8-byte standard frame:

cpp
#include <canlib.h>
#include <iostream>

static void printError(canStatus status)
{
    char errorText[128] = {0};
    canGetErrorText(status, errorText, sizeof(errorText));
    std::cout << "CANlib error: " << errorText << std::endl;
}

int main()
{
    canInitializeLibrary();

    int channel = 0;

    canHandle handle = canOpenChannel(
        channel,
        canOPEN_ACCEPT_VIRTUAL);

    if (handle < 0)
    {
        printError((canStatus)handle);
        return -1;
    }

    canStatus status = canSetBusParams(
        handle,
        canBITRATE_500K,
        0,
        0,
        0,
        0,
        0);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    status = canSetBusOutputControl(
        handle,
        canDRIVER_NORMAL);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    status = canBusOn(handle);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    unsigned char data[8] = {
        0x01, 0x02, 0x03, 0x04,
        0x05, 0x06, 0x07, 0x08
    };

    status = canWrite(
        handle,
        0x123,
        data,
        8,
        0);

    if (status != canOK)
    {
        printError(status);
    }

    status = canWriteSync(
        handle,
        100);

    if (status != canOK)
    {
        printError(status);
    }

    canBusOff(handle);
    canClose(handle);

    return 0;
}

C/C++ CAN FD Transmit Example ​

Use CAN FD with Kvaser FD firmware. Ensure both the arbitration-phase and data-phase bitrates and sample points match all nodes on the target network:

cpp
#include <canlib.h>
#include <iostream>

static void printError(canStatus status)
{
    char errorText[128] = {0};
    canGetErrorText(status, errorText, sizeof(errorText));
    std::cout << "CANlib error: " << errorText << std::endl;
}

int main()
{
    canInitializeLibrary();

    int channel = 0;

    canHandle handle = canOpenChannel(
        channel,
        canOPEN_CAN_FD | canOPEN_ACCEPT_VIRTUAL);

    if (handle < 0)
    {
        printError((canStatus)handle);
        return -1;
    }

    /*
     * Arbitration-phase bitrate: 1 Mbit/s, 80% sample point.
     * Check canlib.h in your installed SDK version for exact bitrate constants.
     */
    canStatus status = canSetBusParams(
        handle,
        canFD_BITRATE_1M_80P,
        0,
        0,
        0,
        0,
        0);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    /*
     * Data-phase bitrate: 4 Mbit/s, 80% sample point.
     */
    status = canSetBusParamsFd(
        handle,
        canFD_BITRATE_4M_80P,
        0,
        0,
        0);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    status = canSetBusOutputControl(
        handle,
        canDRIVER_NORMAL);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    status = canBusOn(handle);

    if (status != canOK)
    {
        printError(status);
        canClose(handle);
        return -1;
    }

    unsigned char data[64] = {0};
    for (int i = 0; i < 64; i++)
    {
        data[i] = (unsigned char)i;
    }

    /*
     * canFDMSG_FDF marks a CAN FD frame.
     * canFDMSG_BRS enables data-phase bit rate switching.
     * Omit canFDMSG_BRS if bit rate switching is not used.
     */
    unsigned int flags = canFDMSG_FDF | canFDMSG_BRS;

    status = canWrite(
        handle,
        0x123,
        data,
        64,
        flags);

    if (status != canOK)
    {
        printError(status);
    }

    status = canWriteSync(
        handle,
        100);

    if (status != canOK)
    {
        printError(status);
    }

    canBusOff(handle);
    canClose(handle);

    return 0;
}

C/C++ Receive Example ​

Read frames from the receive queue with canRead() (or canReadWait()) and inspect flags to distinguish Classic CAN from CAN FD frames:

cpp
long id = 0;
unsigned char data[64] = {0};
unsigned int dlc = 0;
unsigned int flags = 0;
unsigned long timestamp = 0;

canStatus status = canRead(
    handle,
    &id,
    data,
    &dlc,
    &flags,
    &timestamp);

if (status == canOK)
{
    std::cout << "ID: 0x"
              << std::hex
              << id
              << " DLC: "
              << std::dec
              << dlc
              << " Timestamp: "
              << timestamp
              << std::endl;

    if (flags & canFDMSG_FDF)
    {
        std::cout << "CAN FD frame" << std::endl;
    }
    else
    {
        std::cout << "Classic CAN frame" << std::endl;
    }
}
else if (status == canERR_NOMSG)
{
    /*
     * No frame currently queued; wait on a notification handle or canReadWait()
     * instead of spinning in a busy loop.
     */
}
else
{
    printError(status);
}

For sustained or low-latency workloads, use canReadWait() or notification callbacks/handles on a dedicated receive thread rather than busy-polling canRead().

Error Handling ​

Most CANlib functions return a canStatus code. Check every call and translate negative status values with canGetErrorText():

cpp
canStatus status = canBusOn(handle);

if (status != canOK)
{
    char errorText[128] = {0};

    canGetErrorText(
        status,
        errorText,
        sizeof(errorText));

    printf("canBusOn failed: %s\n", errorText);
}

Pay close attention to:

  • Channel open or bit-timing configuration failures;
  • canBusOn failures or transmit timeouts (canWriteSync);
  • Empty receive queue (canERR_NOMSG) vs. full transmit queue (canERR_TXBUFOFL);
  • Error Passive (Bus Heavy), Bus Off, ACK Error, and canMSG_ERROR_FRAME flags;
  • USB disconnects or missing / mismatched Kvaser drivers and CANlib runtime libraries.

Python Development ​

Python is convenient for automated regression tests, bench scripting, and rapid diagnostics. Two common approaches are available; both require the Kvaser driver and CANlib runtime to be installed first.

1. Using python-can ​

python-can accesses Kvaser channels via interface="kvaser".

Classic CAN example:

python
import can

bus = can.Bus(
    interface="kvaser",
    channel=0,
    bitrate=500000
)

msg = can.Message(
    arbitration_id=0x123,
    data=[1, 2, 3, 4],
    is_extended_id=False
)

bus.send(msg)
bus.shutdown()

CAN FD example:

python
import can

bus = can.Bus(
    interface="kvaser",
    channel=0,
    bitrate=1000000,
    data_bitrate=4000000,
    fd=True
)

msg = can.Message(
    arbitration_id=0x123,
    data=bytes(range(64)),
    is_extended_id=False,
    is_fd=True,
    bitrate_switch=True
)

bus.send(msg)
bus.shutdown()

2. Using Kvaser's Official canlib Python Package ​

You can also install Kvaser's official Python wrapper around CANlib:

bash
pip install canlib

Class and helper names vary slightly across canlib package releases; consult the examples bundled with the Kvaser CANlib SDK and Kvaser's pycanlib documentation for the installed package version.

CANmeleon · USB-CAN / CAN FD Hardware, Firmware & Solutions

Image preview0 × 0 px
100%
Click backdrop or press Esc to return