Readline from Serial Port locks up(串行端口的读取线锁定)
问题描述
我正在尝试从电子秤 RS232 接口读取数据.它通过我无法获取的串行端口发送一个连续的 ASCII 字符串流.我只想获取它正在发送的一行数据.我想我假设我会使用 Readline 来获取数据,但是当我运行它时它只会锁定 PC.我认为它正在尝试获取所有数据并且在数据停止之前不会停止?这是我正在使用的代码:
I am trying to read data from a scale RS232 interface. It sends a continuous ASCII string stream through the Serial Port which I am having trouble getting. I just want to get one line of the data that it is sending out. I guess I assumed that I would use Readline to get the data, but it just locks up the PC when I run it. I think it is trying to get all of the data and won't stop until the data stops? Here is the code I'm using:
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
//opening the serial port
serialPort1.Open();
string str = serialPort1.ReadLine();
MessageBox.Show(str);
serialPort1.Close();
}
你能帮我确定如何只获取一行输出数据并关闭连接吗?
Can you help me to determine how to get just one line of the output data and close the connection?
推荐答案
SerialPort.ReadLine 被定义为阻止直到第一次出现 NewLine 值",其中 NewLine 默认为换行.您是否在流中发送换行符?请注意,换行符 (ASCII 0x0A) 与您可能发送的回车符 (ASCII 0x0D) 不同.
SerialPort.ReadLine is defined to block "up to the first occurrence of a NewLine value", where NewLine defaults to a line feed. Are you sending a linefeed in your stream? Note that a linefeed character (ASCII 0x0A) is different that a carriage return (ASCII 0x0D) that you might be sending.
如果需要,您可以重新定义 NewLine,或者如果行尾感觉不正确,您可以使用 SerialPort.ReadTo.您还可以设置 读取超时.
You can redefine the NewLine if needed, or if a line ending doesn't feel right, you can read up to a given string with SerialPort.ReadTo. You can also set a read timeout.
您可能更喜欢使用 SerialPort.Read 重载.
You might prefer to read a given number of bytes from the port, rather than a line, with one of the SerialPort.Read overloads.
如果这都不适用,请确保您实际上是在您认为的位置发送数据 - 调出 HyperTerminal/TeraTerm/您最喜欢的串行终端,使用与上面使用的相同的串行端口设置对其进行配置,并确保您看到您希望看到的数据.
If none of this applies, make sure that you're actually sending data where you think you are - bring up HyperTerminal/TeraTerm/your favorite serial terminal, configure it with the same serial port settings as you've used above, and make sure you see the data you expect to see.
这篇关于串行端口的读取线锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:串行端口的读取线锁定
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01