簡體   English   中英

在C#中,如何一次寫入兩個字節的信號?

[英]In c# how do I write two byte signal in one time?

我有b1和b2都以字節為單位,我正在使用serialport.write分別發送它們。 我可以同時發送嗎? 就像使用一個命令而不是兩個一樣。 我現有的代碼:

   private void SConvert_Click(object sender, EventArgs e)
    {
        byte[] b1 = null, b2 = null;
        string[] coords = textBox1.Text.Split('\n');
        for (int i = 0; i <= coords.Length - 1; i++)
        {
            if (coords[i].Length > 0)
            {
                GetValue(coords[i], out b1, out b2);
            }
            if (serialPort.IsOpen)
            {
                serialPort.Write(b1, 0, 4);
                serialPort.Write(b2, 0, 4);
            }
        }

    }
    private void GetValue(string strValue, out byte[] b1, out byte[] b2)
    {
        string S1, S2, S = strValue;
        string[] x = S.Split(',');
        string y = x[0].ToString();//{lat=-36.123333          
        string z = x[1].ToString();//lng=174.333333}        // index outside bounds of the array
        S1 = y.Substring(y.IndexOf('=') + 1);
        string z1 = z.Replace("}", "0");                    // replace } by 0 since do not know length of }
        S2 = z1.Substring(z1.IndexOf('=') + 1);
        float f1 = float.Parse(S1), f2 = float.Parse(S2);
        b1 = System.BitConverter.GetBytes(f1);
        b2 = System.BitConverter.GetBytes(f2);
    }

代替

serialPort.Write(b1, 0, 4);
serialPort.Write(b2, 0, 4);

你可以做

serialPort.Write(b1.Concat(b2).ToArray(), 0, b1.Length + b2.Length);

我假設您想一次發送兩個字節數組。 解決方案很簡單:將它們合並,然后發送。

byte[] buf = new byte[b1.Length + b2.Length];
Array.Copy(buf, 0, b1);
Array.Copy(buf, 0, b2, b1.Length, b2.Length);
serialPort.Write(buf, 0, buf.Length);

另請參閱: 合並.NET中的兩個數組

暫無
暫無

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

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