C#,从串口输入一些数据?

时间:2015-11-07 16:21:44

标签: c# serial-port buffer

我使用以下代码从串口接收数据,但是我得到的数据有时间错过som值,例如当我发送ascii" 123456"通过Realterm程序到串口,它总是应该给我:

buffer[0]:49
buffer[1]:50
buffer[2]:51
buffer[3]:52
buffer[4]:53
buffer[5]:54

但有一段时间我得到了:

buffer[0]:51
buffer[1]:52
buffer[2]:53
buffer[3]:54

或:

buffer[0]:50

即使我以非常慢的顺序发送数据,也会发生这种情况?

    public Form1()
    {
        InitializeComponent();
        cmdClose.Enabled = false;
        foreach (String s in System.IO.Ports.SerialPort.GetPortNames())
        {
            txtPort.Items.Add(s);
        }
        txtPort.SelectedItem = "COM5";
        cmbbaudrate.SelectedItem = "115200";
        cmbparity.SelectedItem = "None";
        cmbdatabits.SelectedItem = "8";
        cmbstopbits.SelectedItem = "One";
    }

    public System.IO.Ports.SerialPort SP;
    public void serialport_connect(String port, int baudrate, Parity parity, int databits, StopBits stopbits)
    {
        DateTime dt = DateTime.Now;
        SP = new System.IO.Ports.SerialPort(port, baudrate, parity, databits, stopbits);

        try
        {
            SP.Open();
            SP.DataReceived += new SerialDataReceivedEventHandler(sport_DataReceived);
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
    }


    private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        TextBox.CheckForIllegalCrossThreadCalls = false;
        byte[] buffer = new byte[SP.BytesToRead];
        SP.Read(buffer, 0, buffer.Length);

        for (int i = 0; i < buffer.Length; i++)
        {
            Console.WriteLine("buffer[" +i +"]:" +buffer[i]);
            txtReceive.AppendText("buffer[" + i + "]:" + buffer[i] +"\n");
        }

    }

1 个答案:

答案 0 :(得分:0)

您可能需要查看ReadExisting方法。

  

“SerialPort类缓冲数据,但包含的流对象   SerialPort.BaseStream属性没有。因此,SerialPort   对象和流对象可能在字节数上有所不同   可供阅读。当字节缓冲到SerialPort时   对象,BytesToRead属性在其值中包含这些字节;   但是,包含的流可能无法访问这些字节   在BaseStream属性“

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx

我希望它有所帮助! :)