SerialPort WriteLine 命令的 C# 错误
我正在使用 C# SerialPort 类写入我的 COM 端口。奇怪的是,我可以很好地从端口获取数据 - 它发送我期望的数据。但是,我无法向该端口发送任何数据。我发送的任何数据都会立即作为来自端口的新数据回显给我。我期待一个“完成”命令,但它却返回了我刚刚发送的数据。它在 Windows 超级终端上工作得很好,但这段代码不起作用。
我使用的是 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(string) 并且我还使用了 comport.writeline(string) 具有相同的结果。
此代码与普通超级终端之间的主要区别是什么,导致它们的行为不同?
I am using the C# SerialPort class to write to my COM port. Weird thing is that I can get data from the port just fine - it sends data that I am expecting. However, I cannot send any data to the port. Any data that I send is immediately echoed back to me as new data coming from the port. I am expecting a "Done" command but it instead gives me back the data I just sent. It works just fine from Windows HyperTerminal but this code just won't work.
I'm using 9600, 8-N-1 with no flow control.
I'm mostly using code from this article:
I instantiate my port with this
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();
And the write is just using comport.write(string) and I've also used comport.writeline(string) with the same result.
What is the main difference between this code and plain vanilla HyperTerminal that would cause them to act differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我偶然发现这个答案在许多代码示例中都没有。最重要的是,每次写入端口时都必须包含回车符。我正在使用:
但它应该是
你不会相信有多少代码示例未能在代码中包含它。我偶然发现了一个包含它的随机片段,这就是区别。
I stumbled across this answer that is not in many code example. The bottom line is that you have to include a carriage return with each port write. I was using:
But it should have been
You wouldn't believe how many code examples failed to have that in the code. I came across a random snippet that included it and that was the difference.