简体   繁体   English

C#:等待从 RS485 发送的特定字符

[英]C#: Waiting for specific character sent from RS485

In my app I am sending data to microcontroller.在我的应用程序中,我将数据发送到微控制器。 I send data, microcontroller do program, and send character ("K").我发送数据,微控制器做程序,并发送字符(“K”)。 My application should wait for this character.After receiving this char, it should send data again.我的应用程序应该等待这个字符。收到这个字符后,它应该再次发送数据。

I got problem with receiving this character.我在接收这个角色时遇到了问题。 Is function BytesToRead right to reading character?函数 BytesToRead 是否有权读取字符? My program always fall when it reach this my function wait当我的程序到达这个我的功能等待时,它总是下降

static void wait()
    {
        SerialPort COMport = new SerialPort();
        int znak;

        COMport.PortName = "COM6"; // 
        COMport.BaudRate = 1200;
        COMport.DataBits = 8;
        COMport.Parity = Parity.None;
        COMport.StopBits = StopBits.One;

        COMport.Open();

        do
        {
            znak = COMport.BytesToRead;
        } while (znak != 75);   // ASCII K = 75

        COMport.Close();
        return;
    }

The BytesToRead property of the COMport returns the number of characters that have been received by the COMport so your loop will continue until there are exactly 75 characters read. COMport 的 BytesToRead 属性返回 COMport 已接收的字符数,因此您的循环将继续,直到读取了 75 个字符。 Take a look at the documentation for the SerialPort class.查看SerialPort类的文档。 It will show you a good example of how to read/write characters from/to your COMport.它将向您展示如何从/向您的 COMport 读/写字符的一个很好的例子。

为什么不直接使用while(COMport.ReadChar() != 'K') { /* Do Stuff */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM