簡體   English   中英

從串行端口讀取和存儲字節

[英]Read and Store Bytes from Serial Port

我正在嘗試創建一個RS232應用程序,它讀取傳入的數據並將其存儲在緩沖區中。 我在RS232示例中找到了以下代碼,但我不確定如何使用它

* RS232示例port_DataReceived *

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (!comport.IsOpen) return;

        if (CurrentDataMode == DataMode.Text)
        {
            string data = comport.ReadExisting();

            LogIncoming(LogMsgType.Incoming, data + "\n");
        }
        else
        {
            int bytes = comport.BytesToRead;

            byte[] buffer = new byte[bytes];

            comport.Read(buffer, 0, bytes);

            LogIncoming(LogMsgType.Incoming, ByteArrayToHexString(buffer) + "\n");

        }
    }

我正在嘗試編寫另一個接收傳入字節數組並將其與另一個數組相結合的方法...請參閱下文:

private void ReadStoreArray()
{
   //Read response and store in buffer
   int bytes = comport.BytesToRead;
   byte[] respBuffer = new byte[bytes];
   comport.Read(respBuffer, 0, bytes);   

   //I want to take what is in the buffer and combine it with another array
   byte AddOn = {0x01, 0x02}
   byte Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

我目前在我的代碼中有兩種方法,因為我很困惑如何讀取和存儲傳入的字節到端口。 我可以在“ReadStoreArray”方法中使用“port_DataReceived”方法嗎? 我是否需要修改“ReadStoreArray”方法? 或者我應該重新開始?

創建SerialPort時:

SerialPort comport = new SerialPort("COM1");
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Shortened and error checking removed for brevity...
    if (!comport.IsOpen) return;
    int bytes = comport.BytesToRead;
    byte[] buffer = new byte[bytes];
    comport.Read(buffer, 0, bytes);
    HandleSerialData(buffer);
}

//private void ReadStoreArray(byte[] respBuffer)
private void HandleSerialData(byte[] respBuffer)
{
   //I want to take what is in the buffer and combine it with another array
   byte [] AddOn = {0x01, 0x02}
   byte [] Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

不要費心使用DataRecieve處理程序,這是非常不准確的,你最好開始一個不斷讀取串口並抓住每個字節的線程。

您無法從端口讀取相同的數據兩次。 您需要將其讀入緩沖區一次,然后共享緩沖區(作為函數參數傳遞)或克隆它以為每個函數提供自己的副本。

暫無
暫無

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

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