View Full Version : Access Denied to Port??!!

08-23-2010, 03:28 AM
Hi all,

I'm currently using Visual C# to read IR distance sensors and display measurements on a plot in real time. My code is below:

using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using RoboticsConnection.Serializer;
using RoboticsConnection.Serializer.Ids;
using RoboticsConnection.Serializer.Sensors;
using RoboticsConnection.Serializer.Components;

namespace WindowsFormsApplication1
public partial class Form1 : Form
public Form1()

static Serializer serializer;

static GP2D12 leftIr;
private Random random = new Random();
private int pointIndex = 0;

private void timer1_Tick(object sender, EventArgs e)
{ // Define some variables

int numberOfPointsInChart = 200;
int numberOfPointsAfterRemoval = 150;
double leftdistance = 0;
serializer = new Serializer();
serializer.PortName = "COM14";
serializer.BaudRate = 19200;
leftIr = new GP2D12(serializer);
leftIr.Pin = AnalogPinId.Pin0;
leftIr.Enabled = false;


//adding new data points
int numberOfPointsAddedMin = 5;
int numberOfPointsAddedMax = 10;
for (int pointNumber = 0; pointNumber < random.Next(numberOfPointsAddedMin, numberOfPointsAddedMax); pointNumber++)
leftdistance = leftIr.Distance;
chart1.Series[0].Points.AddXY(pointIndex + 1, leftdistance);

// Adjust Y & X axis scale

// Keep a constant number of points by removing them from the left
while (chart1.Series[0].Points.Count > numberOfPointsInChart)
// Remove data points on the left side
while (chart1.Series[0].Points.Count > numberOfPointsAfterRemoval)


// Invalidate chart


The problem is, at the "startcommunication" line, the code stops debugging and an error comes out..."access to port 14 is denied". Would anyone know the reason to this? I'm absolutely sure port 14 is the right port. By the way, if anyone sees a reason that this code may not give me what I wanted, please point that out too.

Thanks a ton!

08-23-2010, 09:14 AM
The port is probably already open or the context that your code is is running under does not have access to the resource. Probably an open port from a downstream error. Just a guess because I don't see any error handling in your code.

If you have a USB to serial device, unplug it, wait a few seconds and try again. For troubleshooting purposes you should create a simple serialport connection using the framework's serialport object. This will isolate the serial connection and help you figure out where the problem is located.

Edit: It's because you're trying to open the port each time the "private void timer1_Tick(object sender, EventArgs e)" event handler fires. Instantiate the serializer (and port) outside "private void timer1_Tick(object sender, EventArgs e)". I would encapsulate the port connection logic.

You could close the port at the end of the event but that might (will) cause problems later updating the GUI as the Rx is spun on a secondary thread.