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

时间:2014-06-12 15:25:42

标签: c# serial-port serial-communication

我通过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);
                 }

我刚刚在登录凭据后调用了这个方法......在收到数据时仍然没有运气......

1 个答案:

答案 0 :(得分:0)

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?
    }
}

你将得到点点滴滴,所以你可能想要缓冲它并查找返回字符(或从另一方获得的任何终止符)来提取数据包。