Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Access to the port 'COM4' is denied.

My program is extremely simple:

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

I also tried using pyserial with python and got:

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.

like image 744
kirbuchi Avatar asked Feb 02 '26 14:02

kirbuchi


2 Answers

Try this:

Right click on your executable and choose "run as administrator". Windows 7 by default runs programs without admin privileges. I'm betting that the ability to write to a COM port requires running a program as an Administrator.

like image 149
Turtle Avatar answered Feb 05 '26 03:02

Turtle


You cannot have multiple simultaneous connections to a serial port. The port is likely in use.

like image 43
Ed S. Avatar answered Feb 05 '26 04:02

Ed S.