kvaser在linux下的二次开发
-
linux下kvaser的驱动和SDK包安装
下载连接: http://www.kvaser.cn/software/7330130980754/V5_13_0/linuxcan.tar.gz
安装过程:
解压:tar -xvzf linuxcan.tar.gz
安装Kernel 头文件:sudo apt-get install build-essentia
安装所有驱动:make;sudo make install
确认安装成功:进入linuxcan/canlib/examples 执行:./listChannels
如果我们安装的驱动是正确的,终端会显示出总线上可用通道的数量
-
开发
在这以C语言和Cmake编译举例
CMakeLists.txt文件中
# 添加链接库
target_link_libraries(kvaser_test canlib)
头文件中添加#include <canlib.h>
这样就可以使用kavser的API了.
-
简单代码举例
#include <canlib.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
static void microseconds_sleep(unsigned long uSec) {
struct timeval tv;
tv.tv_sec = uSec / 1000000;
tv.tv_usec = uSec % 1000000;
int err;
do {
err = select(0, NULL, NULL, NULL, &tv);
} while (err < 0 && errno == EINTR);
}
int main() {
canHandle hnd_0;
canStatus status_0;
canInitializeLibrary();
hnd_0 = canOpenChannel(0, 0);
if (hnd_0 < 0) {
printf("canOpenChannel failed, hnd_0=%d\n", hnd_0);
return 1;
}
status_0 = canSetBusParams(hnd_0, canBITRATE_500K, 0, 0, 0, 0, 0);
if (status_0 < 0) {
printf("canSetBusParams failed, status_0=%d\n", status_0);
return 1;
}
status_0 = canBusOn(hnd_0);
if (status_0 < 0) {
printf("canBusOn failed, status_0=%d\n", status_0);
return 1;
}
while (1) {
canStatus status;
long id;
unsigned char data_read[8];
unsigned int dlc, flags;
unsigned long timestamp;
status = canRead(hnd_0, &id, data_read, &dlc, &flags, ×tamp);
if (status == canOK) {
for (int i = 0; i < 8; i++) {
printf("date[%d]: %X\n", i, data_read[i]);
}
} else {
printf("Failed, status == %d\n", status);
}
microseconds_sleep(1000000);
}
canBusOff(hnd_0);
canClose(hnd_0);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)