簡體   English   中英

如何同時讀寫串口?

[英]how to write and read to serialPort in same time?

我有一些設備需要使用SerialPort建立連接。 該設備從我這邊接收命令並向我發送數據。 我在同一類=>同一線程中進行所有發送/接收。

我已經連接到該設備,並且成功從該設備發送/接收命令和數據。

我需要每25毫秒發送一次命令之一是“給我您的狀態”-這意味着我要求設備發送回帶有數據的結構。

萬一我錯過了一些接收數據...當我做“ serialPortStream.BytesToRead”(測試是否有一些數據要獲取)時,我會在ByteReading上找到我還沒有找到的舊緩沖區嗎? 如果我錯過了需要讀取的最后一個包,或者我收到的新數據將刪除之前已經收到的舊數據,我將擁有多少個包?

使用將數據保存到ConcurrentQueue或類似對象的OnRecieveData處理程序。

namespace Test
{   class Program
    {
        const int bufSize = 2048;
        static void Main(string[] args)
        {

            Byte[] buf = new Byte[bufSize]; 
            SerialPort sp = new SerialPort("COM1", 115200);
            sp.DataReceived += port_OnReceiveData; // Add DataReceived Event Handler

            sp.Open();

            // Wait for data or user input to continue.
            Console.ReadLine();


            sp.Close();
        }

        private static void port_OnReceiveData(object sender,  SerialDataReceivedEventArgs e)
        {
            SerialPort port = (SerialPort) sender;
            switch(e.EventType)
            {
                case SerialData.Chars:
                {
                    Byte[] buf = new Byte[bufSize];
                    port.Read(buf, 0, bufSize)
                    Console.WriteLine("Recieved data! " + buf.ToString());
                    break;
                }
                case SerialData.Eof:
                {
                    // means receiving ended
                    break;
                }
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM