Access to port is denied

I am trying to communicate from visual studio with my arduino, but every time I run my cod I get this error.

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

// ArduinoComm.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::IO::Ports;

int main(array<System::String ^> ^args)
{
	
	String^ answer;
	String^ portName;
	int baudRate=9600;
	Console::WriteLine("Type in a port name and hit ENTER");
	portName=Console::ReadLine();
	// arduino settings
	SerialPort^ arduino;
	arduino = gcnew SerialPort(portName, baudRate);
	// open port
	try
	{
		arduino->Open();

		do
		{
			// ask on or off
			Console::WriteLine("Type \"on\" to turn the light on or \"off\" to turn it off");
			// get answer
			answer=Console::ReadLine();
			//check that user typed one of the options
			if(String::Compare(answer,"on")==0)
				arduino->WriteLine("1"); // send 1 to arduino
			else if(String::Compare(answer,"off")==0)
				arduino->WriteLine("0"); // send 0 to arduino
			else
				Console::WriteLine(answer+" was not an option");
			// ask user if he wants to continue
			Console::WriteLine("Try again? yes/no");
			// get answer
			answer=Console::ReadLine();
			// clear the screen
			Console::Clear();
		}while(String::Compare(answer,"yes")==0);
		// close port to arduino
		arduino->Close();
	}
	catch (IO::IOException^ e  ) 
	{ 
		Console::WriteLine(e->GetType()->Name+": Port is not ready");
	}
	catch (ArgumentException^ e)
	{
		Console::WriteLine(e->GetType()->Name+": incorrect port name syntax, must start with COM/com");
	}
	// end program
	Console::Write("Press enter to close the program");
	Console::Read();
    return 0;
}

I used this code from a website: Arduino Serial Communication With C++ Tutorial
It seems other people got it to work, so I'm not quite sure why I'm getting this error.

Here is my arduino code:

//Some content from SFE_TSL2561 example from SparkFun Electronics
#include <SFE_TSL2561.h>
#include <Wire.h>


//Creat an SFE_TSL2561 object
SFE_TSL2561 light;

//Global variables:

boolean gain; //Gain setting, 0=X1, 1=X16;
unsigned int ms; //Integration ("shutter") time in ms

void setup()
{
  //Initialize the Serial port:
  Serial.begin(9600);
  
  //Initialize the SFE_TSL2561 library
  light.begin();
  
  //If gain=false(0), device is set to low gain(1X)
  //If gain=high (1), device is set to high gain (16X)
  gain = 0;
  
  //If time = 0, integration will be 13.7ms
  //If time = 1, integration will be 101ms
  //If time = 2, integration will be 402ms
  //If time = 3, use maunal start / stop to perform own integration
  
  unsigned char time = 2;
  //SetTiming() will set the third parameter (ms) to the requested
  //integration time in ms
  Serial.println("Set timing...");
  light.setTiming(gain,time,ms);
  
  //Power the sensor (To start taking measurements)
  Serial.println("Powerup...");
  light.setPowerUp();
}

void loop(){
  char measurement=0;
  unsigned int data0, data1;
  
  //read Serial port, when camera has triggered
  if (Serial.available()=='A')
  {
  
    if (light.getData(data0,data1))
    {
      //getData() return true, communication was successful
      Serial.print("data0: ");
      Serial.print(data0);
      Serial.print(" data1: ");
      Serial.print(data1);
      
      //To calculate lux, pass all your settings and readings to the getLux() function
      double lux;    //resulting lux value
      boolean good;  //true if neither sensor is saturated
      
      //Perform lux calculation
      
      good=light.getLux(gain,ms, data0,data1,lux);
      
      //Print results
      
      Serial.print(" lux: ");
      Serial.print(lux);
        if(good) Serial.println(" (good)"); else Serial.println(" (BAD)");
     }
   else
     {
     //getData() returned false because of an I2C error
     
     byte error = light.getError();
     printError(error);
     }
  }
}

void printError (byte error)

//This funtion tells the user if there is an I2C error
{
  Serial.print("I2C error: ");
  Serial.print(error,DEC);
  Serial.print(", ");
  
  switch (error)
    {
      case 0:
        Serial.println("success");
        break;
      case 1:
        Serial.println("data too long for transmit buffer");
        break;
      case 2:
        Serial.println("received NACK on address (disconnected?)");
        break;
      case 3:
        Serial.println("received NACK on data");
        break;
      case 4:
        Serial.println("other error");
        break;
      default:
        Serial.println("unknown error");
    }
}

Do you have the Arduino IDE open & using COM3?

Yes, I do...At least I think I do.
When I tried it without the Arduino connected it told me Port not ready, so this is different I think.

It sounds like the Arduino IDE and your VS program are both trying to use the same COM port. Close the IDE while you try to run the VS stuff.

Or at least, close the serial monitor.

Great that works!
I'm still fairly new to this, but now how do I read the value that was measured by the arduino with the serial monitor closed?

cassmoney28:
how do I read the value that was measured by the arduino with the serial monitor closed?

Only one application at a time can connect to the serial port. If you need your client application to connect to it for some reason, then nothing else can connect to it at the same time. If your Arduino is going to produce some output as a result of the client connecting to it, then you could use your client to read that output and print it to the local console, so that you can see it.

By the way, are you aware that by default opening the serial port would usually cause the Arduino to reset?

I'm still fairly new to this, but now how do I read the value that was measured by the arduino with the serial monitor closed?

Using the same application that WROTE to the serial port would seem reasonable, wouldn't it?

By the way, are you aware that by default opening the serial port would usually cause the Arduino to reset?

I was not aware. Is there anything I can do about this?

Is there anything I can do about this?

You can read the forum, where this issue is regularly discussed.

If you meant "Is there anything I can do about the reset?", then yes there is IF it's a problem. You haven't defined that it is a problem, yet.

Awesome. Thank you all for the help.

The reset is triggered by the toggling of serial port control lines when the port is opened. It's possible to write a client in such a way that the signal lines do not get toggled, which avoids the reset. I don't know whether your application is coded like that. It's also possible to make a hardware modification to the board to suppress the reset. Note that the normal method of uploading sketches to the board via the serial port relies on this reset, so if you inhibit it you will find it harder to program the board.

hey, to come back to this question. I think I've figured out for the most part everything. Now, I am just trying to read the data from the Arduino into my C++ code, but I am not quite sure how to do this. Any help would be greatly appreciated.

cassmoney28:
I am just trying to read the data from the Arduino into my C++ code, but I am not quite sure how to do this.

Have you tried searching for clues? Googling for things like "how to read a serial port in windows using C++" turns up loads of answers. You would need to select the ones relating to whatever runtime library you were using.

Yes, but what I've tried hasn't given me anything.

arduino->Open();
			// Take measurement
			Console::WriteLine("Type \"go\" to measure");
			// get answer
			answer=Console::ReadLine();
			//check that user typed one of the options
			if(String::Compare(answer,"go")==0)
				arduino->WriteLine("A"); // send A to arduino
			else
				Console::WriteLine(answer+" was not an option");
		// close port to arduino
		arduino->Close();

I'm just not sure what to add to this section so I can see the response from the serial port.

cassmoney28:
I'm just not sure what to add to this section so I can see the response from the serial port.

I'm puzzled that your Googling hasn't turned up a tutorial. Have you tried searching for the exact search string I suggested? It seems like a reasonably precise question, and when I do that search I get loads of relevant hits. Here is one that appeared near the top of the list: