SerialPort WriteLine 命令的 C# 错误 [英] C# Errors with SerialPort WriteLine commands

查看:81
本文介绍了SerialPort WriteLine 命令的 C# 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# SerialPort 类来写入我的 COM 端口.奇怪的是,我可以很好地从端口获取数据 - 它发送我期望的数据.但是,我无法向端口发送任何数据.我发送的任何数据都会作为来自端口的新数据立即回显给我.我期待一个完成"命令,但它反而给了我我刚刚发送的数据.它在 Windows 超级终端上工作得很好,但这段代码不起作用.

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.

我使用的是没有流量控制的 9600、8-N-1.

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();

写入只是使用了 comport.write(string) 并且我也使用了 comport.writeline(string) 并得到了相同的结果.

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?

推荐答案

我偶然发现了许多代码示例中没有的答案.最重要的是,您必须在每个端口写入中包含一个回车符.我正在使用:

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:

comport.write(string)

但应该是

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

您不会相信有多少代码示例在代码中没有做到这一点.我偶然发现了一个包含它的随机片段,这就是不同之处.

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.

这篇关于SerialPort WriteLine 命令的 C# 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