我正在尝试在 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/