SerialPort WriteLine命令的C#错误

时间:2010-10-13 22:14:56

标签: c# serial-port

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

我使用的是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();

而write只是使用comport.write(string)而且我也使用了comport.writeline(string),结果相同。

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

1 个答案:

答案 0 :(得分:2)

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

comport.write(string)

但它应该是

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

你不会相信代码中有多少代码示例没有。我遇到了一个包含它的随机片段,这就是区别。