用缓冲区读取串口数据

时间:2018-11-07 12:01:16

标签: c# serial-port buffer

我想从串行端口读取数据并将其存储在buffer中。

我搜索了关于如何将其存储在缓冲区中的解决方案,但找不到。

以下是我到目前为止的程序。接收到的数据将被转换为十六进制。

所以现在我只需要缓冲部分起作用。

谢谢

static SerialPort myserialPort;
    static void Main(string[] args)
    {


       myserialPort = new SerialPort("COM8", 9600);

        myserialPort.DataReceived += new SerialDataReceivedEventHandler(myserialPort_DataReceived);

        try
        {
            myserialPort.Open();


        }

        catch 
        {

        }

        Console.WriteLine("Press enter to close...");  
        Console.ReadLine(); / this is just so i can hold the console open

    }

    private static void myserialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string bytestr = "";

        int numbytes = myserialPort.BytesToRead;
        byte[] rxbytearray = new byte[numbytes];

        for (int i = 0; i < numbytes; i++)
        {
            rxbytearray[i] = (byte)myserialPort.ReadByte();
        }

        string hexvalues = "";
        foreach (byte b in rxbytearray)
        {
            if (b != '\r')
                hexvalues = hexvalues + (b.ToString()) + " ";


        }       //  hexvalues = richTextBox1.Text;

        Console.WriteLine(hexvalues);

        //MessageBox.Show(hexvalues);



    }
}

}

0 个答案:

没有答案