VDG
VDG

Reputation: 83

C# access denied when trying to access communications port?

I'm trying to make a simple Windows Form Application in Visual Studios that will allow me to control the brightness setting of an LED strip hooked up to an Arduino.

The programming inside the Arduino is already well and done, but the C# programming is what's giving me trouble.

When trying to send strings of information through the port, I receive the following message:

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

Here is the piece of code that is giving me trouble:

  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);
        }
    }

I haven't included any closing of the port because first I want to get this to work, and I'm not understanding what's going on. I'm pretty sure no other applications are using the port; the Arduino is plugged in to it via USB in order to receive it's power but other than that, it's not receiving or transmitting from any other process.

I've tried changing the port from COM3 to other ports, which is one of the main solutions given for similar questions, but still I get the same result.

Thanks for the help.

Upvotes: 2

Views: 10171

Answers (2)

Gilad
Gilad

Reputation: 353

This was answered in one of the comments by N.K: Make sure the Serial Monitor is not working.

Upvotes: 2

AVee
AVee

Reputation: 3402

The most common cause of Access Denied errors on COM ports is the COM port already being opened by some other program. You can use portmon to see which program that is. It could well be your own program since you never properly close the port.

Upvotes: 3

Related Questions