简体   繁体   English

写入C#或python上的COM端口

[英]Writing to COM port on C# or python

im trying to write a string to a COM4 which is a usb-serial adapter using Visual Studio C# and got the following error: 我试图使用Visual Studio C#将字符串写入COM4,这是一个usb-serial适配器,并出现以下错误:

Access to the port 'COM4' is denied. 访问端口“COM4”被拒绝。

My program is extremely simple: 我的程序非常简单:

serialport.Open();
serialport.WriteLine("test");
serialport.Close();

I also tried using pyserial with python and got: 我也尝试使用pyserial和python并得到:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    ser.write("string")
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 255, in write
    raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
SerialException: WriteFile failed ([Error 6] The handle is invalid.)

I know this question isn't really related to programming and is probably a Windows 7 thing but I was hoping someone has already had a similar problem. 我知道这个问题与编程没有关系,可能是一个Windows 7的东西,但我希望有人已经有类似的问题。

Try this: 尝试这个:

Right click on your executable and choose "run as administrator". 右键单击您的可执行文件并选择“以管理员身份运行”。 Windows 7 by default runs programs without admin privileges. Windows 7默认情况下运行没有管理员权限的程序。 I'm betting that the ability to write to a COM port requires running a program as an Administrator. 我打赌写入COM端口的能力需要以管理员身份运行程序。

You cannot have multiple simultaneous connections to a serial port. 您不能同时连接多个串行端口。 The port is likely in use. 该端口可能正在使用中。

It had nothing to do with permissions neither with the port being in use. 它与使用端口的权限无关。 I found a related question which said it was because of the version I had installed (64 bit Python and 32 bit pyserial) I feel so silly. 我发现了一个相关的问题 ,说是因为我安装的版本(64位Python和32位pyserial)我觉得很傻。

What I still can't figure out is why it also didn't work on C# but that's OK. 我仍然无法弄清楚为什么它也没有在C#上工作,但那没关系。 I'll just use python. 我只会使用python。

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

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