串行端口的读取线锁定 [英] Readline from Serial Port locks up

查看:18
本文介绍了串行端口的读取线锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从电子秤 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.

这篇关于串行端口的读取线锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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