首页 > 编程语言 >C# kvaser can 通讯

C# kvaser can 通讯

时间:2024-09-08 09:48:24浏览次数:1  
标签:status stat 通讯 Console C# Canlib using kvaser channel

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 channels
            stat = Canlib.canGetNumberOfChannels(out int number_of_channels);
            if (CheckForError("canGetNumberOfChannels", stat))
                return;
            Console.WriteLine("Found {0} channels", number_of_channels);
            // Loop and print all channels
            for (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 continue
            Console.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 channels
            stat = Canlib.canGetNumberOfChannels(out int number_of_channels);
            if (CheckForError("canGetNumberOfChannels", stat))
                return;
            Console.WriteLine("Found {0} channels", number_of_channels);
            // Loop and print all channels
            for (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 channel
            int handle;
            // Status returned by the Canlib calls
            Canlib.canStatus status;
            // The CANlib channel number we would like to use
            int 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 a
    channel connected to the one used in the program. Make sure to use the same
    bitrate.
  - Change the fourth parameter in the call to canWrite to 4. What happens to
    the message on the receiving side?
  - Change the message identifier to something large, like 10000. What happens
    on the receiving side? Then, change the fifth parameter to
    Canlib.canMSG_EXT. What happens now?
*/

 kvaser can 官方其他can  .netcore的博客文章

Using CANlib Visual Studio 2019 C# .NET STANDARD 2.0 - Kvaser

标签:status,stat,通讯,Console,C#,Canlib,using,kvaser,channel
From: https://www.cnblogs.com/JohnnyLei/p/18402222

相关文章

  • 自动化运维工具之WGCLOUD使用操作指南,为服务器安全保驾护航
    WGCLOUD官网下载安装包:www.wgstart.com 1、部署WGCLOUD运行的前置条件说明WGCLOUD包括:server为服务端(或主控端),agent为客户端(探针端、被控端)WGCLOUD的server和agent,可以部署在已有业务运行的主机,不要求主机是纯净的操作系统。当然了,纯净的系统也可以部署WGCLOUDWGCLOUD是绿色......
  • SAP S/4HANA Cloud:云端企业资源规划的未来
     在数字化转型的浪潮中,SAPS/4HANACloud作为SAP公司推出的一款云端ERP解决方案,正成为企业资源规划的新宠。它不仅提供了传统ERP系统的所有功能,还通过云端技术为企业带来了更高的灵活性和可扩展性。   SAPS/4HANACloud的核心优势SAPS/4HANACloud的优势在于其强大的......
  • docker php和nginx的通信
    1安装网络dockernetworkcreatephpClassExamples_network2安装nginx2.1生成临时容器dockerrun-it--nametest_nginx-dnginx查看临时容器内部,找到关键目录1、工作目录:lsusr/share/nginx/html 2、配置目录lsetc/nginx/conf.d3、日志目录lsvar......
  • vscode中使用go环境配置细节
    1、在docker容器中下载了go的sdk2、在/etc/profile.d/go.sh里填入如下内容:#!/bin/bashexportGOROOT=/home/ud_dev/goexportPATH=$GOROOT/bin:$PATH 3、设置goenvgoenv-wGOPROXY=https://goproxy.cn,directgoenv-wGO111MODULE=on4、重启这个容器,使得vscode......
  • PLC(电力载波通信)网络机制介绍
    1.概述1.1什么是PLC电力载波通讯即PLC,是英文PowerlineCarrier的简称。电力载波是电力系统特有的通信方式,电力载波通讯是指利用现有电力线,通过载波方式将模拟或数字信号进行高速传输的技术。最大特点是不需要重新架设网络,只要有电线,就能进行数据传递。 名词解释:相位:C......
  • 猎豹算法(CO)优化BP神经网络原理及Matlab代码
    目录0引言1数学模型2优化方式3Maltab代码3.1伪代码3.2CO主函数代码3.3CO-BP4视频讲解0引言猎豹算法(cheetahoptimizer,CO)是MohammadAminAkbari于2022年基于猎豹的狩猎策略启发而提出的智能算法。CO模拟猎豹的三种主要策略来捕猎猎物,即搜索、坐着和攻击;同时......
  • 猎豹算法(CO)优化支持向量机原理及Matlab代码
    目录0引言1数学模型2优化方式3Maltab代码3.1伪代码3.2CO主函数代码3.3CO-SVM4视频讲解0引言猎豹算法(cheetahoptimizer,CO)是MohammadAminAkbari于2022年基于猎豹的狩猎策略启发而提出的智能算法。CO模拟猎豹的三种主要策略来捕猎猎物,即搜索、坐着和攻击;同时......
  • 猎豹算法(CO)优化长短期记忆神经网络原理及Matlab代码
    目录0引言1数学模型2优化方式3Maltab代码3.1伪代码3.2CO主函数代码3.3CO-LSTM4视频讲解0引言猎豹算法(cheetahoptimizer,CO)是MohammadAminAkbari于2022年基于猎豹的狩猎策略启发而提出的智能算法。CO模拟猎豹的三种主要策略来捕猎猎物,即搜索、坐着和攻击;同......
  • JDBC创建数据库实例
    在本教程将演示如何在JDBC应用程序中创建数据库。在执行以下示例之前,请确保您已经准备好以下操作:具有数据库管理员权限,以在给定模式中创建数据库。要执行以下示例,需要用实际用户名和密码替换这里用户名(username)和密码(password)。MySQL或数据库已启动并运行。所需步骤使......
  • JDBC流ASCII和二进制数据
    PreparedStatement对象可以使用输入和输出流来提供参数数据。能够将整个文件放入可以容纳大值的数据库列,例如CLOB和BLOB数据类型。有以下方法可用于流式传输数据-setAsciiStream():此方法用于提供大的ASCII值。setCharacterStream():此方法用于提供较大的UNICODE值。setBinary......