C# kvaser can 通讯

news/2024/12/22 18:44:10/文章来源:https://www.cnblogs.com/JohnnyLei/p/18402222

1、查看官方文档

 

 

https://kvaser.com/canlib-webhelp/section_install_windows.html

 

 

 

2、安装can windows驱动

https://www.kvaser.com/downloads-kvaser/?utm_source=software&utm_ean=7330130980013&utm_status=latest

 3、安装canlib

https://www.kvaser.com/downloads-kvaser/?utm_source=software&utm_ean=7330130980150&utm_status=latest

 

 4、教程

 5、新建项目 引用canlib dll

C# CanlibTutorial, VS2017 (kvaser.com)

 

6、代码

//-----------------------------------------------------------
// This is a sample program for Visual Studio 2017 CANlib tutorial. 
// It prints a list of connected CAN interfaces.
//
// For further information please refer to the tutorial section of the CANlib documentation.
//-----------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kvaser.CanLib;
namespace CanlibTutorial
{class Program{// When called CheckForError will check for and print any error.// Return true if an error has occured.static public bool CheckForError(string cmd, Canlib.canStatus stat){if (stat != Canlib.canStatus.canOK){Canlib.canGetErrorText(stat, out string buf);Console.WriteLine("[{0}] {1}: failed, stat={2}", cmd, buf, (int)stat);return true;}return false;}// ListChannels prints a list of all connected CAN interfaces.static public void ListChannels(){Canlib.canStatus stat;// Get number channelsstat = Canlib.canGetNumberOfChannels(out int number_of_channels);if (CheckForError("canGetNumberOfChannels", stat))return;Console.WriteLine("Found {0} channels", number_of_channels);// Loop and print all channelsfor (int i = 0; i < number_of_channels; i++){stat = Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_DEVDESCR_ASCII, out object device_name);if (CheckForError("canGetChannelData", stat))return;stat = Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHAN_NO_ON_CARD, out object device_channel);if (CheckForError("canGetChannelData", stat))return;Console.WriteLine("Found channel: {0} {1} {2}", i, device_name, ((UInt32)device_channel + 1));}}static void Main(string[] args){Canlib.canInitializeLibrary();ListChannels();// Press any key to continueConsole.ReadKey(true);}}
}

封装一下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Kvaser.CanLib;namespace MyCan.Demo.Core
{public class CanHelper{ // When called CheckForError will check for and print any error.// Return true if an error has occured.public static bool CheckForError(string cmd, Canlib.canStatus stat){if (stat != Canlib.canStatus.canOK){Canlib.canGetErrorText(stat, out string buf);Console.WriteLine("[{0}] {1}: failed, stat={2}", cmd, buf, (int)stat);return true;}return false;}// ListChannels prints a list of all connected CAN interfaces.public static void ListChannels(){Canlib.canStatus stat;// Get number channelsstat = Canlib.canGetNumberOfChannels(out int number_of_channels);if (CheckForError("canGetNumberOfChannels", stat))return;Console.WriteLine("Found {0} channels", number_of_channels);// Loop and print all channelsfor (int i = 0; i < number_of_channels; i++){stat = Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_DEVDESCR_ASCII, out object device_name);if (CheckForError("canGetChannelData", stat))return;stat = Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHAN_NO_ON_CARD, out object device_channel);if (CheckForError("canGetChannelData", stat))return;Console.WriteLine("Found channel: {0} {1} {2}", i, device_name, ((UInt32)device_channel + 1));}}private static AutoResetEvent autoResetEvent = new AutoResetEvent(false);public static void canInitializeLibrary(){Canlib.canInitializeLibrary();ListChannels();// Press any key to continue
            autoResetEvent.WaitOne();}}
}

新建控制台程序调用

 

CanHelper.canInitializeLibrary();

提示

 其他:发送数据案例

