如何将字节数组发送到串行设备(C#)

时间:2016-06-29 08:16:16

标签: c# serial-port

我有一个串行设备,它向我发送一串ASCII十六进制代码(例如42 33)。然后我读了这些并使用它们来旋转校验和。一旦它们被旋转,我需要将它们发送回串行设备,包括一些控制字节。

我觉得我的代码可能过于复杂,我正在努力创建一种简洁的方法来构建一系列字节以发送回设备。

// Calculate Checksum
private byte[] calcChecksum(string checksum)
{
    // Create a byte array from checksum string
    byte[] byteArray = Encoding.ASCII.GetBytes(checksum);

    // Create Hex Characters from ASCII codes of byte array positions 5, 6.
    string left = ((char)byteArray[5]).ToString();
    string right = ((char)byteArray[6]).ToString();

    // Convert Hex Characters to Integer values used for the shifting
    int numLeft = Convert.ToByte(left, 16);
    int numRight = Convert.ToByte(right, 16);

    // Dummy checksum values to shift
    string cs = ShiftLeft(0x5232, numLeft).ToString("x4");
    string kw = ShiftRight(0xab23, numRight).ToString("x4");

    string cskw = cs + kw;

    byte[] checksumBytes = Encoding.ASCII.GetBytes(cskw);

    return checksumBytes;
}

// Communicate with Serial device
private void bChecksum_Click(object sender, EventArgs e)
{
    // Read string from device. Need a better way to create this
    // instead of using a richtext box. Okay for now but suggestions
    // welcome.
    returnCode = tbOutput.Text;
    byte[] checksumBytes = calcChecksum(returnCode);

    // Bytes I need to send to the device. Here I need to insert all the
    // checksumBytes Array values between 0x1B and 0x03
    byte[] bytesToSend = { 0x04, 0x02, 0x31, 0x30, 0x1B, ...array bytes..., 0x03 };
    _serialPort.Write(bytesToSend, 0, bytestosend.Length);
}

为了澄清我需要一种方法将checksumBytes数组插入到0x1B和0x03位置之间的bytesToSend数组中。

此外,欢迎任何代码改进。

1 个答案:

答案 0 :(得分:1)

如果我已正确理解您,那么您可以使用Array.CopyTo方法将3个数组合并在一起;             byte [] controlStart = {0x01,0x02,0x03};             byte [] checksumBytes = {0x04,0x05,0x06};             byte [] controlEnd = {0x07,0x08,0x09};

        byte[] bytesToSend = new byte[controlStart.Length + checksumBytes.Length + controlEnd.Length];

        controlStart.CopyTo(bytesToSend, 0);
        checksumBytes.CopyTo(bytesToSend, controlStart.Length);
        controlEnd.CopyTo(bytesToSend, controlStart.Length + checksumBytes.Length);