使用c#从串行端口通信器接收缓冲区数据的问题

本文关键字:缓冲区 数据 问题 串行端口 通信器 使用 | 更新日期: 2023-09-27 18:08:33

我通过RS232电缆连接的串口与机器通信。在传递凭据之后,如果机器的缓冲区存储为空(干净),我就可以作为客户端从机器获取数据。只要我关闭我的应用程序,数据就会进入机器的缓冲区存储,因为机器处于连续运行模式。在此之后,如果我试图通过启动应用程序并传递凭据以相同的方式获取数据,我不会从机器获得缓冲区以及实时数据。

现在,当我尝试通过将凭据传递到hyperterminal.exe并在我能够获得缓冲区以及实时数据后登录时,再次

所以我的问题是为什么我没有从程序中获得缓冲区数据当数据在缓冲区中时我们从Hyperterminal.exe

获得数据

我已经挣扎了很多寻找解决方案,但没有运气…

我请求请在这方面指导我。任何建议对我来说都是救命恩人。

这是我使用的代码…

        port1.RtsEnable = true;
        port1.DtrEnable = true;
        port1.PortName = "COM1";
        port1.BaudRate = 9600;
        port1.DataBits = 8;
        port1.Parity = System.IO.Ports.Parity.None;
        port1.StopBits = System.IO.Ports.StopBits.One;
        port1.Handshake = Handshake.RequestToSend;
        port1.Handshake = Handshake.RequestToSendXOnXOff;
        port1.Handshake = Handshake.None;
        port1.Handshake = Handshake.XOnXOff;
        port1.Open();
        port1.Write("Username'r'n");
        port1.Write("Password'r'n");
        port1.Write("Command'r'n");
        port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
    }
    public void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Thread.Sleep(500);
        while (port1.IsOpen)
        {
            //string s = port1.ReadExisting();
            string s = port1.ReadLine();
        }
        }

我已经使用ReadLine()以及ReadExisting(),但没有运气…

I/O代码. .

        public void getData() {
        byte[] buffersize = new byte[port1.ReadBufferSize];
        int bytesRead = port1.Read(buffersize, 0, buffersize.Length);
        byte[] buffer = new byte[bytesRead];
        File.AppendAllText(text, "Inside 1'r'n");
        Action kickoffRead = delegate
        {
            port1.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult ar)
            {
                try
                {
                    File.AppendAllText(text, "Inside 2'r'n");
                    int actualLength = port1.BaseStream.EndRead(ar);
                    byte[] received = new byte[actualLength];
                    Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
                    string mybuffer = "";
                    //ASCII data. 
                    mybuffer += Encoding.ASCII.GetString(received, 0, bytesRead);
                 }

我在登录凭据之后调用了这个方法…

使用c#从串行端口通信器接收缓冲区数据的问题

public void port1_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    //Initialize a buffer to hold the received data 
    byte[] buffer = new byte[port1.ReadBufferSize]; 
    //get the number of bytes read 
    int bytesRead = port1.Read(buffer, 0, buffer.Length); 
    //ASCII data. 
    mybuffer += Encoding.ASCII.GetString(buffer, 0, bytesRead);
    if(mybuffer.IndexOf(''r') > -1)
    {
        //Found a carriage return, do something with buffer?
    }
}

您将获得比特和碎片,因此您可能希望将其全部缓冲并查找返回字符(或您从另一端获得的任何终止符)以提取数据包。