Today we take a look at how to setup and send a CAN message using Kvaser’s new Python package canlib. For this example we use the Kvaser USBcan Pro 2xHS v2, but any Kvaser interface can be used.
First step is to download and install Kvaser Linux Driver and SDK (the current version of CANlib is v5.18):
$ cd ~
$ wget http://www.kvaser.com/software/7330130980754/V5_18_0/linuxcan.tar.gz
$ tar xf linuxcan.tar.gz
$ cd linuxcan
$ make
$ sudo make install
Now we insert the Kvaser interface into a USB port and run the `listChannels’ example program to verify that the driver loaded correctly and our device is recognized:
$ cd canlib/examples
$ ./listChannels
Found 2 channel(s).
channel 0 = Kvaser USBcan Pro 2xHS v2, 73-30130-00752-9, 1012, 3.4.0.822
channel 1 = Kvaser USBcan Pro 2xHS v2, 73-30130-00752-9, 1012, 3.4.0.822
The next step is to download and install the Python canlib package (current version is v1.1.23):
$ cd ~
$ wget http://www.kvaser.com/software/7330130981911/V1_1_23/canlib-1.1.23.zip
$ pip install canlib-1.1.23.zip
If you are using Python v3, you would probably be using pip3
instead of pip
in order to install the Python package in the correct place.
Now we can write a small Python program, sendReceiveSingleCanMsg.py
, that sends a CAN message on channel 1 and receives the same CAN message on channel 0:
import canlib.canlib as canlib
def setUpChannel(channel=0,
openFlags=canlib.canOPEN_ACCEPT_VIRTUAL,
bitrate=canlib.canBITRATE_500K,
bitrateFlags=canlib.canDRIVER_NORMAL):
cl = canlib.canlib()
ch = cl.openChannel(channel, openFlags)
print("Using channel: %s, EAN: %s" % (ch.getChannelData_Name(),
ch.getChannelData_EAN()))
ch.setBusOutputControl(bitrateFlags)
ch.setBusParams(bitrate)
ch.busOn()
return ch
def tearDownChannel(ch):
ch.busOff()
ch.close()
cl = canlib.canlib()
print("canlib version: %s" % cl.getVersion())
channel_0 = 0
channel_1 = 1
ch0 = setUpChannel(channel=0)
ch1 = setUpChannel(channel=1)
msgId = 100
msg = [1, 2, 3, 4]
flg = canlib.canMSG_EXT
ch1.write(msgId, msg, flg)
while True:
try:
(msgId, msg, dlc, flg, time) = ch0.read()
data = ''.join(format(x, '02x') for x in msg)
print("time:%9d id:%9d flag:0x%02x dlc:%d data:%s" %
(time, msgId, flg, dlc, data))
break
except (canlib.canNoMsg) as ex:
None
except (canlib.canError) as ex:
print(ex)
tearDownChannel(ch0)
tearDownChannel(ch1)
Running the above Python program results in the following:
$ python sendReceiveSingleCanMsg.py
canlib version: 5.18
Using channel: Kvaser USBcan Pro 2xHS v2 (channel 0), EAN: 73-30130-00752-9
Using channel: Kvaser USBcan Pro 2xHS v2 (channel 1), EAN: 73-30130-00752-9
time: 2819710 id: 100 flag:0x04 dlc:4 data:01020304
If you are using Python v3, you would probably be using python3
instead of python
.
And thus we have successfully sent and received a CAN message using the Python canlib package.
Bug reports, contributions, suggestions for improvements, and similar things are much appreciated and can be sent by e-mail to support@kvaser.com.