// This tutorial walks you through how to open a channel and send a CAN message on it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kvaser.CanLib;
namespace SendMessage
{class Program{static void Main(string[] args){// Holds a handle to the CAN channelint handle;// Status returned by the Canlib calls
            Canlib.canStatus status;// The CANlib channel number we would like to useint channelNumber = 0;// The msg will be the body of the message we send on the CAN bus.byte[] msg = {0, 1, 2, 3, 4, 5, 6, 7};Console.OutputEncoding = System.Text.Encoding.UTF8;Console.WriteLine("Initializing Canlib");// Initialize the Canlib library with a call to// Canlib.initializeLibrary(). This always needs to be done before// doing anything with the library.
            Canlib.canInitializeLibrary();Console.WriteLine("Opening channel {0}", channelNumber);// Next, we open up the channel and receive a handle to// it. Depending on what devices you have connected to your// computer, you might want to change the channel number. The// canOPEN_ACCEPT_VIRTUAL flag means that it is ok to open the// selected channel, even if it is on a virtual device.handle = Canlib.canOpenChannel(channelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);CheckStatus((Canlib.canStatus)handle, "canOpenChannel");Console.WriteLine("Setting channel bitrate");// Once we have successfully opened a channel, we need to set its bitrate. We// do this using canSetBusParams. CANlib provides a set of predefined bus parameter// settings in the form of canBITRATE_XXX constants. For other desired bus speeds// bus paramters have to be set manually.// See CANlib documentation for more information on parameter settings.status = Canlib.canSetBusParams(handle, Canlib.canBITRATE_250K, 0, 0, 0, 0);CheckStatus(status, "canSetBusParams");Console.WriteLine("Going on bus");// Next, take the channel on bus using the canBusOn method. This// needs to be done before we can send a message.status = Canlib.canBusOn(handle);CheckStatus(status, "canBusOn");Console.WriteLine("Writing a message to the channel");// We send the message using canWrite. This method takes five// parameters: the channel handle, the message identifier, the// message body, the message length (in bytes) and optional flags.status = Canlib.canWrite(handle, 123, msg, 8, 0);CheckStatus(status, "canWrite");Console.WriteLine("Waiting for the message to be transmitted");// After sending, we wait for at most 1000 ms for the message to be sent, using// canWriteSync.status = Canlib.canWriteSync(handle, 1000);CheckStatus(status, "canWriteSync");Console.WriteLine("Going off bus");// Once we are done using the channel, we go off bus using the// canBusOff method. It take the handle as the only argument.status = Canlib.canBusOff(handle);CheckStatus(status, "canBusOff");Console.WriteLine("Closing channel {0}", channelNumber);// We also close the channel using the canCloseChannel method,// which take the handle as the only argument.status = Canlib.canClose(handle);CheckStatus(status, "canClose");// Wait for the user to press a key before exiting, in case the// console closes automatically on exit.Console.WriteLine("Press any key to exit");Console.ReadKey();}// The check method takes a canStatus (which is an enumerable) and the method// name as a string argument. If the status is an error code, it will print it.// Most Canlib method return a status, and checking it with a method like this// is a useful practice to avoid code duplication.private static void CheckStatus(Canlib.canStatus status, string method){if (status < 0){string errorText;Canlib.canGetErrorText(status, out errorText);Console.WriteLine(method + " failed: " + errorText);}}}
}
/*Exercises:- The canWriteWait method combines canWrite with canWriteSync. Try it out.- Use some other program (such as Kvaser CanKing) to listen for messages on achannel connected to the one used in the program. Make sure to use the samebitrate.- Change the fourth parameter in the call to canWrite to 4. What happens tothe message on the receiving side?- Change the message identifier to something large, like 10000. What happenson the receiving side? Then, change the fifth parameter toCanlib.canMSG_EXT. What happens now?
*/

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/793930.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Cursor一键导入vscode插件以及设置

在cursor中找到 setting-- general -- vscode import 导入配置,一键导入即可

时间序列结构变化分析:Python实现时间序列变化点检测

平稳性是时间序列分析与预测的核心概念。在平稳条件下,时间序列的统计特性(如均值)在时间维度上保持不变,仅存在随机波动。 但是实际数据集中很少观察到完全的平稳性。时间序列通常会经历结构性断裂或变化。这些变化会引入非平稳性,从而改变时间序列的整体分布,这些标志着…

RuoYi框架部分历史漏洞

RuoYi框架部分历史漏洞 生产环境搭建(代码审计)项目地址:若依 (y_project) - Gitee.com 官方文档:RuoYi项目构成 因为RuoYi框架是基于SpringBoot搭建的,所以我们启动项目时不用像SpringMVC那样去配置我们的服务器然后把项目放到服务器上启动。我们成功导入项目之后会生成一些…

ROS话题通信和服务通信的区别

话题和服务是 ROS 中使用最多的通信方法,它们之间有很多不同之处:

分治

由 ryz 讲解 什么是分治?把一个较大规模的问题分成若干个较小规模的问题。小规模的问题与原问题不同(根号分治)小规模的问题与原问题相同(对数分治)二分就是一种对数分治的方法。 操作序列分治 cdq 分治 修改和询问的整体分治也被称为 cdq 分治。 要求:修改对询问具有可加…

Docker 镜像的发布过程

搭建了一个镜像后(例如搭建好了一个开发环境),如果想要供其他人使用,此时就可以发布镜像到镜像仓库。本文就试着将本地的镜像,发布到阿里云。搭建了一个镜像后(例如搭建好了一个开发环境),如果想要供其他人使用,此时就可以发布镜像到镜像仓库。 本文就试着将本地的镜像…

VI源的基本概念

V/I源的基本概念 1.1 基本概念 通用直流电压电流源是一种线性电源,也称为四象限可编程电压电流源,主要用于各种自动测试设备(Automated Test Equipment,ATE)或自动测试系统(Automatic Test System, ATS),英文名称为Voltage/Current Source(V/I Source),在本书中简称…

Swagger/OpenAPI Client Generator for Delphi and FPC

Delphi和FPC的Swagger/OpenAPI客户端生成器 Swagger/OpenAPI Client Generator for Delphi and FPC Swagger/OpenAPI 是一种用于描述和定义RESTful API的规范和工具集。具体来说,它们提供了以下关键特性和作用: 一、定义与背景Swagger :最初是一种用于描述RESTful API的规范…

数据包格式

近来常思,不应止步于此,可自觉进阶缓慢,一筹莫展,就打算自废武功复习一下,那就从状态码开始吧。前言近来常思,不应止步于此,可自觉进阶缓慢,一筹莫展,就打算自废武功复习一下,那就从状态码开始吧。 由于强迫症患者,所以后面就顺便把数据包格式啥的都一起写一下吧。请…

英特尔FPGA深度学习加速(DLA)套件

英特尔FPGA深度学习加速(DLA)套件英特尔FPGA的DLA加速套件,如图11-17所示。图11-17 英特尔FPGA的DLA加速套件 深度学习部署工具包(DLDT)中的推理引擎,提供了一个高级的设备无关API来编程推理。这是一些示例代码,如图11-18所示。图11-18 深度学习部署工具包(DLDT)中的推…