在c#中,我如何一次写两个字节的信号

本文关键字:两个 字节 信号 何一次 | 更新日期: 2023-09-27 18:19:02

我有b1和b2,它们都是字节,我使用串行端口。分别写信寄给他们。我可以同时寄吗?就像使用一个命令而不是两个。我现有的代码:

   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);
    }

在c#中,我如何一次写两个字节的信号

代替

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中合并两个数组