尝试访问通信端口时 C# 访问被拒绝?

标签 c# arduino serial-port

我正在尝试在 Visual Studios 中制作一个简单的 Windows 窗体应用程序,它允许我控制连接到 Arduino 的 LED 灯带的亮度设置。

Arduino 内部的编程已经很好完成,但 C# 编程却给我带来了麻烦。

当尝试通过端口发送信息字符串时,我收到以下消息:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll . Additional information: Access to the port 'COM3' is denied.

这是给我带来麻烦的代码:

  private void trackBar1_Scroll(object sender, EventArgs e)
    {    
        String color = trackBar1.Value.ToString();

        System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort("COM3");
        if (myPort.IsOpen == false){
         //if not open, open the port
            myPort.Open(); // Error is shown here.
        }
        if (myPort.IsOpen){
            myPort.WriteLine(color);
        }
    }

我没有包括任何端口的关闭,因为首先我想让它工作,但我不明白发生了什么。我很确定没有其他应用程序正在使用该端口; Arduino 通过 USB 插入它以接收电源,但除此之外,它不从任何其他进程接收或传输。

我尝试将端口从 COM3 更改为其他端口,这是针对类似问题给出的主要解决方案之一,但我仍然得到相同的结果。

感谢您的帮助。

最佳答案

COM 端口上拒绝访问错误的最常见原因是 COM 端口已被其他程序打开。您可以使用portmon看看是哪个程序。它很可能是您自己的程序,因为您从未正确关闭端口。

关于尝试访问通信端口时 C# 访问被拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31104809/

相关文章:

c# - 在 API 调用上显示等待或微调器

c# - 存储库和使用原始 sql 查询?

c# - 领域类应该如何设计?

c# - 值的范围 - 如何在没有 if 循环的情况下确定?

node.js - 如何将皮诺奇连接到 apache couchdb

java - 将使用Processing.org制作的应用程序迁移到Eclipse

c++ - 为 'virtual void' 指定的返回类型有冲突

arduino - server.args() ESP8266 Arduino

linux - 使用 UART 进行流量控制

c++ - C 或 C++ 中的 Com 端口库