2010-10-13 77 views
0

我正在使用C#SerialPort类写入我的COM端口。奇怪的是,我可以从端口获取数据 - 它发送我期待的数据。但是,我无法将任何数据发送到端口。我发送的任何数据都立即作为来自端口的新数据回显给我。我期待着一个“完成”的命令,但它将我刚刚发送的数据还给我。它从Windows HyperTerminal运行得很好,但是这个代码不起作用。C#SerialPort WriteLine命令错误

我使用9600,8-N-1无流量控制。

我主要使用代码这篇文章:

我实例化我的端口与此

comPort.BaudRate = int.Parse(_baudRate); //BaudRate 
comPort.DataBits = int.Parse(_dataBits); //DataBits 
comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits); //StopBits 
comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity); //Parity 
comPort.PortName = _portName; //PortName 
comPort.Handshake = Handshake.None; 
comPort.ReadTimeout = 2000; 
comPort.RtsEnable = true; 
//now open the port 
comPort.Open(); 

和写只是使用comport.write(串),我以前也用过COMPORT .writeline(字符串)具有相同的结果。

此代码与普通香草超级终端之间的主要区别是什么,会导致它们的行为不同?

+0

对不起,意在包括链接到这篇文章,其中大部分来自:http://www.dreamincode.net/forums/topic/35775-serial-port-communication-in-c%23/ – 2010-10-13 22:20:00

回答

2

我偶然发现了许多代码示例中没有的答案。底线是你必须在每个端口写入时包含一个回车符。我用的是:

comport.write(string) 

但它应该是

comport.write(string+"\r\n") 

你不会相信许多代码示例如何没能有一个代码。我偶然发现了一个包含它的随机片段,这是不同的。