从串行端口的ReadLine锁定了 [英] Readline from Serial Port locks up

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

问题描述

我试图从规模RS232接口读取数据。它会通过它我遇到麻烦串行端口一个连续的ASCII字符串流。我只是想获得它发送一个数据线。我猜我猜我会使用输入行来获取数据,但它只是锁定了电脑,当我运行它。我认为这是试图让所有的数据并不会停止,直到数据停止?下面是我使用的代码:

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 默认为换行。难道你发送的流中的换行?需要注意的是换行符(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.

如果需要,您可以重新换行,或者如果一条线的结局感觉不对,你可以阅读到给定的字符串的 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.

如果这一切都不适用,请确保你实际上发送,你觉得你的数据 - 打开超级终端/ 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.

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

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