首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

请问Port通讯有关问题!

2012-08-14 
请教Port通讯问题!!!代码如下:C# codeprivate Queuestring RobotBy new Queuestring() // received

请教Port通讯问题!!!
代码如下:

C# code
private Queue<string> RobotBy = new Queue<string>(); // received data . robotprivate bool SendDataToRobot(string DataStr){                bool rut = false;            string sendDataFormat;            try            {                if (!serialPort_Robot.IsOpen)                {                    string portName = System.IO.Ports.SerialPort.GetPortNames().Where(pName => (pName == serialPort_Robot.PortName)).First();                    if (string.IsNullOrEmpty(portName))                    {                        WriteLog(string.Format("port '{0}' is denied", serialPort_Robot.PortName));                        throw new Exception(string.Format("port '{0}' is denied", serialPort_Robot.PortName));                    }                    serialPort_Robot.Open();                }            }            catch (Exception err)            {                WriteLog(string.Format("Open Robot Port Exception Message:{0}", err.Message));                throw new Exception(err.Message);            }    if (serialPort_Robot.IsOpen && !!string.IsNullOrEmpty(DataStr))        {        try{        serialPort_Robot.DiscardOutBuffer();                byte[] buf = Encoding.ASCII.GetBytes(DataStr.ToString());                serialPort_Robot.Write(buf, 0, buf.Length);        }catch(Exception e)        {            throw new Exception("Write Data to Robot Error,message:"+ e.Message);        }    }}public MainForm(){serialPort_Robot.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SerialPort_RobotDataReceived);}private void SerialPort_RobotDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)        {            try            {                RobotBy.Enqueue(serialPort_Robot.ReadTo("\x001a"));                serialPort_Robot.Close();            }            catch (IOException se)            {                WriteLog(string.Format(                    "Robot receivedata {0} : The write operation could not be performed because the specified part of the file is locked.",                    se.GetType().Name)                    );            }        }


问题在调用 SendDataToRobot(string DataStr) 的时候会出现 "Open Robot Port Exception Message:Access to the port 'COM7' is denied." ,弄了好久没弄好,请教高手..

[解决办法]
也许你COM口关闭了,线程还是再访问这个端口,建议先关闭timer,线程,然后注销端口
[解决办法]
不是同步没做好,重复调用 serialPort_Robot.Open()
[解决办法]
如楼上
你应该把open独立出来,并不是每发送一个数据,就打开一次。一个过程打开一次就可以了,甚至说,程序已运行就新型初始化,然后一直保持打开状态。你发送就好了。

热点排行