以下代码正在构建且没有错误,但是当我运行程序时,接收到的数据未显示在输出中。当我在上放置断点时,myReceivedLines = port.ReadExisting();
我得到:
System.InvalidOperationException
.
在程序本身中,重新启动我的计算机后它说:
Access to COM5 is denied
我能做些什么来解决这个问题?
代码:
//Fields
SerialPort port;
string myReceivedLines;
protected override void SolveInstance(IGH_DataAccess DA)
{
List<string> gcode = new List<string>();
DA.GetDataList(0, gcode);
string selectedportname = default(string);
DA.GetData(1, ref selectedportname);
int selectedbaudrate = default(int);
DA.GetData(2, ref selectedbaudrate);
bool connecttodevice=default(bool);
DA.GetData(3, ref connecttodevice);
bool sendtoprint= default(bool);
DA.GetData(4, ref sendtoprint);
if (!DA.GetDataList(0, gcode)) return;
if (!DA.GetData(1, ref selectedportname)) return;
if (!DA.GetData(2, ref selectedbaudrate)) return;
if (!DA.GetData(3, ref connecttodevice)) return;
if (!DA.GetData(4, ref sendtoprint)) return;
port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
port.DtrEnable = true; //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
port.Open(); //Open the port
port.DataReceived += this.portdatareceived;
if (gcode == null)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
return;
}
if (connecttodevice == true)
{
DA.SetDataList(0, myReceivedLines);
}
if (sendtoprint == true)
{
foreach (String s in gcode)
{
port.WriteLine(s);
}
}
}
//subscriber method for the port.DataReceived Event
private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
myReceivedLines = port.ReadExisting();
}