简体   繁体   English

如何获取值并使用C#侦听COM2端口?

[英]How to get the value and listen to the COM2 port using C#?

I'm working with Dallas Key which is wired on the COM2 port. 我正在使用连接在COM2端口上的Dallas Key。 The dallas Key has a value when it's ON (for example 00 AA BB) and a value when it's removed (for example 00 00 00). 达拉斯密钥打开时有一个值(例如00 AA BB),而删除它时有一个值(例如00 00 00)。 How can I ready continuously the value of the COM2 port in order to detect it's change and take actions based on it ( winforms application ). 我如何连续准备COM2端口的值,以便检测到它的变化并基于它进行操作(winforms应用程序)。

I've tried to get the value by port name and read it but it says access denied in some cases. 我试图通过端口名称获取值并读取它,但是它表示在某些情况下访问被拒绝。

private SerialPort port = new   SerialPort("COM2",9600, Parity.None, 8, StopBits.One); 

   static void Main(string[] args) 
    { 
      SerialPortProgram(); 
    } 

private static void SerialPortProgram() 
    { 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        port.Open(); 
        Console.ReadLine();
     } 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
       Console.WriteLine(port.ReadExisting()); 
    } 

I want to listen to the COM2 port value all the time without having a big impact on the application speed, get the value of the COM2 port (my dallas key) when it is ON and detect when it is off and take specific action. 我想一直监听COM2端口的值,而又不影响应用程序速度,打开时获取COM2端口的值(我的达拉斯密钥),并检测它何时关闭并采取特定措施。

Even though you didn't describe what line actually throws, by reading the documentation i found this nuget 即使您没有描述实际抛出的行,但通过阅读文档我发现了这个细节

SerialPort.Open Method SerialPort.Open方法

Exceptions UnauthorizedAccessException Access is denied to the port. 异常 UnauthorizedAccessException拒绝对端口的访问。

-or- -要么-

The current process, or another process on the system, already has the specified COM port open either by a SerialPort instance or in unmanaged code. 当前进程或系统上的另一个进程已经通过SerialPort实例或非托管代码打开了指定的COM端口。

You either don't have permission to open the port, or you already have it open, you need to figure out which one it is and deal with it appropriately 您或者没有打开端口的权限,或者您已经打开了端口,您需要确定端口是哪一个并进行适当处理

Note : com ports can be a bit fickle if you are using usb to com 注意 :如果您使用USB来进行com通讯,端口可能会有些变

The below code works when I write in console (Project is Console Application) but when I changed back to Windows Application and try to write in a label or change a variable value: this doesn't work: 下面的代码在我用控制台(项目是控制台应用程序)编写时起作用,但是当我改回到Windows应用程序并尝试写标签或更改变量值时,此代码不起作用:

    public Form1()
    {
        InitializeComponent();
        SerialPortProgram();
    }

    private void SerialPortProgram()
    {
        SerialPort mySerialPort = new SerialPort("COM2");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        mySerialPort.Open();
        mySerialPort.Close();
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        switch (ASCIItoHex(indata))
        {
            case "00000113":
                LB_Display.Text = "User 1";
                break;
            case "0000017a":
                LB_Display.Text = "User 2";
                break;
            default:
                LB_Display.Text = "Disconnect";
                break;
        }
    }

    public static string ASCIItoHex(string Value)
    {
        StringBuilder sb = new StringBuilder();
        foreach (byte b in Value)
            sb.Append(string.Format("{0:x2}", b));
        return sb.ToString();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM